commit ed7bbae7354687877a0bb652696c21254e32a959
Author: MrJensK <jens.se@icloud.com>
AuthorDate: Wed Jul 29 20:50:32 2026 +0200
Commit: MrJensK <jens.se@icloud.com>
CommitDate: Wed Jul 29 20:50:32 2026 +0200
lots of updates
---
Makefile | 2 +-
README.md | 461 ++-
default_sxbarc | 211 +-
docs/wiki.html | 1127 +++++++
scripts/battery.sh | 50 +
scripts/bluetooth.sh | 27 +
scripts/brightness.sh | 20 +
scripts/clock.sh | 16 +
scripts/cpu.sh | 57 +
scripts/date.sh | 16 +
scripts/media.sh | 69 +
scripts/network.sh | 59 +
scripts/taskbar.sh | 41 +
scripts/usermenu.sh | 24 +
scripts/volume.sh | 22 +
src/defs.h | 69 +-
src/parser.c | 631 +++-
src/parser.h | 9 +
src/stb_image.h | 7988 +++++++++++++++++++++++++++++++++++++++++++++++++
src/sxbar.c | 943 ++++--
sxbar.1 | 491 +++
21 files changed, 11923 insertions(+), 410 deletions(-)
diff --git a/Makefile b/Makefile
index 9957087..a3ac88e 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
CC ?= gcc
CFLAGS ?= -std=c99 -Wall -Wextra -O3 -Isrc $(shell pkg-config --cflags xft 2>/dev/null || echo -I/usr/include/freetype2)
-LDFLAGS ?= -lX11 -lXinerama -lXft
+LDFLAGS ?= -lX11 -lXinerama -lXft -lm
PREFIX ?= /usr/local
BIN := sxbar
diff --git a/README.md b/README.md
index e175770..e384fa3 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,8 @@
# sxbar
The simple, yet powerful, status bar for Xorg.
+📖 **[Wiki](https://htmlpreview.github.io/?https://github.com/MrJensK/sxbar/blob/main/docs/wiki.html)** — full config reference with a searchable sidebar and worked examples for every directive ([source](docs/wiki.html)).
+
#FORK
## Improved Multi-Monitor Workspace Box Handling
@@ -570,7 +572,464 @@ popup_item : mymodule : "Restart" : "systemctl --user restart myservice"
popup_set : mymodule : "myservice-set-level"
```
+## Built-in module logic moved into scripts/, and popups on clock/date/battery
+
+Every built-in module's shell command used to be a string literal embedded
+in `init_modules()` -- some of them (cpu's `/proc/stat` sampling, network's
+interface detection) fairly long, gnarly awk/shell pipelines. This moves
+all of that logic into `scripts/`, one script per module, and adds popups
+to the three modules that didn't have one yet (`clock`, `date`, `battery`).
+
+### Changes
+- Added `resolve_script(name)` and `script_cmd(name, extra_arg)` (`src/sxbar.c`).
+ `resolve_script` checks, in order: the user's own edited copy at
+ `~/.config/sxbar/scripts/<name>.sh`, then the system copy `make install`
+ places at `/usr/local/share/sxbar/scripts/<name>.sh` (same fallback-path
+ convention as the config-file lookup in `parser.c`), or a harmless shell
+ no-op (`:`) if neither exists -- e.g. a freshly built, not-yet-installed
+ checkout. `script_cmd` appends a fixed (not user-controlled) extra
+ argument, used to reuse one script for two purposes -- see cpu below.
+- Every built-in module's `.command`, and every non-trivial popup row or
+ slider `set_command`, now resolves to a script instead of an embedded
+ string. Trivial single-command actions (`bluetoothctl power on`,
+ `systemctl suspend`, etc.) stay inline -- there's no logic in those worth
+ hiding in a file.
+- Modules whose bar text and popup content are closely related share one
+ script with subcommands, rather than one file per piece of output:
+ - `cpu.sh` -- `usage [PREFIX]` (bar text / usage popup row), `mem`,
+ `cores`
+ - `network.sh` -- `status` (bar text, default), `wifi`, `ethernet`
+ - `battery.sh` -- `capacity` (bar text, default), `status`,
+ `toggle-powersave`
+ - `volume.sh` / `brightness.sh` -- `get` (bar text/slider start,
+ default), `set VALUE`
+ - `bluetooth.sh` -- `status` (bar text, default), `pair`
+- New popups, matching the pattern the other six built-ins already use
+ (hover, no accidental triggering -- a click on a row is still required):
+ - `clock` / `date` -- "Open calendar" button (`gsimplecal`)
+ - `battery` -- a detailed status row (`upower`: state, time
+ remaining, health) plus a "Toggle power saver" button
+ (`power-profiles-daemon`), both opt-in extra tools beyond the
+ `/sys/class/power_supply` read the bar text itself uses
+
+### Result
+
+- `scripts/` now has exactly one file per built-in module (plus
+ `battery_icon.sh`/`volume_icon.sh` for `prefix_cmd` icons and
+ `demo_popup.sh` for the try-it-yourself popup) -- copy any of them to
+ `~/.config/sxbar/scripts/` and edit freely, same as the existing
+ `prefix_cmd` convention, without recompiling.
+- All nine built-in modules now have a popup.
+
+## Module-declared menus -- each built-in module's popup now lives in its own script
+
+The previous section moved bar-text/popup *commands* into `scripts/`, but
+each module's popup *content* (which rows it has, in what order) was still
+hardcoded in `init_modules()` (`src/sxbar.c`) -- e.g. `usermenu`'s
+Sleep/Log out/Shut down rows were three `add_popup_item()` calls at compile
+time, only reachable from sxbarc by overriding them wholesale via
+`popup_item`. This moves that content into the scripts themselves, so a
+built-in module's *entire* on-bar behaviour -- bar text and popup both --
+lives in one self-contained file, and sxbarc goes back to just turning
+modules on/off and tuning their refresh interval, as intended.
+
+### Changes
+- Every built-in module's script now supports a `menu` subcommand (e.g.
+ `usermenu.sh menu`). Run once at startup, it prints that module's popup
+ definition using the exact same `popup`/`popup_item`/`popup_info`/
+ `popup_set` directives sxbarc itself uses, just without the module-name
+ field -- a script only ever describes itself. Example
+ (`scripts/usermenu.sh menu`):
+ ```
+ popup : hover : buttons
+ popup_item : "Sleep" : "systemctl suspend"
+ popup_item : "Log out" : "pkill sxwm"
+ popup_item : "Shut down" : "systemctl poweroff"
+ ```
+- Added `load_popup_from_script(Module *m, const char *script_path)`
+ (`src/parser.c`, declared in `parser.h`): runs `<script_path> menu` and
+ feeds each line through the same directive parsing sxbarc's own
+ `popup`/`popup_item`/`popup_info`/`popup_set` lines use.
+- Refactored that parsing itself: the four directives' bodies (previously
+ duplicated between `parse_config()`'s sxbarc-line handling and
+ `init_modules()`'s compile-time-default helpers) are now the single
+ `apply_popup()`/`apply_popup_item()`/`apply_popup_info()`/
+ `apply_popup_set()` functions in `parser.c`, shared by both callers.
+- `init_modules()` (`src/sxbar.c`) shrank from one hardcoded struct
+ literal plus manual `add_popup_item`/`add_popup_info_item`/
+ `add_popup_slider_item` calls per module, to a single
+ `add_builtin_module(name, enabled, refresh_interval)` helper that
+ resolves the script and calls `load_popup_from_script`. The old
+ `add_popup_*`/`script_cmd` helpers are gone; nothing else used them.
+
+### Result
+- Adding a menu item to `usermenu` (or any other built-in module's popup)
+ is now a one-line edit to your own copy of that module's script under
+ `~/.config/sxbar/scripts/` -- no sxbarc editing, no recompiling.
+- sxbarc's `popup`/`popup_item`/`popup_info`/`popup_set` directives are
+ unchanged and still work exactly as before: the first `popup_item`/
+ `popup_info` line for a module still replaces its default rows (now
+ script-provided instead of compiled-in) and later lines still append,
+ so sxbarc can still override a script's menu wholesale if you'd rather
+ keep everything in one config file.
+- A custom module (`custom : name : "cmd" : interval`) has no script to
+ load a menu from, so this is a no-op for those -- give it a popup via
+ sxbarc's directives as before.
+
+## Popup images (album art), segmented button rows, and a media module
+
+Every popup row so far was text, a button or a slider, and every button
+row took the popup's full width -- nothing could render an actual image,
+and three related actions (previous/play-pause/next) meant three stacked
+full-width rows. This adds two new row types for that, and a new built-in
+`media` module (MPRIS controls via `playerctl`) to use both: its hover
+popup shows the current track's album art, track info, and glyph
+Previous/Play-Pause/Next buttons side by side on one row.
+
+### Changes
+- **No new runtime dependency.** Image decoding uses
+ [`stb_image.h`](https://github.com/nothings/stb) (`src/stb_image.h`,
+ public domain, vendored verbatim), compiled straight into the sxbar
+ binary via `#define STB_IMAGE_IMPLEMENTATION` in `src/sxbar.c` -- unlike
+ a full image-loading library (Imlib2 and similar), there's no extra
+ shared library or format-loader plugins installed on the system, and no
+ new `-dev` package needed to build. The only new link flag is `-lm`
+ (`Makefile`), for the `pow`/`ldexp` calls stb_image's decoders use.
+- New `POPUP_ROW_IMAGE` row type (`src/defs.h`). `PopupItem` gained
+ `image_command` (a shell command, re-run every popup open just like
+ `label_command` -- its stdout is a path to a local image file, or empty
+ for "no image this time"), plus `image` (an `XImage *`, opaque as
+ `void *` in `defs.h` so `parser.c` only ever touches `image_command`, a
+ plain string) and `image_w`/`image_h` (its current on-screen size).
+- New `popup_image : module_name : "command"` config directive
+ (`src/parser.c`), parsed the same way as `popup_info` -- including a
+ `menu`-subcommand form (`popup_image : "command"`, no name field) for
+ module scripts to use, and the same "first popup_item/popup_info/
+ popup_image line for a module clears its default rows" rule.
+- `popup_item_height()`/`popup_open()`/`popup_draw()` (`src/sxbar.c`)
+ handle the new row type. On open: the image row's command is re-run,
+ decoded via `stbi_load()`, and (if larger) downscaled to fit within a
+ `POPUP_IMAGE_SIZE` (160px) square, preserving aspect ratio, via a
+ hand-written box filter (`scale_image_rgba()` -- averages every source
+ pixel under each destination pixel, so shrinking a photo-sized image
+ down doesn't alias the way nearest-neighbour sampling would). The result
+ is packed into an `XImage` (`rgba_to_ximage()`), reading the *actual*
+ default visual's red/green/blue masks (`mask_shift()`/`mask_bits()`)
+ rather than assuming 24-bit TrueColor, so it renders correctly on any
+ visual depth. On draw: `XPutImage()` blits it onto the popup's pixmap,
+ centred, before the final `XCopyArea` blits everything to the window,
+ same as every other row. The previous `XImage` is freed
+ (`XDestroyImage()`) before loading a new one on each open, and on
+ program exit via `cleanup_modules()`.
+- New `POPUP_ROW_BUTTONS` row type (`src/defs.h`) for a row split into N
+ equal-width button segments side by side, instead of N stacked
+ full-width `POPUP_ROW_BUTTON` rows. `PopupItem` gained `buttons`/
+ `button_count` -- an array of `PopupButton { label, command }` pairs;
+ labels are static (no per-segment `label_command`, unlike TEXT rows).
+- New `popup_buttons : module_name : "Label1" : "cmd1" : "Label2" : "cmd2" ...`
+ config directive (`src/parser.c`, `apply_popup_buttons()`) -- an even
+ number of quoted label/command pairs, parsed the same
+ quote-then-`:`-then-quote way as the other directives (so a label or
+ command can itself contain a literal `:`). Same `menu`-subcommand form
+ and "first line clears default rows" rule as the other row directives.
+- `popup_open()`/`popup_draw()`/`popup_handle_button()`/`hdl_motion()`
+ (`src/sxbar.c`) handle the new row type: width is split evenly across
+ `button_count` segments (the last segment absorbs any leftover pixels
+ from integer division); click/hover hit-testing maps the pointer's X
+ position to a segment index (`popup.hover_col`, alongside the existing
+ `popup.hover_row`) instead of the whole row.
+- New `scripts/media.sh`, added as a tenth built-in module (`media`,
+ disabled by default): dispatches on subcommand, same convention as the
+ other module scripts --
+ - bar text (default): a play/pause glyph plus "Artist - Title" via
+ `playerctl metadata`/`status`; empty when no player is active.
+ - `track` -- "Artist - Title" undecorated, for a `popup_info` row.
+ - `art` -- resolves `playerctl metadata mpris:artUrl`: a `file://` URL
+ is used directly, an `http(s)://` one is downloaded once and cached
+ under `$XDG_CACHE_HOME/sxbar-media-art/<hash-of-url>` (needs `curl`;
+ silently produces no output if `curl` isn't installed, or the URL
+ isn't reachable) -- for a `popup_image` row.
+ - `prev`/`playpause`/`next` -- `playerctl previous`/`play-pause`/`next`,
+ spawned from the popup's step-backward/play/step-forward button
+ segments. These are Nerd Font glyphs (Font Awesome's `step_backward`/
+ `play`/`step_forward`, U+F048/U+F04B/U+F051) -- an earlier draft used
+ the plain Unicode media-control symbols (⏮/⏯/⏭) instead, on the theory
+ that they'd render without needing a patched font, but they turned out
+ to be missing from at least one real Nerd Font (JetBrainsMono Nerd
+ Font's own charset doesn't include that Unicode block, confirmed via
+ `fc-query`), while every Nerd Font is guaranteed to cover its own
+ Font Awesome icon set -- so Nerd Font glyphs are the safer default
+ given every other module's icon already assumes one.
+ - `menu` -- declares the popup (see below).
+- `default_sxbarc`: added `media` to the built-in module list, a
+ `popup_image`/`popup_info`/`popup_buttons` override example, and a note
+ on the older four-custom-module playerctl recipe pointing at this
+ instead.
+
+### `scripts/media.sh menu` output
+```
+popup : hover : buttons
+popup_image : "<path>/media.sh art"
+popup_info : "<path>/media.sh track"
+popup_buttons : "<step-backward>" : "<path>/media.sh prev" : "<play>" : "<path>/media.sh playpause" : "<step-forward>" : "<path>/media.sh next"
+```
+(the `<...>` labels above are the actual Nerd Font glyphs -- U+F048/
+U+F04B/U+F051 -- shown as placeholders here since they render as tofu in
+plain-text contexts without that font)
+
+### Result
+- `module : media : true : 2` gets album art, track info and transport
+ controls in one hover popup, with zero sxbarc configuration beyond
+ turning the module on -- consistent with every other built-in module's
+ self-contained-script model.
+- Build requirements are unchanged: still just Xlib/Xinerama/Xft (plus
+ libm, already present on any system with a C toolchain) -- no new
+ package to install to build or package sxbar.
+- Any other module -- built-in or custom -- can add its own image row via
+ `popup_image`, or its own segmented button row via `popup_buttons`
+ (e.g. a window/tag switcher, or paging controls), in sxbarc the same way.
+
+## Scrolling (marquee) text for unpredictable-length modules
+
+`width` (see "Fixed-width modules") reserves a *minimum* slot so short
+text doesn't cause shifting, but had no answer for the opposite problem:
+a module whose text can occasionally run very long (`media`'s
+"Artist - Title", for a long title) would just stretch the bar and shove
+everything after it sideways. This adds the opposite of `width`: a hard
+cap that overflowing text scrolls within instead.
+
+### Changes
+- `Module` (`src/defs.h`) gained `max_width` (0 = no cap, same convention
+ as `min_width`) and `scroll_offset` (the marquee's current scroll
+ position in pixels, persisted on the module so it keeps animating
+ smoothly across redraws).
+- New `max_width : module_name : max_pixels` config directive
+ (`src/parser.c`), parsed identically to the existing `width` directive.
+- `module_slot_width()` (`src/sxbar.c`) now caps a module's reserved slot
+ at `max_width` when set and the text overflows it, instead of growing
+ to fit -- this alone is what stops the bar from stretching; every
+ caller (layout, click hit-testing in `module_at_x()`) already goes
+ through this one function, so nothing else needed to change to keep
+ layout and clicks consistent.
+- New `draw_module_text()` (`src/sxbar.c`) replaces the plain
+ `XftDrawStringUtf8()` call at all three module-drawing sites
+ (left/center/right groups) in `draw_bar_into()`. Text that fits draws
+ exactly as before; text that overflows is clipped to `max_width` via
+ `XftDrawSetClipRectangles()` and drawn twice back to back (`"text "`
+ repeated) offset by `scroll_offset`, so the wrap-around reads as one
+ continuous ticker instead of jumping at the seam.
+- New `advance_marquees()` (`src/sxbar.c`): each call, advances
+ `scroll_offset` by a fixed step for every enabled module currently
+ overflowing its `max_width`, and reports whether any did.
+- `run()`'s main loop now calls `advance_marquees()` every ~100ms tick and
+ redraws immediately if it reports anything scrolling, independent of
+ the normal once-a-second `update_modules()`/redraw cadence -- a config
+ that never sets `max_width` sees zero behaviour change (the function's
+ a no-op, `advance_marquees()` always returns false), and only modules
+ actually mid-scroll get the faster redraw.
+
+### Result
+- `max_width : media : 220` (now in the default config's media example)
+ keeps a long "Artist - Title" scrolling smoothly inside a fixed-width
+ slot instead of pushing every module after it sideways every time the
+ track changes.
+- Applies to any module, built-in or custom -- e.g. a long window title
+ or commit message in a custom module's output.
+- No extra idle cost: sxbar only wakes up to redraw faster than once a
+ second while text is actually overflowing somewhere.
+
+## Popup text rows now cap to the popup's own width too
+
+The bar-level marquee above only covered a module's own text; a popup's
+rows had no equivalent, so a module like `media` with a long track title
+in its `popup_info` row would stretch the *popup* wider than its album
+art instead of scrolling -- the opposite of what album art is supposed to
+anchor. This extends the same marquee mechanism to popup rows, and bumps
+`POPUP_IMAGE_SIZE` up (120px -> 160px) since the art was the main reason
+to open the popup in the first place.
+
+### Changes
+- `PopupItem` (`src/defs.h`) gained `scroll_offset`, the same idea as a
+ `Module`'s but scoped to one popup row.
+- Factored the bar's marquee-drawing logic out into a shared
+ `draw_ticker(d, col, x, text_y, max_w, text, tw, offset)` (`src/sxbar.c`)
+ -- `draw_module_text()` (bar) is now a thin wrapper around it, and
+ popup rows call it directly with the popup's own width/offset.
+- `popup_open()` now first checks whether the module has an IMAGE,
+ SLIDER or BUTTONS row (an "anchor") -- if so, plain TEXT/BUTTON rows no
+ longer get to stretch the popup's width to fit their own text; if not
+ (e.g. `network`'s or `cpu`'s popups, which are plain informational
+ rows with nothing to anchor to), nothing changes, same as before.
+- `popup_draw()`'s TEXT/BUTTON row rendering goes through `draw_ticker()`
+ now instead of a plain `XftDrawStringUtf8()` call, clipped to the
+ popup's actual width -- a no-op when the text already fits (which,
+ absent an anchor row, it always does by construction).
+- New `advance_popup_marquee()`, the popup-scoped equivalent of
+ `advance_marquees()`: advances `scroll_offset` for any row of the
+ *currently open* popup that overflows, redraws the popup directly if
+ so (it's its own window, separate from the bars), and is called from
+ `run()`'s existing ~100ms tick.
+- Each row's `scroll_offset` resets to 0 in `popup_open()`, so a marquee
+ always restarts from the beginning on a fresh hover rather than picking
+ up wherever it left off last time.
+
+### Result
+- `media`'s popup is now exactly as wide as its album art (or the
+ transport-buttons row, whichever is wider); a long "Artist - Title"
+ scrolls within that width instead of widening the popup past the art.
+- Every other built-in popup (`network`, `cpu`, `battery`, ...) is
+ unaffected -- none of them has an IMAGE/SLIDER/BUTTONS row, so they
+ keep sizing to fit their text exactly as before.
+
+## Workspace icons
+
+The workspace switcher draws whatever text the window manager reports via
+`_NET_DESKTOP_NAMES` -- for most WMs (including sxwm) that's just plain
+numbers, `"1"`, `"2"`, `"3"`, .... There was no way to show something else
+there (e.g. Nerd Font glyphs) without renaming the actual desktops in the
+WM's own config, which most WMs don't even support past plain strings.
+
+### Changes
+- New `WorkspaceIcon { name, icon }` struct and `workspace_icons`/
+ `workspace_icon_count`/`workspace_icon_max` fields on `Config`
+ (`src/defs.h`).
+- New `workspace_icon : name : "icon text"` config directive
+ (`src/parser.c`), parsed the same quote-delimited way as `prefix`;
+ repeatable, growable array, same realloc-doubling pattern as
+ `grow_popup_items()`.
+- New `workspace_display_name(name)` (`src/sxbar.c`): looks `name` (the
+ WM-reported desktop name) up against the configured list and returns
+ its replacement text if there's a match, else `name` unchanged.
+- The three places that format a workspace's label into `" %s "` --
+ `draw_bar_into()`'s width-measuring pass, its drawing pass, and
+ `workspace_end_x()` (which mirrors the same layout math for click
+ hit-testing) -- all go through this lookup now instead of using `name`
+ directly.
+- New `ink_centered_x(origin_x, box_w, lead_w, inner)` (`src/sxbar.c`).
+ Some Nerd Font icon glyphs -- confirmed via `XftTextExtentsUtf8`, e.g.
+ JetBrainsMono Nerd Font's (non-Mono) globe/terminal/code icons all
+ report just an 8px advance width while their actual ink is 13-16px
+ wide and entirely right-shifted (0px left bearing, up to -8px "right
+ bearing") -- would otherwise render visibly off-center inside the
+ workspace pill's highlight box, which is sized from that same narrow
+ advance width.
+ A first version of this measured the extents of the whole
+ `" %s "`-padded label string directly and computed a shift from that --
+ which, for this same font, turned out to always come back as a no-op
+ (`XftTextExtentsUtf8()` reported the padded string's bounding box as
+ spanning its *entire* advance width regardless of where the inner
+ glyph's ink actually sat, silently zeroing out the correction for
+ exactly the glyphs that needed it most). Fixed by measuring `inner`
+ (the workspace name/icon alone, correctly asymmetric) instead, and
+ offsetting by the known width of the one leading padding space,
+ rather than trying to read the padded string's own (misleading)
+ extents. Verified this shifts each glyph's ink to within half a pixel
+ of the pill's true center (`code`: ink centered exactly; `1`: 12.5 vs.
+ a 12px middle).
+ Leaves the padded string's advance width itself (and therefore layout/
+ box sizing elsewhere) untouched -- only where within it we draw
+ shifts. Both of the workspace label's `XftDrawStringUtf8()` calls in
+ `draw_bar_into()` go through it now. A font's "Nerd Font Mono" variant
+ (if it has one) narrows the underlying advance/ink mismatch a lot on
+ its own (down to ~9px ink vs. 8px advance, for the same JetBrainsMono
+ example) but this fixes it in sxbar itself regardless of which
+ variant is configured.
+
+### Result
+- `workspace_icon : 1 : "<glyph>"` replaces "1"'s pill text with any
+ glyph from your Nerd Font, purely cosmetically -- switching still
+ targets the same underlying desktop number, only what's drawn changes.
+- Workspaces with no matching `workspace_icon` line keep showing their
+ plain name exactly as before -- this is opt-in per workspace.
+- Icon glyphs render centered in their pill even when the font's own
+ glyph metrics are asymmetric.
+
+## Taskbar
+
+Every module so far renders one line of its own text. This adds a module
+that doesn't: `taskbar` shows one clickable segment per window on the
+current workspace, so you can switch focus between them -- the motivating
+case being a window manager's monocle mode, where only one window is
+visible at a time and there was otherwise no way to reach the others from
+the bar. Typical setup is its own row on the secondary bar, directly
+beneath the primary status bar.
+
+### A dependency this actually needed patching a window manager for
+
+`wmctrl -i -a <id>` (window activation) works by sending a standard EWMH
+`_NET_ACTIVE_WINDOW` client message to the root window. Checking sxwm's
+own source (not just its advertised `_NET_SUPPORTED` list, which does
+list `_NET_ACTIVE_WINDOW`) showed `hdl_client_msg()` only ever handled
+`_NET_CURRENT_DESKTOP` and `_NET_WM_STATE` -- `_NET_ACTIVE_WINDOW` was
+published read-only (to reflect sxwm's own idea of focus) but nothing
+accepted external requests to change it, and sxwm has no other IPC
+(no socket, no FIFO, no signals) that could do it either. So this module
+needed a small sxwm patch first:
+`patches/net-active-window-mrjensk.patch` in the sxwm repo (also copied
+to `~/dotfiles/net-active-window.patch`, applied by `install.sh` right
+after the existing `cursor-dpi-fix.patch`) adds a `_NET_ACTIVE_WINDOW`
+branch to `hdl_client_msg()` that resolves the target window to its
+`Client` the same way the existing `_NET_WM_STATE` handler does
+(`find_client(find_toplevel(w))`), switches to that client's workspace
+first if needed (`change_workspace()`), and focuses/raises it via the
+existing `set_input_focus()` -- the same function `focus_next()`/
+`focus_prev()` already use, so monocle-mode raising and cursor warping
+behave identically to switching focus with a keybind. Verified the patch
+applies cleanly (byte-identical result) against a pristine checkout, and
+together with `cursor-dpi-fix.patch` in the order `install.sh` uses.
+
+### Changes
+- New `scripts/taskbar.sh`. Unlike every other built-in module's script,
+ its default/`list` output isn't bar text -- it's an internal wire
+ format, one line per current-workspace window: `"Title" : "0xID" :
+ "command"`, sourced from `wmctrl -l` filtered to whichever desktop
+ `wmctrl -d` marks current. `focus ID` runs `wmctrl -i -a ID`. `menu` is
+ an explicit no-op (`exit 0`): taskbar has no popup, so there's nothing
+ to declare, and without an explicit case it would otherwise fall
+ through to the listing logic.
+- New `TaskbarEntry { label, command, id }` struct and `taskbar_entries`/
+ `taskbar_entry_count` fields on `Module` (`src/defs.h`).
+ `taskbar` is registered as an 11th built-in module
+ (`add_builtin_module`, `src/sxbar.c`) the same way as any other.
+- New `update_taskbar()` (`src/sxbar.c`), called from `update_modules()`
+ instead of the normal run-command-into-cached_output path when
+ `m->name` is `"taskbar"`: runs the script with `list` appended and
+ parses each line via a small dedicated `parse_three_quoted()` (this is
+ an internal wire format, not a user-facing sxbarc directive, so it
+ doesn't reuse `parser.c`'s quote-parsing). Deliberately leaves
+ `m->cached_output` `NULL` -- every generic per-module code path
+ (`draw_bar_into()`'s layout/rendering loops, `module_at_x()`,
+ `advance_marquees()`) already skips modules with no `cached_output`,
+ which is exactly what's wanted: taskbar renders and handles clicks
+ through its own dedicated paths instead.
+- New dedicated block in `draw_bar_into()` (`src/sxbar.c`): finds the
+ taskbar module, computes the gap between wherever the left-aligned and
+ right-aligned module groups end (reusing `total_left`/`total_right`
+ already computed for those groups), and splits that gap into one
+ equal-width segment per window entry. Reads `_NET_ACTIVE_WINDOW` fresh
+ each draw and highlights the matching entry's segment the same way the
+ active workspace pill is highlighted. Ignores the module's own `align`
+ -- a fill module has no single anchor side.
+- New `taskbar_entry_at_x()` (`src/sxbar.c`), mirroring that block's
+ bounds/segment math for click hit-testing without any of the drawing
+ work -- same pattern `module_at_x()`/`workspace_end_x()` already use
+ for ordinary modules and the workspace switcher. Wired into
+ `hdl_button()`: when `module_at_x()` finds nothing (which it never
+ will for taskbar, since its `cached_output` is `NULL`), a left click
+ falls through to this instead, spawning the matched entry's command.
+
+### Result
+- `module : taskbar : true : 1` plus `bar : taskbar : secondary` (with
+ `secondary_bar : true`) gets a clickable per-window taskbar on its own
+ row, independent of the primary status bar.
+- Requires `wmctrl`, and (for the click to actually do anything) a WM
+ that honours `_NET_ACTIVE_WINDOW` requests -- for sxwm specifically,
+ that means the patch above.
+
## Disk footprint
-- `sxbar` is very lightweight: the compiled binary is about 36 KB.
+- `sxbar` is lightweight: the compiled binary is about 36 KB without
+ `popup_image`/`media` support, or roughly 220 KB with the vendored
+ `stb_image.h` decoder compiled in -- still just the one binary, no
+ extra shared library installed alongside it.
- The source tree is also small, so `sxbar` is ideal for minimal Xorg setups.
diff --git a/default_sxbarc b/default_sxbarc
index d0f111e..abdf555 100644
--- a/default_sxbarc
+++ b/default_sxbarc
@@ -31,12 +31,28 @@ border_colour : #005577
# font : Hack Nerd Font:size=10
font : monospace:size=8
+# Workspace icons -- replaces a workspace's displayed label (its
+# _NET_DESKTOP_NAMES string, as reported by your WM -- typically plain
+# numbers like "1", "2", "3") with different text instead, e.g. a Nerd
+# Font glyph. Needs a Nerd Font set via `font` above to render glyphs.
+# Purely cosmetic -- the underlying workspace name/number your WM uses
+# for switching is unaffected, only what's drawn on the pill changes.
+# workspace_icon : name : "icon text"
+#
+# Example (only meaningful with a Nerd Font -- pick glyphs from your
+# font's cheat sheet, e.g. https://www.nerdfonts.com/cheat-sheet):
+# workspace_icon : 1 : "" # globe
+# workspace_icon : 2 : "" # terminal
+# workspace_icon : 3 : "" # code
+
# Built-in modules
# module : name : enabled : refresh_interval_seconds
# Available: clock, date, battery, volume, cpu, brightness, bluetooth,
-# usermenu, network
+# usermenu, network, media, taskbar
+# clock/date: hover over either to reveal an "Open calendar" shortcut (needs gsimplecal)
module : clock : true : 1
module : date : true : 60
+# battery: hover over it for detailed status + a power-saver toggle (needs upower, power-profiles-daemon)
module : battery : false : 30
# volume: hover over it to reveal a slider (needs wpctl)
module : volume : true : 5
@@ -50,6 +66,14 @@ module : bluetooth : false : 10
module : usermenu : true : 300
# network: hover over it to reveal a floating menu showing WiFi/Ethernet + IPs (needs ip)
module : network : false : 10
+# media: hover over it to reveal album art + Previous/Play-Pause/Next (needs playerctl; curl for remote art)
+module : media : false : 2
+# taskbar: NOT like other modules -- renders one clickable segment per
+# window on the current workspace directly in the bar (see "Taskbar"
+# further down), instead of a single line of text. Needs wmctrl, and a
+# window manager that acts on _NET_ACTIVE_WINDOW client messages to
+# actually focus what you click.
+module : taskbar : false : 1
# Custom script modules (like polybar exec)
# Command must be quoted. Output is displayed in the bar.
@@ -97,6 +121,27 @@ module : network : false : 10
# Reference copies of these two scripts ship in this repo's scripts/ dir
# and are installed to $(PREFIX)/share/sxbar/scripts/ -- copy them to
# ~/.config/sxbar/scripts/ (the path above) and edit from there.
+#
+# The built-in modules' own bar text/popup commands work the same way,
+# under the hood: each resolves to a script in scripts/ (one per module --
+# cpu.sh, network.sh, battery.sh, volume.sh, brightness.sh, bluetooth.sh,
+# usermenu.sh, clock.sh, date.sh), checked in this order: your own copy at
+# ~/.config/sxbar/scripts/<name>.sh, then the installed system copy, else
+# a harmless no-op. Copy any of them over and edit -- no config line or
+# recompile needed, sxbar just picks up your copy on the next restart.
+#
+# Each of these scripts is also self-contained about its own popup menu:
+# running it as `<script> menu` (which sxbar does once at startup) prints
+# that module's popup/popup_item/popup_info/popup_set lines -- the exact
+# same directives as below, just without the module-name field, since a
+# script only ever describes itself. This is what usermenu.sh's Sleep/Log
+# out/Shut down rows are, for instance -- add, remove or edit rows there
+# to customize your user menu, no sxbarc editing needed. sxbarc's own
+# popup_item/popup_info/popup_set lines further down still work exactly as
+# before, and still replace a module's rows on the first line for that
+# module -- whether those rows came from the compiled-in fallback or a
+# script no longer matters, sxbarc always wins if you use it. See
+# "Floating popups" below for the full directive reference.
# Icon only -- hides a module's own text, showing just its prefix/icon.
# Needs a prefix/prefix_cmd set (see above) or there's nothing left to show.
@@ -122,6 +167,18 @@ module : network : false : 10
# width : volume : 48
# width : cpu : 48
+# Max width -- the opposite of width above: caps a module's slot at this
+# many pixels. Text that fits stays put; text wider than the cap scrolls
+# left (a marquee/ticker) within that fixed width instead of stretching
+# the bar -- handy for anything with unpredictable-length text, like
+# media's "Artist - Title". sxbar only redraws faster than its usual
+# once-a-second cadence while something is actually scrolling, so this
+# doesn't cost anything when nothing's overflowing.
+# max_width : module_name : max_pixels
+#
+# Example:
+# max_width : media : 220
+
# Bar assignment -- which bar a module is drawn on when secondary_bar is
# enabled above. Defaults to primary; only needs setting for modules you
# want to move to the secondary bar. The secondary bar has no workspace
@@ -135,6 +192,30 @@ module : network : false : 10
# bar : volume : secondary
# bar : cpu : secondary
+# Taskbar -- one clickable, equal-width segment per window on the current
+# workspace, so you can switch focus between them (e.g. while a window
+# manager's monocle/fullscreen-stack mode only shows one window at a
+# time). Unlike every other module, it doesn't have a single line of bar
+# text: it renders directly in the bar itself, filling whatever space is
+# left over between the left- and right-aligned modules on whichever bar
+# it's assigned to (its own `align` is ignored -- it's a fill module, not
+# anchored to one side). The currently-focused window's segment is
+# highlighted the same way the active workspace pill is.
+#
+# Needs:
+# - wmctrl, for both listing windows and requesting focus
+# - a window manager that actually acts on a _NET_ACTIVE_WINDOW client
+# message (that's what wmctrl sends to request focus) -- sxwm as of
+# this writing does not out of the box; see
+# patches/net-active-window-mrjensk.patch in the sxwm repo, or your
+# WM's own docs if you're not on sxwm
+#
+# Typical setup: its own row on the secondary bar, so it reads like an
+# actual taskbar underneath the primary status bar.
+# secondary_bar : true
+# module : taskbar : true : 1
+# bar : taskbar : secondary
+
# Alignment -- which side of the bar a module is anchored to. Defaults to
# right, so existing configs (which never set this) are unaffected. Each
# group (left/center/right) is laid out independently -- left continues on
@@ -181,14 +262,18 @@ module : network : false : 10
# Floating popups -- a module can open a small floating window instead of
# (or as well as) running a plain click_command. A popup is just a list of
-# rows, and text/button/slider rows can all be freely mixed in the same
-# popup (see demo_menu below for an example combining all three). Either
-# trigger works with any row -- every built-in popup below defaults to
-# `hover` for a consistent feel, but `click` remains available if you'd
-# rather a menu only appear on a deliberate click:
-# text -- purely informational, not clickable at all (popup_info)
-# button -- runs its own command and closes the popup on click (popup_item)
-# slider -- a draggable 0-100% track; dragging doesn't close the popup (popup_set)
+# rows, and text/button/slider/image rows can all be freely mixed in the
+# same popup (see demo_menu below for an example combining the first
+# three). Either trigger works with any row -- every built-in popup below
+# defaults to `hover` for a consistent feel, but `click` remains available
+# if you'd rather a menu only appear on a deliberate click:
+# text -- purely informational, not clickable at all (popup_info)
+# button -- runs its own command and closes the popup on click (popup_item)
+# slider -- a draggable 0-100% track; dragging doesn't close the popup (popup_set)
+# image -- renders an image file, e.g. album art; not clickable (popup_image)
+# buttons -- one row split into N equal-width button segments side by
+# side, e.g. media transport controls, instead of N stacked
+# full-width button rows (popup_buttons)
#
# popup : module_name : hover|click : buttons|slider
# hover opens the popup while the pointer is over the module (and closes
@@ -196,49 +281,92 @@ module : network : false : 10
# it on left-click and closes it again on a second click, on clicking a
# button row, or on clicking anywhere else (like an ordinary dropdown
# menu). The third field only decides "does this module have a popup at
-# all" these days -- popup_item/popup_info/popup_set decide what's in it,
-# in any combination, regardless of which of `buttons`/`slider` you put
-# here, so either word works.
+# all" these days -- popup_item/popup_info/popup_image/popup_buttons/
+# popup_set decide what's in it, in any combination, regardless of which
+# of `buttons`/`slider` you put here, so either word works.
#
# popup_item : module_name : "Label" : "command" -- one button row.
-# Repeat for more rows. The first popup_item/popup_info line for a module
-# replaces its built-in default rows (if any, including a popup_set
-# slider row); later lines append to it. Add popup_set again afterwards
-# if you cleared a built-in slider this way and still want it back.
+# Repeat for more rows. The first popup_item/popup_info/popup_image/
+# popup_buttons line for a module replaces its built-in default rows (if
+# any, including a popup_set slider row); later lines append to it. Add
+# popup_set again afterwards if you cleared a built-in slider this way
+# and still want it back.
#
# popup_info : module_name : "shell command" -- one plain text row. Its
# label is this command's output, re-run fresh every time the popup
# opens (e.g. current IP address). Not clickable at all -- clicking it
# does nothing and the popup stays open.
#
+# popup_image : module_name : "shell command" -- one image row. The
+# command's stdout is a path to a local image file, re-run fresh every
+# time the popup opens (e.g. current track's album art); scaled to fit a
+# 160px box, preserving aspect ratio. Empty/failed output just means no
+# image that time -- the row stays, it renders blank. Not clickable.
+# No extra build dependency -- image decoding is a vendored, compiled-in
+# library (see README). An image (or slider, or buttons) row anchors
+# the popup's width -- any popup_info/popup_item text in the same popup
+# is then capped to that width and scrolls (marquee) if it's longer,
+# instead of stretching the popup past the image.
+#
+# popup_buttons : module_name : "Label1" : "cmd1" : "Label2" : "cmd2" ...
+# one row split into N equal-width button segments, each running its own
+# command and closing the popup on click -- same behaviour as popup_item
+# but laid out side by side instead of stacked. Needs an even number of
+# quoted label/command pairs; glyphs work well as labels here (see the
+# media example below) so you get an icon row instead of stacked text.
+#
# popup_set : module_name : "command" -- adds (or updates) one slider row
# for this module. Run when the value changes; receives the new value as
# $1, e.g. "45%" (same convention as prefix_cmd's $1). The slider's
# starting position comes from the module's own command output, so no
-# separate "get" command is needed. Can coexist with popup_item/popup_info
-# rows on the same module.
+# separate "get" command is needed. Can coexist with popup_item/popup_info/
+# popup_image/popup_buttons rows on the same module.
#
-# brightness, volume, cpu, bluetooth, usermenu and network below already
-# come with sensible defaults built in (see README) -- these directives are
-# for overriding them or adding this behaviour to your own custom modules.
-# Want click instead of hover for one of them? Just override its trigger,
-# e.g. `popup : usermenu : click : buttons`.
+# All ten built-in modules below already come with sensible popup
+# defaults built in (see README) -- these directives are for overriding
+# them or adding this behaviour to your own custom modules. Want click
+# instead of hover for one of them? Just override its trigger, e.g.
+# `popup : usermenu : click : buttons`.
#
-# Examples (already the defaults for these -- shown for reference):
-# popup : cpu : hover : buttons
-# popup_info : cpu : "{ grep -m1 '^cpu ' /proc/stat; sleep 0.2; grep -m1 '^cpu ' /proc/stat; } | LC_ALL=C awk 'NR==1{for(i=2;i<=8;i++)t1+=$i; d1=$5+$6} NR==2{for(i=2;i<=8;i++)t2+=$i; d2=$5+$6; d=t2-t1; printf \"CPU: %d%%\n\", (d>0 ? (1-(d2-d1)/d)*100 : 0)}'"
-# popup_info : cpu : "LC_ALL=C free -h | awk '/^Mem:/{print \"Mem: \" $3\"/\"$2}'"
+# The built-in modules' own commands (bar text, popup rows, slider
+# set-commands) all resolve to a script under scripts/ -- one script per
+# module, dispatched by subcommand where a module needs more than one
+# piece of output (e.g. cpu.sh handles bar text, its usage/mem/cores
+# popup rows). Copy any of them to ~/.config/sxbar/scripts/ and edit
+# freely, same as prefix_cmd scripts -- see README for the full list.
#
-# popup : brightness : hover : slider
-# popup_set : brightness : "brightnessctl set"
+# Examples (these already match each module's own script default -- see
+# "Built-in modules" further up -- so uncommenting one as-is changes
+# nothing; they're here as a starting point to override from, e.g. to
+# reorder rows, add more, or point usermenu's "Log out" at your own
+# WM/session. Paths assume you've copied the scripts to
+# ~/.config/sxbar/scripts/, same as the prefix_cmd examples above):
+# popup : clock : hover : buttons
+# popup_item : clock : "Open calendar" : "gsimplecal"
+#
+# popup : date : hover : buttons
+# popup_item : date : "Open calendar" : "gsimplecal"
+#
+# popup : battery : hover : buttons
+# popup_info : battery : "~/.config/sxbar/scripts/battery.sh status"
+# popup_item : battery : "Toggle power saver" : "~/.config/sxbar/scripts/battery.sh toggle-powersave"
#
# popup : volume : hover : slider
-# popup_set : volume : "wpctl set-volume @DEFAULT_AUDIO_SINK@"
+# popup_set : volume : "~/.config/sxbar/scripts/volume.sh set"
+#
+# popup : cpu : hover : buttons
+# popup_info : cpu : "~/.config/sxbar/scripts/cpu.sh usage 'CPU: '"
+# popup_info : cpu : "~/.config/sxbar/scripts/cpu.sh mem"
+# popup_info : cpu : "~/.config/sxbar/scripts/cpu.sh cores"
+#
+# popup : brightness : hover : slider
+# popup_set : brightness : "~/.config/sxbar/scripts/brightness.sh set"
#
# popup : bluetooth : hover : buttons
-# popup_item : bluetooth : "Turn on" : "bluetoothctl power on"
-# popup_item : bluetooth : "Turn off" : "bluetoothctl power off"
-# popup_item : bluetooth : "Search for devices" : "bluetoothctl --timeout 10 scan on"
+# popup_item : bluetooth : "Turn on" : "bluetoothctl power on"
+# popup_item : bluetooth : "Turn off" : "bluetoothctl power off"
+# popup_item : bluetooth : "Search for devices" : "bluetoothctl --timeout 10 scan on"
+# popup_item : bluetooth : "Pair last found device" : "~/.config/sxbar/scripts/bluetooth.sh pair"
#
# popup : usermenu : hover : buttons
# popup_item : usermenu : "Sleep" : "systemctl suspend"
@@ -246,8 +374,13 @@ module : network : false : 10
# popup_item : usermenu : "Shut down" : "systemctl poweroff"
#
# popup : network : hover : buttons
-# popup_info : network : "i=$(for d in /sys/class/net/*/wireless; do [ -d \"$d\" ] && basename \"$(dirname \"$d\")\" && break; done); if [ -z \"$i\" ]; then echo 'WiFi: none'; else ip=$(ip -4 -o addr show \"$i\" 2>/dev/null | awk '{print $4}' | cut -d/ -f1); [ -n \"$ip\" ] && echo \"WiFi ($i): $ip\" || echo \"WiFi ($i): disconnected\"; fi"
-# popup_info : network : "i=$(for d in /sys/class/net/*; do n=$(basename \"$d\"); case \"$n\" in lo|docker*|veth*|br-*|virbr*|tun*|tap*) continue;; esac; [ -d \"$d/wireless\" ] && continue; [ \"$(cat \"$d/type\" 2>/dev/null)\" = \"1\" ] && echo \"$n\" && break; done); if [ -z \"$i\" ]; then echo 'Ethernet: none'; else ip=$(ip -4 -o addr show \"$i\" 2>/dev/null | awk '{print $4}' | cut -d/ -f1); [ -n \"$ip\" ] && echo \"Ethernet ($i): $ip\" || echo \"Ethernet ($i): disconnected\"; fi"
+# popup_info : network : "~/.config/sxbar/scripts/network.sh wifi"
+# popup_info : network : "~/.config/sxbar/scripts/network.sh ethernet"
+#
+# popup : media : hover : buttons
+# popup_image : media : "~/.config/sxbar/scripts/media.sh art" # album art (needs playerctl; curl for remote art)
+# popup_info : media : "~/.config/sxbar/scripts/media.sh track"
+# popup_buttons : media : "" : "~/.config/sxbar/scripts/media.sh prev" : "" : "~/.config/sxbar/scripts/media.sh playpause" : "" : "~/.config/sxbar/scripts/media.sh next"
# Try-it-yourself demo popup -- a throwaway custom module combining all
# three row kinds in one popup, so you can test hover/click/drag mechanics
@@ -265,6 +398,14 @@ module : network : false : 10
# popup_set : demo_menu : "~/.config/sxbar/scripts/demo_popup.sh"
# Media controller example (requires playerctl)
+#
+# There's now a built-in `media` module (see "Built-in modules" above and
+# scripts/media.sh) with a hover popup showing album art, track info, and
+# Previous/Play-Pause/Next buttons -- `module : media : true : 2` is
+# usually the easier route. The four-segment custom-module version below
+# is still here for anyone who wants transport controls always visible
+# directly in the bar instead, with no popup involved.
+#
# playerctl uses the MPRIS2 protocol and works with most players automatically:
# Firefox (YouTube, Spotify Web), Spotify, VLC, mpv, rhythmbox, etc.
# It will control whichever player was most recently active.
diff --git a/docs/wiki.html b/docs/wiki.html
new file mode 100644
index 0000000..f634ee9
--- /dev/null
+++ b/docs/wiki.html
@@ -0,0 +1,1127 @@
+<title>sxbar — wiki</title>
+<style>
+ :root {
+ --bg: #f3f5f8;
+ --surface: #ffffff;
+ --surface2: #e9edf3;
+ --ink: #1a2029;
+ --muted: #5b6472;
+ --accent: #a8690a;
+ --accent2: #257587;
+ --border: rgba(20,30,45,0.11);
+ --code-ink: #2b3140;
+ --red: #b3372c;
+ --green: #2f7d4f;
+
+ --mono: "JetBrains Mono", ui-monospace, "SF Mono", "Cascadia Code", "Fira Code", Consolas, monospace;
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
+
+ --fs-3xl: clamp(1.9rem, 1.5rem + 1.6vw, 2.6rem);
+ --fs-2xl: 1.75rem;
+ --fs-xl: 1.375rem;
+ --fs-lg: 1.0625rem;
+ --fs-base: 1rem;
+ --fs-sm: 0.875rem;
+ --fs-xs: 0.75rem;
+ }
+
+ @media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #12151c;
+ --surface: #1a1e27;
+ --surface2: #21262f;
+ --ink: #e4e9f0;
+ --muted: #8b93a3;
+ --accent: #e8a33d;
+ --accent2: #6fb3c2;
+ --border: rgba(255,255,255,0.09);
+ --code-ink: #d7dde6;
+ --red: #e0685c;
+ --green: #6fce93;
+ }
+ }
+ :root[data-theme="dark"] {
+ --bg: #12151c;
+ --surface: #1a1e27;
+ --surface2: #21262f;
+ --ink: #e4e9f0;
+ --muted: #8b93a3;
+ --accent: #e8a33d;
+ --accent2: #6fb3c2;
+ --border: rgba(255,255,255,0.09);
+ --code-ink: #d7dde6;
+ --red: #e0685c;
+ --green: #6fce93;
+ }
+ :root[data-theme="light"] {
+ --bg: #f3f5f8;
+ --surface: #ffffff;
+ --surface2: #e9edf3;
+ --ink: #1a2029;
+ --muted: #5b6472;
+ --accent: #a8690a;
+ --accent2: #257587;
+ --border: rgba(20,30,45,0.11);
+ --code-ink: #2b3140;
+ --red: #b3372c;
+ --green: #2f7d4f;
+ }
+
+ * { box-sizing: border-box; }
+ html { scroll-behavior: smooth; }
+ @media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
+
+ body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--ink);
+ font-family: var(--sans);
+ font-size: var(--fs-base);
+ line-height: 1.65;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ a { color: var(--accent2); text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ a:focus-visible, button:focus-visible, summary:focus-visible {
+ outline: 2px solid var(--accent2);
+ outline-offset: 2px;
+ border-radius: 2px;
+ }
+
+ h1, h2, h3, h4 {
+ font-family: var(--mono);
+ font-weight: 700;
+ text-wrap: balance;
+ letter-spacing: -0.01em;
+ color: var(--ink);
+ }
+
+ code, kbd, .mono { font-family: var(--mono); }
+
+ /* ---------- fake status-bar hero mockup ---------- */
+ .barmock {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ background: #000;
+ color: #7abccd;
+ font-family: var(--mono);
+ font-size: 0.8125rem;
+ padding: 7px 14px;
+ border-bottom: 1px solid var(--border);
+ }
+ .barmock .ws { display: flex; gap: 6px; }
+ .barmock .ws span {
+ padding: 2px 8px;
+ border-radius: 2px;
+ color: #7abccd;
+ }
+ .barmock .ws span.active { background: #7abccd; color: #000; }
+ .barmock .clock { color: #50fa7b; }
+ .barmock .spacer { flex: 1; }
+ .barmock .mods { display: flex; gap: 16px; }
+ .barmock .mods .bat { color: #ffb86c; }
+ .barmock .mods .vol { color: #ff79c6; }
+ .barmock .mods .cpu { color: #bd93f9; }
+ .barmock .mods .bt { color: #4a9eff; }
+ .barmock .mods .net { color: #2ee6d6; }
+ .barmock .ver { color: #444; padding-left: 6px; }
+
+ /* ---------- shell layout ---------- */
+ .shell {
+ display: grid;
+ grid-template-columns: 250px minmax(0, 1fr);
+ max-width: 1180px;
+ margin: 0 auto;
+ }
+ @media (max-width: 880px) {
+ .shell { grid-template-columns: 1fr; }
+ }
+
+ nav.toc {
+ position: sticky;
+ top: 0;
+ align-self: start;
+ height: 100vh;
+ overflow-y: auto;
+ padding: 28px 18px 40px 24px;
+ border-right: 1px solid var(--border);
+ font-family: var(--mono);
+ font-size: 0.8125rem;
+ }
+ @media (max-width: 880px) {
+ nav.toc {
+ position: static;
+ height: auto;
+ border-right: none;
+ border-bottom: 1px solid var(--border);
+ padding: 18px 20px;
+ }
+ }
+ nav.toc .brand {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+ margin-bottom: 22px;
+ }
+ nav.toc .brand strong { font-size: 1rem; }
+ nav.toc .brand span { color: var(--muted); font-size: var(--fs-xs); }
+ nav.toc .group { margin-bottom: 20px; }
+ nav.toc .group h4 {
+ font-size: var(--fs-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: var(--muted);
+ margin: 0 0 8px;
+ font-weight: 600;
+ }
+ nav.toc ul { list-style: none; margin: 0; padding: 0; }
+ nav.toc li { margin: 0; }
+ nav.toc a {
+ display: block;
+ color: var(--ink);
+ padding: 5px 8px;
+ margin: 0 -8px;
+ border-radius: 4px;
+ opacity: 0.72;
+ }
+ nav.toc a:hover { opacity: 1; background: var(--surface2); text-decoration: none; }
+ nav.toc a.active { opacity: 1; color: var(--accent); background: var(--surface2); }
+
+ main {
+ padding: 40px clamp(20px, 4vw, 56px) 100px;
+ min-width: 0;
+ }
+
+ .tagline {
+ color: var(--muted);
+ font-size: var(--fs-lg);
+ max-width: 62ch;
+ margin: 14px 0 0;
+ }
+ .toprow {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ flex-wrap: wrap;
+ }
+ .badges { display: flex; gap: 8px; flex-wrap: wrap; }
+ .badge {
+ font-family: var(--mono);
+ font-size: var(--fs-xs);
+ padding: 3px 9px;
+ border-radius: 20px;
+ border: 1px solid var(--border);
+ color: var(--muted);
+ }
+
+ section {
+ margin-top: 64px;
+ scroll-margin-top: 20px;
+ }
+ section h2 {
+ font-size: var(--fs-2xl);
+ margin: 0 0 6px;
+ padding-bottom: 12px;
+ border-bottom: 1px solid var(--border);
+ }
+ section > .lede {
+ color: var(--muted);
+ max-width: 68ch;
+ margin: 14px 0 26px;
+ }
+ h3 {
+ font-size: var(--fs-xl);
+ margin: 36px 0 10px;
+ }
+ h4 {
+ font-size: var(--fs-lg);
+ margin: 22px 0 8px;
+ }
+ p { max-width: 70ch; }
+ .eyebrow {
+ font-family: var(--mono);
+ font-size: var(--fs-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.09em;
+ color: var(--accent);
+ font-weight: 700;
+ margin: 0 0 8px;
+ }
+
+ /* ---------- code blocks ---------- */
+ pre {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 14px 16px;
+ overflow-x: auto;
+ font-family: var(--mono);
+ font-size: 0.8125rem;
+ line-height: 1.6;
+ color: var(--code-ink);
+ margin: 12px 0 20px;
+ }
+ pre .k { color: var(--accent); } /* directive keyword */
+ pre .s { color: var(--green); } /* quoted string */
+ pre .c { color: var(--muted); font-style: italic; } /* comment */
+ pre .v { color: var(--accent2); } /* value */
+ code.inline {
+ background: var(--surface2);
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 0.1em 0.4em;
+ font-size: 0.875em;
+ color: var(--code-ink);
+ white-space: nowrap;
+ }
+
+ /* ---------- tables ---------- */
+ .twrap { overflow-x: auto; margin: 16px 0 24px; }
+ table {
+ border-collapse: collapse;
+ width: 100%;
+ min-width: 560px;
+ font-size: var(--fs-sm);
+ }
+ th, td {
+ text-align: left;
+ padding: 9px 14px;
+ border-bottom: 1px solid var(--border);
+ vertical-align: top;
+ }
+ th {
+ font-family: var(--mono);
+ font-size: var(--fs-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--muted);
+ font-weight: 600;
+ }
+ td.mono, th.mono { font-family: var(--mono); }
+ td code.inline { white-space: normal; }
+ tr:last-child td { border-bottom: none; }
+ .pill {
+ display: inline-block;
+ font-family: var(--mono);
+ font-size: var(--fs-xs);
+ padding: 2px 8px;
+ border-radius: 20px;
+ }
+ .pill.on { background: color-mix(in srgb, var(--green) 18%, transparent); color: var(--green); }
+ .pill.off { background: var(--surface2); color: var(--muted); }
+ .pill.req { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); }
+
+ /* ---------- cards / row-type grid ---------- */
+ .grid3 {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
+ gap: 14px;
+ margin: 18px 0 26px;
+ }
+ .card {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 16px 18px;
+ }
+ .card .eyebrow { margin-bottom: 6px; }
+ .card p { margin: 0; font-size: var(--fs-sm); color: var(--muted); }
+ .card h4 { margin: 0 0 6px; font-size: var(--fs-base); }
+
+ .note {
+ border-left: 3px solid var(--accent2);
+ background: color-mix(in srgb, var(--accent2) 8%, transparent);
+ padding: 10px 16px;
+ border-radius: 0 8px 8px 0;
+ font-size: var(--fs-sm);
+ margin: 16px 0;
+ max-width: 70ch;
+ }
+ .note strong { color: var(--accent2); }
+
+ footer {
+ border-top: 1px solid var(--border);
+ margin-top: 70px;
+ padding: 28px clamp(20px, 4vw, 56px);
+ color: var(--muted);
+ font-size: var(--fs-sm);
+ grid-column: 2;
+ }
+ @media (max-width: 880px) { footer { grid-column: 1; } }
+
+ ::selection { background: color-mix(in srgb, var(--accent) 35%, transparent); }
+
+ .toggle-theme {
+ font-family: var(--mono);
+ font-size: var(--fs-xs);
+ background: var(--surface2);
+ border: 1px solid var(--border);
+ color: var(--ink);
+ border-radius: 20px;
+ padding: 5px 12px;
+ cursor: pointer;
+ }
+</style>
+
+<div class="barmock" aria-hidden="true">
+ <div class="ws"><span class="active">1</span><span>2</span><span>3</span></div>
+ <span class="clock"> 14:32:07</span>
+ <div class="spacer"></div>
+ <div class="mods">
+ <span class="bat"> 83%</span>
+ <span class="vol"> 47%</span>
+ <span class="cpu"> 22%</span>
+ <span class="bt"> On</span>
+ <span class="net"> wlp2s0</span>
+ </div>
+ <span class="ver">sxbar ver. 1.1</span>
+</div>
+
+<div class="shell">
+ <nav class="toc" id="toc">
+ <div class="brand">
+ <strong>sxbar</strong>
+ <span>wiki</span>
+ </div>
+
+ <div class="group">
+ <h4>Get started</h4>
+ <ul>
+ <li><a href="#overview">Overview</a></li>
+ <li><a href="#install">Install & build</a></li>
+ <li><a href="#quickstart">Quick start</a></li>
+ </ul>
+ </div>
+
+ <div class="group">
+ <h4>Appearance</h4>
+ <ul>
+ <li><a href="#bars">Global & bar options</a></li>
+ <li><a href="#workspaces">Workspaces & monitors</a></li>
+ </ul>
+ </div>
+
+ <div class="group">
+ <h4>Modules</h4>
+ <ul>
+ <li><a href="#modules">Built-in modules</a></li>
+ <li><a href="#taskbar">Taskbar</a></li>
+ <li><a href="#custom">Custom modules & scripts</a></li>
+ <li><a href="#customize">Icons, colour, layout, clicks</a></li>
+ </ul>
+ </div>
+
+ <div class="group">
+ <h4>Floating popups</h4>
+ <ul>
+ <li><a href="#popups">Concept & triggers</a></li>
+ <li><a href="#popup-rows">Row types</a></li>
+ <li><a href="#popup-builtins">Built-in popups</a></li>
+ </ul>
+ </div>
+
+ <div class="group">
+ <h4>Reference</h4>
+ <ul>
+ <li><a href="#example">Full example config</a></li>
+ <li><a href="#reference">Directive reference</a></li>
+ </ul>
+ </div>
+ </nav>
+
+ <main>
+ <div class="toprow">
+ <div>
+ <h1 style="font-size:var(--fs-3xl); margin:0;">sxbar</h1>
+ <p class="tagline">A small, fast status bar for Xorg — one C99 binary, configured entirely
+ through a plain-text file. Workspaces, system stats, floating popups with
+ sliders and menus, all driven by shell commands you control.</p>
+ </div>
+ <button class="toggle-theme" id="themeToggle" type="button">toggle theme</button>
+ </div>
+ <div class="badges" style="margin-top:18px;">
+ <span class="badge">C99</span>
+ <span class="badge">Xlib + Xft + Xinerama</span>
+ <span class="badge">~36 KB binary</span>
+ <span class="badge">no daemon dependencies</span>
+ </div>
+
+ <section id="overview">
+ <h2>Overview</h2>
+ <p class="lede">sxbar renders a slim EWMH workspace switcher plus a row of
+ modules — clock, battery, volume, custom scripts, anything you configure —
+ and can pop a floating slider or menu window out of any module.</p>
+
+ <p>Everything is controlled from a single config file, read from (in order)
+ <code class="inline">$XDG_CONFIG_HOME/sxbarc</code>,
+ <code class="inline">$XDG_CONFIG_HOME/sxbar/sxbarc</code>,
+ <code class="inline">~/.config/sxbarc</code>,
+ <code class="inline">~/.config/sxbar/sxbarc</code>, then a system-wide
+ fallback at <code class="inline">/usr/local/share/sxbarc</code>. There's
+ nothing to recompile to change modules, colours, icons, click actions or
+ popups — it's all config-file syntax of the form <code class="inline">key : value</code>.</p>
+
+ <div class="note"><strong>Multi-monitor</strong> is automatic: sxbar detects
+ screens via Xinerama and opens one bar per monitor, each with its own
+ workspace switcher filtered to windows actually on that screen.</div>
+ </section>
+
+ <section id="install">
+ <h2>Install & build</h2>
+ <p class="lede">Standard GNU make build. Needs Xlib, Xinerama and Xft
+ (with freetype2 headers) development packages, plus a C99 compiler.
+ Album art (<code class="inline">popup_image</code>, the
+ <code class="inline">media</code> module) needs no extra package —
+ image decoding is a vendored, public-domain single-header library
+ (<code class="inline">src/stb_image.h</code>) compiled straight into
+ the binary.</p>
+
+ <pre>git clone <this repo> sxbar
+<span class="k">cd</span> sxbar
+<span class="k">make</span>
+<span class="k">sudo make install</span> <span class="c"># PREFIX defaults to /usr/local</span></pre>
+
+ <div class="twrap">
+ <table>
+ <thead><tr><th>Installed to</th><th>What</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">$PREFIX/bin/sxbar</td><td>the binary</td></tr>
+ <tr><td class="mono">$PREFIX/share/man/man1/sxbar.1</td><td>man page</td></tr>
+ <tr><td class="mono">$PREFIX/share/sxbarc</td><td>fallback default config</td></tr>
+ <tr><td class="mono">$PREFIX/share/sxbar/scripts/</td><td>reference icon/demo scripts — copy to <code class="inline">~/.config/sxbar/scripts/</code> and edit your own copy</td></tr>
+ </tbody>
+ </table>
+ </div>
+ <p>Start it from your window manager's autostart / <code class="inline">.xinitrc</code>
+ with a plain <code class="inline">sxbar &</code>.</p>
+ </section>
+
+ <section id="quickstart">
+ <h2>Quick start</h2>
+ <p class="lede">Copy the shipped default config and enable a few modules to get oriented.</p>
+ <pre>mkdir -p ~/.config/sxbar
+cp /usr/local/share/sxbarc ~/.config/sxbar/sxbarc</pre>
+
+ <pre><span class="k">font</span> : JetBrainsMono Nerd Font:size=10
+<span class="k">background_colour</span> : #000000
+<span class="k">foreground_colour</span> : #7abccd
+
+<span class="k">module</span> : clock : <span class="v">true</span> : 1
+<span class="k">module</span> : date : <span class="v">true</span> : 60
+<span class="k">module</span> : battery : <span class="v">true</span> : 30
+<span class="k">module</span> : volume : <span class="v">true</span> : 5
+
+<span class="k">prefix</span> : clock : <span class="s">" "</span>
+<span class="k">colour</span> : clock : <span class="v">#50fa7b</span></pre>
+ <p>Restart sxbar to pick up changes — it re-reads the config on startup, not live.</p>
+ </section>
+
+ <section id="bars">
+ <h2>Global & bar options</h2>
+ <p class="lede">Set once at the top of the config; apply to every bar unless noted.</p>
+ <div class="twrap">
+ <table>
+ <thead><tr><th class="mono">key</th><th>default</th><th>does</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">height</td><td>19</td><td>bar height in px</td></tr>
+ <tr><td class="mono">bottom_bar</td><td>false</td><td>dock at the screen bottom instead of top</td></tr>
+ <tr><td class="mono">vertical_padding</td><td>0</td><td>gap between the bar and the screen edge</td></tr>
+ <tr><td class="mono">horizontal_padding</td><td>0</td><td>gap on both sides of the bar</td></tr>
+ <tr><td class="mono">text_padding</td><td>0</td><td>inner padding before the first workspace/module</td></tr>
+ <tr><td class="mono">border / border_width</td><td>false / 0</td><td>draw a border around the bar window</td></tr>
+ <tr><td class="mono">background_colour<br>foreground_colour<br>border_colour</td><td>#000000<br>#7abccd<br>#005577</td><td>hex (<code class="inline">#rrggbb</code>) or X colour name. These three don't support a trailing <code class="inline"># comment</code> on the same line — comment on its own line instead.</td></tr>
+ <tr><td class="mono">font</td><td>monospace:size=8</td><td>Xft font name, <code class="inline">Family:size=N[:style=Bold]</code>. Use a Nerd Font family here to render icon glyphs.</td></tr>
+ <tr><td class="mono">show_version<br>version_text</td><td>true<br>sxbar ver. 1.1</td><td>optional version string at the bar's right edge</td></tr>
+ <tr><td class="mono">secondary_bar</td><td>false</td><td>adds a second, modules-only bar on the opposite edge — see below</td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <h3>Secondary bar</h3>
+ <p>A second bar on the edge opposite <code class="inline">bottom_bar</code> — no
+ workspace switcher, no version text, just whichever modules you tag onto it.
+ Shares the primary bar's font/colours/height.</p>
+ <pre><span class="k">bottom_bar</span> : <span class="v">false</span>
+<span class="k">secondary_bar</span> : <span class="v">true</span>
+
+<span class="k">module</span> : battery : <span class="v">true</span> : 30
+<span class="k">module</span> : volume : <span class="v">true</span> : 5
+
+<span class="k">bar</span> : battery : <span class="v">secondary</span>
+<span class="k">bar</span> : volume : <span class="v">secondary</span></pre>
+ <p><code class="inline">bar : module_name : primary|secondary</code> defaults to
+ <code class="inline">primary</code> — clock, date and the workspace switcher always
+ stay on the primary bar.</p>
+ </section>
+
+ <section id="workspaces">
+ <h2>Workspaces & monitors</h2>
+ <p class="lede">The workspace switcher reads standard EWMH properties, so it works
+ with any EWMH-compliant window manager — no sxbar-specific config needed.</p>
+ <ul>
+ <li>Workspace names come from <code class="inline">_NET_DESKTOP_NAMES</code>, the
+ current one from <code class="inline">_NET_CURRENT_DESKTOP</code>.</li>
+ <li>Each workspace pill shows up to 4 small boxes for windows on it — counted
+ per monitor, so a bar only reflects the windows actually on its own screen,
+ not every window across every screen.</li>
+ <li>One bar opens per monitor automatically (via Xinerama); each computes its
+ own <code class="inline">_NET_WM_STRUT_PARTIAL</code> so multiple bars don't
+ clobber each other's reserved screen edge.</li>
+ </ul>
+
+ <h3>Workspace icons</h3>
+ <pre><span class="k">workspace_icon</span> : name : <span class="s">"icon text"</span></pre>
+ <p>Replaces a workspace's displayed label — its
+ <code class="inline">_NET_DESKTOP_NAMES</code> string, typically a plain number
+ like <code class="inline">"1"</code> — with different text instead, e.g. a Nerd
+ Font glyph. Purely cosmetic: switching still targets the same underlying
+ desktop, only what's drawn on the pill changes. Needs a Nerd Font set via
+ <code class="inline">font</code> to render glyphs. Repeatable, one line per
+ workspace; any workspace without a matching line just shows its plain name,
+ same as always.</p>
+ <pre><span class="k">workspace_icon</span> : 1 : <span class="s">"<glyph>"</span>
+<span class="k">workspace_icon</span> : 2 : <span class="s">"<glyph>"</span>
+<span class="k">workspace_icon</span> : 3 : <span class="s">"<glyph>"</span></pre>
+ </section>
+
+ <section id="modules">
+ <h2>Built-in modules</h2>
+ <p class="lede">Enabled with <code class="inline">module : name : true|false : refresh_interval_seconds</code>.
+ Everything below is opt-in/opt-out by default as shown.</p>
+ <div class="twrap">
+ <table>
+ <thead><tr><th class="mono">module</th><th>shows</th><th>default</th><th>needs</th><th>popup</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">clock</td><td>HH:MM:SS</td><td><span class="pill on">on</span></td><td>—</td><td>hover → open calendar</td></tr>
+ <tr><td class="mono">date</td><td>YYYY-MM-DD</td><td><span class="pill on">on</span></td><td>—</td><td>hover → open calendar</td></tr>
+ <tr><td class="mono">battery</td><td>charge %</td><td><span class="pill off">off</span></td><td><code class="inline">/sys/class/power_supply</code></td><td>hover → status + power-saver toggle</td></tr>
+ <tr><td class="mono">volume</td><td>volume %</td><td><span class="pill on">on</span></td><td><code class="inline">wpctl</code></td><td>hover → slider</td></tr>
+ <tr><td class="mono">cpu</td><td>usage %</td><td><span class="pill off">off</span></td><td><code class="inline">/proc/stat</code></td><td>hover → cpu / memory / per-core</td></tr>
+ <tr><td class="mono">brightness</td><td>brightness %</td><td><span class="pill off">off</span></td><td><span class="pill req">brightnessctl</span></td><td>hover → slider</td></tr>
+ <tr><td class="mono">bluetooth</td><td>On / Off</td><td><span class="pill off">off</span></td><td><span class="pill req">bluetoothctl</span></td><td>hover → power/scan/pair menu</td></tr>
+ <tr><td class="mono">usermenu</td><td>current username</td><td><span class="pill on">on</span></td><td><code class="inline">systemctl</code></td><td>hover → sleep/logout/shutdown</td></tr>
+ <tr><td class="mono">network</td><td>Online / Offline</td><td><span class="pill off">off</span></td><td><code class="inline">ip</code></td><td>hover → WiFi/Ethernet + IP</td></tr>
+ <tr><td class="mono">media</td><td>play/pause glyph + Artist - Title</td><td><span class="pill off">off</span></td><td><span class="pill req">playerctl</span>, curl for remote art</td><td>hover → album art + Previous/Play-Pause/Next</td></tr>
+ <tr><td class="mono">taskbar</td><td colspan="4">not like the others — see <a href="#taskbar">Taskbar</a> below</td></tr>
+ </tbody>
+ </table>
+ </div>
+ <p>Full detail on each popup is in <a href="#popup-builtins">Built-in popups</a> below.</p>
+
+ <div class="note"><strong>Every built-in module's command — and its popup —
+ is a script</strong>, not code baked into the binary. Each resolves (in order)
+ to your own copy at <code class="inline">~/.config/sxbar/scripts/<name>.sh</code>,
+ then the system copy <code class="inline">make install</code> places at
+ <code class="inline">/usr/local/share/sxbar/scripts/<name>.sh</code>,
+ or a harmless no-op if neither exists. Copy any of them over and edit —
+ no recompile needed, and no sxbarc editing needed either to change a
+ module's popup content (e.g. adding a row to <code class="inline">usermenu</code>)
+ — see <a href="#custom">Reference scripts</a> below for the full list.</div>
+ </section>
+
+ <section id="taskbar">
+ <h2>Taskbar</h2>
+ <p class="lede">Every module above renders one line of its own text.
+ <code class="inline">taskbar</code> doesn't: it shows one clickable segment per
+ window on the current workspace, so you can switch focus between them — the
+ motivating case being a window manager's monocle mode, where only one window
+ is visible at a time and there'd otherwise be no way to reach the others from
+ the bar. Typical setup is its own row on the <a href="#bars">secondary bar</a>,
+ directly beneath the primary status bar.</p>
+
+ <pre><span class="k">secondary_bar</span> : <span class="v">true</span>
+<span class="k">module</span> : taskbar : <span class="v">true</span> : 1
+<span class="k">bar</span> : taskbar : <span class="v">secondary</span></pre>
+
+ <div class="note"><strong>Needs <code class="inline">wmctrl</code></strong>, for both
+ listing windows and requesting focus — and a window manager that actually acts on
+ a <code class="inline">_NET_ACTIVE_WINDOW</code> client message (what
+ <code class="inline">wmctrl -i -a</code> sends to request focus). Checking sxwm's
+ own source (not just its advertised <code class="inline">_NET_SUPPORTED</code> list,
+ which does list it) showed that message was never handled — sxwm published
+ <code class="inline">_NET_ACTIVE_WINDOW</code> read-only to reflect its own focus,
+ but accepted no external requests to change it, and has no other IPC that could
+ either. <code class="inline">patches/net-active-window-mrjensk.patch</code> in the
+ sxwm repo adds that handling (reusing sxwm's own
+ <code class="inline">set_input_focus()</code>, the same function
+ <code class="inline">focus_next</code>/<code class="inline">focus_prev</code> use, so
+ monocle-mode raising behaves identically to switching focus with a keybind). Other
+ window managers may already support this out of the box — check yours.</div>
+
+ <p>It ignores its own <code class="inline">align</code> — as a fill module, it
+ always occupies whatever's left between the left- and right-aligned modules on
+ its bar, split into equal-width segments, rather than anchoring to one side. The
+ currently-focused window's segment is highlighted the same way the active
+ workspace pill is.</p>
+ </section>
+
+ <section id="custom">
+ <h2>Custom modules & scripts</h2>
+ <p class="lede">Any shell command or script becomes a module — its stdout is the
+ bar text, refreshed on its own interval.</p>
+ <pre><span class="k">custom</span> : <span class="v">temp</span> : <span class="s">"sensors | grep 'Package' | awk '{print $4}'"</span> : 5
+<span class="k">custom</span> : <span class="v">mem</span> : <span class="s">"free -h | awk '/^Mem:/{print $3\"/\"$2}'"</span> : 10
+<span class="k">custom</span> : <span class="v">updates</span> : <span class="s">"checkupdates | wc -l | tr -d ' '"</span> : 300</pre>
+ <p>Custom modules take every other directive on this page too — <code class="inline">prefix</code>,
+ <code class="inline">colour</code>, <code class="inline">click</code>,
+ <code class="inline">popup</code>, and so on — just referenced by whatever name
+ you gave the <code class="inline">custom</code> line.</p>
+
+ <h3>Reference scripts</h3>
+ <p>Every script sxbar ships with lives in <code class="inline">scripts/</code> and
+ installs to <code class="inline">$PREFIX/share/sxbar/scripts/</code> as a
+ reference copy — copy any of them to <code class="inline">~/.config/sxbar/scripts/</code>
+ and point your config (or nothing, for the built-in module scripts —
+ see the note above) at your own copy so you can edit freely.</p>
+
+ <p>One script per built-in module, dispatched by subcommand where a
+ module needs more than one piece of output. Every one of them also
+ answers a <code class="inline">menu</code> subcommand — see the note
+ below the table.</p>
+ <div class="twrap">
+ <table>
+ <thead><tr><th class="mono">script</th><th>subcommands</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">clock.sh</td><td>bar text (default) · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">date.sh</td><td>bar text (default) · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">battery.sh</td><td><code class="inline">capacity</code> (bar, default) · <code class="inline">status</code> · <code class="inline">toggle-powersave</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">volume.sh</td><td><code class="inline">get</code> (bar/slider, default) · <code class="inline">set VALUE</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">brightness.sh</td><td><code class="inline">get</code> (bar/slider, default) · <code class="inline">set VALUE</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">cpu.sh</td><td><code class="inline">usage [PREFIX]</code> (bar/popup, default) · <code class="inline">mem</code> · <code class="inline">cores</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">bluetooth.sh</td><td><code class="inline">status</code> (bar, default) · <code class="inline">pair</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">usermenu.sh</td><td>bar text (default) · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">network.sh</td><td><code class="inline">status</code> (bar, default) · <code class="inline">wifi</code> · <code class="inline">ethernet</code> · <code class="inline">menu</code></td></tr>
+ <tr><td class="mono">media.sh</td><td>bar text (default) · <code class="inline">track</code> · <code class="inline">art</code> · <code class="inline">prev</code> · <code class="inline">playpause</code> · <code class="inline">next</code> · <code class="inline">menu</code></td></tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="note"><strong><code class="inline">menu</code></strong> is what
+ makes a built-in module self-contained: run once at startup, it prints
+ that module's <a href="#popup-builtins">popup definition</a> — the same
+ <code class="inline">popup</code>/<code class="inline">popup_item</code>/
+ <code class="inline">popup_info</code>/<code class="inline">popup_set</code>
+ directives sxbarc itself uses, minus the module-name field, since a
+ script only ever describes itself. Edit your own copy of e.g.
+ <code class="inline">usermenu.sh</code> to add, remove or reorder rows —
+ sxbarc's own directives can still override the result wholesale if you'd
+ rather keep everything in one config file (see
+ <a href="#popup-rows">Row types</a>).</div>
+
+ <p>Plus three standalone helpers:</p>
+ <div class="twrap">
+ <table>
+ <thead><tr><th class="mono">script</th><th>used as</th><th>does</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">battery_icon.sh</td><td><code class="inline">prefix_cmd</code></td><td>picks a battery glyph by charge level, swaps to a bolt glyph while charging</td></tr>
+ <tr><td class="mono">volume_icon.sh</td><td><code class="inline">prefix_cmd</code></td><td>picks a volume glyph, mute-aware</td></tr>
+ <tr><td class="mono">demo_popup.sh</td><td><code class="inline">popup_item</code> / <code class="inline">popup_set</code></td><td>fires a desktop notification — a safe target for testing popup rows before wiring up real commands</td></tr>
+ </tbody>
+ </table>
+ </div>
+ <p><code class="inline">battery_icon.sh</code>, trimmed:</p>
+ <pre><span class="c">#!/bin/sh</span>
+pct=$(printf <span class="s">'%s'</span> <span class="s">"$1"</span> | tr -dc <span class="s">'0-9'</span>)
+status=$(cat /sys/class/power_supply/BAT*/status 2>/dev/null | head -n1)
+
+<span class="k">if</span> [ <span class="s">"$status"</span> = <span class="s">"Charging"</span> ]; <span class="k">then</span>
+ printf <span class="s">'%s '</span> <span class="s">''</span> <span class="c"># bolt glyph</span>
+ exit 0
+<span class="k">fi</span>
+
+<span class="k">if</span> [ <span class="s">"$pct"</span> -ge 90 ]; <span class="k">then</span> printf <span class="s">'%s '</span> <span class="s">''</span>
+<span class="k">elif</span> [ <span class="s">"$pct"</span> -ge 50 ]; <span class="k">then</span> printf <span class="s">'%s '</span> <span class="s">''</span>
+<span class="k">else</span> printf <span class="s">'%s '</span> <span class="s">''</span>
+<span class="k">fi</span></pre>
+ <p>The module's current output (e.g. <code class="inline">"83%"</code>) is passed in
+ as <code class="inline">$1</code>, shell-quoted — built-in commands don't expose
+ extra state like charging/muted beyond that string, so scripts needing it
+ re-check the system themselves.</p>
+ </section>
+
+ <section id="customize">
+ <h2>Icons, colour, layout, clicks</h2>
+ <p class="lede">These directives apply to any module — built-in or custom — by name.</p>
+
+ <h3>Prefix / icon</h3>
+ <pre><span class="k">prefix</span> : module_name : <span class="s">"icon text"</span> <span class="c"># icon : ... is an accepted alias</span></pre>
+ <p>Static text prepended to a module's output. Needs a Nerd Font set via
+ <code class="inline">font</code> to render glyphs. For <code class="inline">custom</code>
+ modules, declare <code class="inline">prefix</code> after the module's
+ <code class="inline">custom</code> line.</p>
+
+ <h4>Dynamic icon (<code class="inline">prefix_cmd</code>)</h4>
+ <pre><span class="k">prefix_cmd</span> : module_name : <span class="s">"command or script path"</span> <span class="c"># icon_cmd is an alias</span></pre>
+ <p>Runs a script instead of fixed text, so the icon can reflect live state (battery
+ charging, volume muted). Re-run every refresh, with the module's own current
+ output passed in as <code class="inline">$1</code>. Its stdout becomes the prefix
+ verbatim — include your own trailing space.</p>
+
+ <h3>Colour</h3>
+ <pre><span class="k">colour</span> : module_name : <span class="v">#rrggbb</span> <span class="c"># color : ... also works</span></pre>
+ <p>Overrides <code class="inline">foreground_colour</code> for one module.</p>
+
+ <h3>Width</h3>
+ <pre><span class="k">width</span> : module_name : <span class="v">min_pixels</span></pre>
+ <p>Reserves a minimum pixel width for the module's slot so neighbours don't
+ shift when its digit count changes (e.g. cpu going <code class="inline">9%</code> →
+ <code class="inline">16%</code> → <code class="inline">100%</code>). Text is
+ never truncated — wider values just use their natural width.</p>
+
+ <h3>Max width (scrolling / marquee text)</h3>
+ <pre><span class="k">max_width</span> : module_name : <span class="v">max_pixels</span></pre>
+ <p>The opposite of <code class="inline">width</code> above: caps a module's slot
+ at this many pixels. Text that fits draws as normal; text wider than the cap
+ scrolls left within that fixed width instead of stretching the bar — handy for
+ anything with unpredictable-length output, like <code class="inline">media</code>'s
+ "Artist - Title". sxbar only redraws faster than its usual once-a-second cadence
+ while something is actually scrolling, so this costs nothing when nothing
+ overflows.</p>
+ <pre><span class="k">max_width</span> : media : <span class="v">220</span></pre>
+ <p>This is a bar-level directive; a popup's own text rows (e.g.
+ <code class="inline">media</code>'s track title) scroll the same way
+ automatically whenever the popup also has an image, slider or button-row
+ to anchor its width — no separate config needed there, see
+ <a href="#popup-rows">Row types</a>.</p>
+
+ <h3>Alignment</h3>
+ <pre><span class="k">align</span> : module_name : <span class="v">left|center|right</span> <span class="c"># default: right</span></pre>
+ <p>Three independent groups per bar: left continues on from the workspace
+ switcher, center is centered across the full bar width, right is anchored
+ before <code class="inline">version_text</code>.</p>
+
+ <h3>icon_only</h3>
+ <pre><span class="k">icon_only</span> : module_name : <span class="v">true|false</span></pre>
+ <p>Shows only the prefix/icon, hiding the module's own text entirely. The
+ command, refresh interval and any popup keep running exactly as normal —
+ only the rendered bar text changes. Needs a <code class="inline">prefix</code>
+ or <code class="inline">prefix_cmd</code> set, or there's nothing left to show.</p>
+
+ <h3>Click & scroll</h3>
+ <pre><span class="k">click</span> : module_name : <span class="s">"command"</span>
+<span class="k">scroll_up</span> : module_name : <span class="s">"command"</span>
+<span class="k">scroll_down</span> : module_name : <span class="s">"command"</span></pre>
+ <pre><span class="k">click</span> : volume : <span class="s">"pavucontrol"</span>
+<span class="k">scroll_up</span> : volume : <span class="s">"wpctl set-volume --limit 1.0 @DEFAULT_AUDIO_SINK@ 5%+"</span>
+<span class="k">scroll_down</span> : volume : <span class="s">"wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-"</span></pre>
+ <p>Runs detached (double-fork) so sxbar never blocks. If a module also has a
+ <code class="inline">popup</code> with a <code class="inline">click</code>
+ trigger, the popup takes over left-click and <code class="inline">click</code>
+ is ignored for it — <code class="inline">scroll_up</code>/<code class="inline">scroll_down</code>
+ still work independently either way.</p>
+ </section>
+
+ <section id="popups">
+ <h2>Floating popups</h2>
+ <p class="lede">A module can open a small floating (override-redirect) window
+ instead of — or as well as — running a plain <code class="inline">click</code>
+ command. Only one popup is open at a time.</p>
+
+ <pre><span class="k">popup</span> : module_name : <span class="v">hover|click</span> : <span class="v">buttons|slider</span></pre>
+ <p>The third field only decides whether the module has a popup at all these
+ days — <code class="inline">popup_item</code>/<code class="inline">popup_info</code>/<code class="inline">popup_set</code>
+ decide what's actually in it, in any combination, so either word works there.</p>
+
+ <div class="grid3">
+ <div class="card">
+ <div class="eyebrow">hover</div>
+ <h4>Opens on mouse-over</h4>
+ <p>Reveals the popup while the pointer is over the module; closes when the
+ pointer leaves both the module and the popup. Every built-in popup uses this.</p>
+ </div>
+ <div class="card">
+ <div class="eyebrow">click</div>
+ <h4>Opens on left-click</h4>
+ <p>Toggles on click; closes again on a second click, on clicking a button
+ row, or on clicking anywhere else — like an ordinary dropdown menu.</p>
+ </div>
+ </div>
+ <div class="note">Hovering only <em>reveals</em> a menu — an actual click on a
+ button row is still needed to run anything. A hover-triggered
+ <code class="inline">usermenu</code> doesn't make "Shut down" any easier to
+ trigger by accident.</div>
+ </section>
+
+ <section id="popup-rows">
+ <h2>Row types</h2>
+ <p class="lede">A popup is a list of rows. Text, button, slider, image and
+ segmented-button rows all mix freely in the same popup.</p>
+ <div class="grid3">
+ <div class="card">
+ <div class="eyebrow">text</div>
+ <h4>popup_info</h4>
+ <p>Purely informational, not clickable at all. Label is a shell command's
+ output, re-run fresh every time the popup opens (e.g. current IP).</p>
+ </div>
+ <div class="card">
+ <div class="eyebrow">button</div>
+ <h4>popup_item</h4>
+ <p>Runs its own command and closes the popup on click.</p>
+ </div>
+ <div class="card">
+ <div class="eyebrow">slider</div>
+ <h4>popup_set</h4>
+ <p>Draggable 0–100% track; dragging doesn't close the popup. Starting
+ position comes from the module's own command output.</p>
+ </div>
+ <div class="card">
+ <div class="eyebrow">image</div>
+ <h4>popup_image</h4>
+ <p>Renders an image file, e.g. album art. Command's stdout is a path to a
+ local image, re-run fresh every popup open, scaled to fit a 160px box.
+ Not clickable. No extra build dependency needed. Anchors the popup's
+ width — any text row in the same popup is capped to it and scrolls
+ instead of stretching the popup wider than the image.</p>
+ </div>
+ <div class="card">
+ <div class="eyebrow">buttons</div>
+ <h4>popup_buttons</h4>
+ <p>One row split into N equal-width button segments side by side (e.g.
+ media transport controls), instead of N stacked full-width
+ <code class="inline">popup_item</code> rows. Each segment runs its own
+ command and closes the popup on click.</p>
+ </div>
+ </div>
+
+ <pre><span class="k">popup_item</span> : module_name : <span class="s">"Label"</span> : <span class="s">"command"</span> <span class="c"># button row, repeatable</span>
+<span class="k">popup_info</span> : module_name : <span class="s">"shell command"</span> <span class="c"># text row, repeatable</span>
+<span class="k">popup_image</span> : module_name : <span class="s">"shell command"</span> <span class="c"># image row, stdout = path to an image file</span>
+<span class="k">popup_buttons</span> : module_name : <span class="s">"L1"</span> : <span class="s">"cmd1"</span> : <span class="s">"L2"</span> : <span class="s">"cmd2"</span> ... <span class="c"># one row, N button segments</span>
+<span class="k">popup_set</span> : module_name : <span class="s">"command"</span> <span class="c"># slider row, receives new value as $1 (e.g. "45%")</span></pre>
+
+ <p>The first <code class="inline">popup_item</code>/<code class="inline">popup_info</code>/
+ <code class="inline">popup_image</code>/<code class="inline">popup_buttons</code> line for
+ a module replaces its built-in default rows (if any, including a
+ <code class="inline">popup_set</code> slider row) — later lines append. Add
+ <code class="inline">popup_set</code> again afterwards if you cleared a built-in
+ slider this way and still want it back.</p>
+
+ <p>Example combining all five on one custom module:</p>
+ <pre><span class="k">custom</span> : mymodule : <span class="s">"echo ok"</span> : 5
+<span class="k">popup</span> : mymodule : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_info</span> : mymodule : <span class="s">"echo 'status: '$(whoami)"</span>
+<span class="k">popup_image</span> : mymodule : <span class="s">"echo /path/to/icon.png"</span>
+<span class="k">popup_buttons</span> : mymodule : <span class="s">"⏮"</span> : <span class="s">"mymodule-ctl prev"</span> : <span class="s">"⏭"</span> : <span class="s">"mymodule-ctl next"</span>
+<span class="k">popup_item</span> : mymodule : <span class="s">"Restart"</span> : <span class="s">"systemctl --user restart myservice"</span>
+<span class="k">popup_set</span> : mymodule : <span class="s">"myservice-set-level"</span></pre>
+ </section>
+
+ <section id="popup-builtins">
+ <h2>Built-in popups</h2>
+ <p class="lede">What each built-in module's popup contains by default. This
+ content isn't hardcoded in the binary — it's each module's own
+ <code class="inline"><script> menu</code> output (see
+ <a href="#custom">Custom modules & scripts</a>), shown below as the
+ equivalent sxbarc directives for reference. Edit the script directly to
+ change these, or override wholesale from sxbarc with the directives
+ above — either works, since the first <code class="inline">popup_item</code>/
+ <code class="inline">popup_info</code> line for a module always replaces
+ its current rows regardless of where they came from.</p>
+
+ <h3>clock · date — open calendar</h3>
+ <pre><span class="k">popup </span>: clock : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_item </span>: clock : <span class="s">"Open calendar"</span> : <span class="s">"gsimplecal"</span>
+
+<span class="k">popup </span>: date : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_item </span>: date : <span class="s">"Open calendar"</span> : <span class="s">"gsimplecal"</span></pre>
+ <p>Same action on both, since clock and date are usually shown next to each other.</p>
+
+ <h3>battery — status + power-saver toggle</h3>
+ <pre><span class="k">popup </span>: battery : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_info </span>: battery : <span class="s">"~/.config/sxbar/scripts/battery.sh status"</span>
+<span class="k">popup_item </span>: battery : <span class="s">"Toggle power saver"</span> : <span class="s">"~/.config/sxbar/scripts/battery.sh toggle-powersave"</span></pre>
+ <p>The status row (state, time remaining, health) needs <code class="inline">upower</code>;
+ the toggle needs <code class="inline">power-profiles-daemon</code> — both beyond the
+ plain <code class="inline">/sys/class/power_supply</code> read the bar text itself uses.</p>
+
+ <h3>brightness · volume — slider</h3>
+ <pre><span class="k">popup </span>: brightness : <span class="v">hover</span> : <span class="v">slider</span>
+<span class="k">popup_set </span>: brightness : <span class="s">"~/.config/sxbar/scripts/brightness.sh set"</span>
+
+<span class="k">popup </span>: volume : <span class="v">hover</span> : <span class="v">slider</span>
+<span class="k">popup_set </span>: volume : <span class="s">"~/.config/sxbar/scripts/volume.sh set"</span></pre>
+
+ <h3>cpu — three status rows</h3>
+ <p>Fresh CPU sample, memory line, and a per-core breakdown (two
+ <code class="inline">/proc/stat</code> samples 0.2s apart, paired up by
+ position via an awk array — no process substitution, since
+ <code class="inline">/bin/sh</code> may be <code class="inline">dash</code>).
+ One script, <code class="inline">cpu.sh</code>, handles all three via subcommand.</p>
+ <pre><span class="k">popup </span>: cpu : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_info </span>: cpu : <span class="s">"~/.config/sxbar/scripts/cpu.sh usage 'CPU: '"</span>
+<span class="k">popup_info </span>: cpu : <span class="s">"~/.config/sxbar/scripts/cpu.sh mem"</span>
+<span class="k">popup_info </span>: cpu : <span class="s">"~/.config/sxbar/scripts/cpu.sh cores"</span></pre>
+
+ <h3>bluetooth — power / scan / pair</h3>
+ <pre><span class="k">popup </span>: bluetooth : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_item </span>: bluetooth : <span class="s">"Turn on"</span> : <span class="s">"bluetoothctl power on"</span>
+<span class="k">popup_item </span>: bluetooth : <span class="s">"Turn off"</span> : <span class="s">"bluetoothctl power off"</span>
+<span class="k">popup_item </span>: bluetooth : <span class="s">"Search for devices"</span> : <span class="s">"bluetoothctl --timeout 10 scan on"</span>
+<span class="k">popup_item </span>: bluetooth : <span class="s">"Pair last found device"</span> : <span class="s">"~/.config/sxbar/scripts/bluetooth.sh pair"</span></pre>
+ <p>The first three are plain passthrough commands (no logic to extract into a
+ script); "pair" has real parsing/control flow, so it's the one that's scripted.
+ No interactive device list — it targets whichever device
+ <code class="inline">bluetoothctl devices</code> saw most recently.</p>
+
+ <h3>usermenu — sleep / log out / shut down</h3>
+ <pre><span class="k">popup </span>: usermenu : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_item </span>: usermenu : <span class="s">"Sleep"</span> : <span class="s">"systemctl suspend"</span>
+<span class="k">popup_item </span>: usermenu : <span class="s">"Log out"</span> : <span class="s">"pkill sxwm"</span>
+<span class="k">popup_item </span>: usermenu : <span class="s">"Shut down"</span> : <span class="s">"systemctl poweroff"</span></pre>
+ <div class="note">The default logout command is <code class="inline">pkill <your-wm></code>
+ — minimal window managers without a session manager have no external way to
+ trigger their own quit keybind. Simplest fix: edit the <code class="inline">pkill sxwm</code>
+ line directly in your own copy of <code class="inline">usermenu.sh</code> for your
+ WM/session — or override the <code class="inline">"Log out"</code> row's command
+ from sxbarc as shown above if you'd rather keep it in your config file.</div>
+
+ <h3>network — WiFi / Ethernet status</h3>
+ <p>Bar text is <code class="inline">Online</code>/<code class="inline">Offline</code>
+ based on whether a default route exists. Popup has two informational rows: first
+ interface with a <code class="inline">/sys/class/net/<if>/wireless</code>
+ directory for WiFi, first non-virtual <code class="inline">ARPHRD_ETHER</code>
+ interface for Ethernet — each showing its IPv4 address or "disconnected".</p>
+ <pre><span class="k">popup </span>: network : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_info </span>: network : <span class="s">"~/.config/sxbar/scripts/network.sh wifi"</span>
+<span class="k">popup_info </span>: network : <span class="s">"~/.config/sxbar/scripts/network.sh ethernet"</span></pre>
+
+ <h3>media — album art + transport controls</h3>
+ <p>Bar text is a play/pause glyph plus <code class="inline">Artist - Title</code>,
+ via <code class="inline">playerctl</code> (controls whichever player it considers
+ active — most players speak MPRIS2 automatically: Spotify, VLC, mpv, browser
+ tabs, etc.). The popup's image row resolves <code class="inline">mpris:artUrl</code>:
+ a <code class="inline">file://</code> path is used directly; an
+ <code class="inline">http(s)://</code> one is downloaded once and cached under
+ <code class="inline">$XDG_CACHE_HOME/sxbar-media-art/</code> (needs
+ <code class="inline">curl</code>). The transport buttons are one
+ <code class="inline">popup_buttons</code> row (step-backward/play/step-forward
+ Nerd Font glyphs, U+F048/U+F04B/U+F051 — shown as
+ <code class="inline"><...></code> placeholders below since they render as
+ tofu without that font) rather than three stacked rows.</p>
+ <pre><span class="k">popup </span>: media : <span class="v">hover</span> : <span class="v">buttons</span>
+<span class="k">popup_image </span>: media : <span class="s">"~/.config/sxbar/scripts/media.sh art"</span>
+<span class="k">popup_info </span>: media : <span class="s">"~/.config/sxbar/scripts/media.sh track"</span>
+<span class="k">popup_buttons </span>: media : <span class="s">"<step-backward>"</span> : <span class="s">"~/.config/sxbar/scripts/media.sh prev"</span> : <span class="s">"<play>"</span> : <span class="s">"~/.config/sxbar/scripts/media.sh playpause"</span> : <span class="s">"<step-forward>"</span> : <span class="s">"~/.config/sxbar/scripts/media.sh next"</span></pre>
+ </section>
+
+ <section id="example">
+ <h2>Full example config</h2>
+ <p class="lede">A config combining most of the directives on this page.</p>
+ <pre><span class="c"># appearance</span>
+<span class="k">height</span> : 20
+<span class="k">bottom_bar</span> : <span class="v">false</span>
+<span class="k">vertical_padding</span> : 5
+<span class="k">horizontal_padding</span> : 5
+<span class="k">background_colour</span> : #000000
+<span class="k">foreground_colour</span> : #7abccd
+<span class="k">font</span> : JetBrainsMono Nerd Font:size=10
+
+<span class="c"># modules</span>
+<span class="k">module</span> : clock : <span class="v">true</span> : 1
+<span class="k">module</span> : date : <span class="v">true</span> : 60
+<span class="k">module</span> : battery : <span class="v">true</span> : 30
+<span class="k">module</span> : volume : <span class="v">true</span> : 5
+<span class="k">module</span> : cpu : <span class="v">true</span> : 3
+<span class="k">module</span> : network : <span class="v">true</span> : 10
+<span class="k">module</span> : usermenu : <span class="v">true</span> : 300
+
+<span class="c"># icons + colours</span>
+<span class="k">prefix</span> : clock : <span class="s">" "</span>
+<span class="k">prefix</span> : network : <span class="s">" "</span>
+<span class="k">colour</span> : clock : #50fa7b
+<span class="k">colour</span> : battery : #ffb86c
+<span class="k">colour</span> : volume : #ff79c6
+<span class="k">colour</span> : network : #2ee6d6
+
+<span class="c"># layout</span>
+<span class="k">align</span> : clock : <span class="v">center</span>
+<span class="k">width</span> : battery : 48
+<span class="k">width</span> : volume : 48
+<span class="k">icon_only</span> : network : <span class="v">true</span>
+
+<span class="c"># actions</span>
+<span class="k">scroll_up</span> : volume : <span class="s">"wpctl set-volume --limit 1.0 @DEFAULT_AUDIO_SINK@ 5%+"</span>
+<span class="k">scroll_down</span> : volume : <span class="s">"wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-"</span>
+
+<span class="c"># override the default logout command</span>
+<span class="k">popup_item</span> : usermenu : <span class="s">"Sleep"</span> : <span class="s">"systemctl suspend"</span>
+<span class="k">popup_item</span> : usermenu : <span class="s">"Log out"</span> : <span class="s">"loginctl terminate-session $XDG_SESSION_ID"</span>
+<span class="k">popup_item</span> : usermenu : <span class="s">"Shut down"</span> : <span class="s">"systemctl poweroff"</span>
+
+<span class="c"># a custom module</span>
+<span class="k">custom</span> : mem : <span class="s">"free -h | awk '/^Mem:/{print $3\"/\"$2}'"</span> : 10
+<span class="k">prefix</span> : mem : <span class="s">" "</span></pre>
+ </section>
+
+ <section id="reference">
+ <h2>Directive reference</h2>
+ <p class="lede">Every config key, at a glance.</p>
+ <div class="twrap">
+ <table>
+ <thead><tr><th class="mono">directive</th><th>syntax</th></tr></thead>
+ <tbody>
+ <tr><td class="mono">module</td><td class="mono">module : name : true|false : interval</td></tr>
+ <tr><td class="mono">custom</td><td class="mono">custom : name : "command" : interval</td></tr>
+ <tr><td class="mono">prefix</td><td class="mono">prefix : name : "text"</td></tr>
+ <tr><td class="mono">prefix_cmd</td><td class="mono">prefix_cmd : name : "command"</td></tr>
+ <tr><td class="mono">icon_only</td><td class="mono">icon_only : name : true|false</td></tr>
+ <tr><td class="mono">colour</td><td class="mono">colour : name : #rrggbb</td></tr>
+ <tr><td class="mono">width</td><td class="mono">width : name : min_pixels</td></tr>
+ <tr><td class="mono">align</td><td class="mono">align : name : left|center|right</td></tr>
+ <tr><td class="mono">bar</td><td class="mono">bar : name : primary|secondary</td></tr>
+ <tr><td class="mono">click</td><td class="mono">click : name : "command"</td></tr>
+ <tr><td class="mono">scroll_up / scroll_down</td><td class="mono">scroll_up : name : "command"</td></tr>
+ <tr><td class="mono">popup</td><td class="mono">popup : name : hover|click : buttons|slider</td></tr>
+ <tr><td class="mono">popup_item</td><td class="mono">popup_item : name : "Label" : "command"</td></tr>
+ <tr><td class="mono">popup_info</td><td class="mono">popup_info : name : "shell command"</td></tr>
+ <tr><td class="mono">popup_image</td><td class="mono">popup_image : name : "shell command"</td></tr>
+ <tr><td class="mono">popup_set</td><td class="mono">popup_set : name : "command"</td></tr>
+ <tr><td class="mono">height / bottom_bar / *_padding / border*</td><td>global bar geometry — see <a href="#bars">Global & bar options</a></td></tr>
+ <tr><td class="mono">background_colour / foreground_colour / border_colour / font</td><td>global appearance</td></tr>
+ <tr><td class="mono">show_version / version_text</td><td>global</td></tr>
+ <tr><td class="mono">secondary_bar</td><td class="mono">secondary_bar : true|false</td></tr>
+ <tr><td class="mono">workspace_icon</td><td class="mono">workspace_icon : name : "icon text"</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </section>
+ </main>
+
+ <footer>
+ sxbar — the simple, yet powerful, status bar for Xorg. ~36 KB binary, no daemon
+ dependencies beyond Xlib/Xft/Xinerama.
+ </footer>
+</div>
+
+<script>
+ (function () {
+ var toggle = document.getElementById('themeToggle');
+ var root = document.documentElement;
+ toggle.addEventListener('click', function () {
+ var current = root.getAttribute('data-theme');
+ var prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
+ var effectiveDark = current ? current === 'dark' : prefersDark;
+ root.setAttribute('data-theme', effectiveDark ? 'light' : 'dark');
+ });
+
+ var links = Array.prototype.slice.call(document.querySelectorAll('nav.toc a'));
+ var sections = links.map(function (a) {
+ return document.querySelector(a.getAttribute('href'));
+ });
+ function onScroll() {
+ var pos = window.scrollY + 100;
+ var activeIdx = 0;
+ sections.forEach(function (sec, i) {
+ if (sec && sec.offsetTop <= pos) activeIdx = i;
+ });
+ links.forEach(function (a, i) {
+ a.classList.toggle('active', i === activeIdx);
+ });
+ }
+ document.addEventListener('scroll', onScroll, { passive: true });
+ onScroll();
+ })();
+</script>
diff --git a/scripts/battery.sh b/scripts/battery.sh
new file mode 100755
index 0000000..5fee176
--- /dev/null
+++ b/scripts/battery.sh
@@ -0,0 +1,50 @@
+#!/bin/sh
+# battery module -- everything the module needs, dispatched by subcommand:
+# battery.sh -> bar text, "NN%" (from /sys/class/power_supply)
+# battery.sh status -> detailed status row (popup, needs upower)
+# battery.sh toggle-powersave -> toggle power profile (popup action, needs power-profiles-daemon)
+# battery.sh menu -> popup definition, read once at startup
+# (see README, "Module-declared menus")
+mode="${1:-capacity}"
+
+case "$mode" in
+menu)
+ self="$0"
+ echo 'popup : hover : buttons'
+ echo "popup_info : \"$self status\""
+ echo "popup_item : \"Toggle power saver\" : \"$self toggle-powersave\""
+ ;;
+capacity)
+ # BAT0 on some machines, BAT1 on others -- glob for whichever exists
+ cat /sys/class/power_supply/BAT*/capacity 2>/dev/null | head -n1 | sed 's/$/%/'
+ ;;
+status)
+ dev=$(upower -e 2>/dev/null | grep -m1 'BAT')
+ if [ -z "$dev" ]; then
+ echo "Battery: no info"
+ exit 0
+ fi
+
+ upower -i "$dev" 2>/dev/null | awk '
+ /state:/ { state = $2 }
+ /percentage:/ { pct = $2 }
+ /time to empty:/ { tte = $0; sub(/.*time to empty:[ \t]*/, "", tte) }
+ /time to full:/ { ttf = $0; sub(/.*time to full:[ \t]*/, "", ttf) }
+ /capacity:/ { health = $2 }
+ END {
+ out = state " " pct
+ if (state == "discharging" && tte != "") out = out " (" tte " left)"
+ if (state == "charging" && ttf != "") out = out " (" ttf " to full)"
+ if (health != "") out = out " -- health " health
+ print out
+ }'
+ ;;
+toggle-powersave)
+ current=$(powerprofilesctl get 2>/dev/null)
+ if [ "$current" = "power-saver" ]; then
+ powerprofilesctl set balanced
+ else
+ powerprofilesctl set power-saver
+ fi
+ ;;
+esac
diff --git a/scripts/bluetooth.sh b/scripts/bluetooth.sh
new file mode 100755
index 0000000..6e78472
--- /dev/null
+++ b/scripts/bluetooth.sh
@@ -0,0 +1,27 @@
+#!/bin/sh
+# bluetooth module -- dispatched by subcommand:
+# bluetooth.sh -> bar text, "On"/"Off" (adapter power state)
+# bluetooth.sh pair -> "Pair last found device" popup action. No
+# interactive device list -- targets whichever
+# device bluetoothctl saw most recently.
+# bluetooth.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-status}"
+
+case "$mode" in
+menu)
+ self="$0"
+ echo 'popup : hover : buttons'
+ echo 'popup_item : "Turn on" : "bluetoothctl power on"'
+ echo 'popup_item : "Turn off" : "bluetoothctl power off"'
+ echo 'popup_item : "Search for devices" : "bluetoothctl --timeout 10 scan on"'
+ echo "popup_item : \"Pair last found device\" : \"$self pair\""
+ ;;
+status)
+ bluetoothctl show 2>/dev/null | grep -q 'Powered: yes' && echo 'On' || echo 'Off'
+ ;;
+pair)
+ m=$(bluetoothctl devices | tail -n1 | awk '{print $2}')
+ [ -n "$m" ] && bluetoothctl pair "$m" && bluetoothctl trust "$m" && bluetoothctl connect "$m"
+ ;;
+esac
diff --git a/scripts/brightness.sh b/scripts/brightness.sh
new file mode 100755
index 0000000..47060fd
--- /dev/null
+++ b/scripts/brightness.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# brightness module -- dispatched by subcommand:
+# brightness.sh -> bar text / slider starting value, "NN%"
+# brightness.sh set NN% -> slider drag target
+# brightness.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-get}"
+
+case "$mode" in
+menu)
+ echo 'popup : hover : slider'
+ echo "popup_set : \"$0 set\""
+ ;;
+get)
+ brightnessctl -m 2>/dev/null | awk -F, '{print $4}'
+ ;;
+set)
+ brightnessctl set "$2"
+ ;;
+esac
diff --git a/scripts/clock.sh b/scripts/clock.sh
new file mode 100755
index 0000000..fbba0df
--- /dev/null
+++ b/scripts/clock.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+# clock module -- dispatched by subcommand:
+# clock.sh -> bar text, "HH:MM:SS"
+# clock.sh menu -> popup definition, read once at startup (see README,
+# "Module-declared menus")
+mode="${1:-text}"
+
+case "$mode" in
+menu)
+ echo 'popup : hover : buttons'
+ echo 'popup_item : "Open Clock" : "xclock"'
+ ;;
+*)
+ date '+%H:%M:%S'
+ ;;
+esac
diff --git a/scripts/cpu.sh b/scripts/cpu.sh
new file mode 100755
index 0000000..3be1f3f
--- /dev/null
+++ b/scripts/cpu.sh
@@ -0,0 +1,57 @@
+#!/bin/sh
+# cpu module -- everything the module needs, dispatched by subcommand:
+# cpu.sh -> bar text, "NN%"
+# cpu.sh usage "PREFIX" -> same usage %, with PREFIX prepended (popup row)
+# cpu.sh mem -> "Mem: used/total" (popup row)
+# cpu.sh cores -> "Cores: 0:NN% 1:NN% ..." (popup row)
+# cpu.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-usage}"
+
+case "$mode" in
+menu)
+ self="$0"
+ echo 'popup : hover : buttons'
+ echo "popup_info : \"$self usage 'CPU: '\""
+ echo "popup_info : \"$self mem\""
+ echo "popup_info : \"$self cores\""
+ ;;
+usage)
+ prefix="${2:-}"
+ # two /proc/stat samples 0.2s apart -- top(1)'s own output is
+ # localised and unparseable
+ { grep -m1 '^cpu ' /proc/stat; sleep 0.2; grep -m1 '^cpu ' /proc/stat; } |
+ LC_ALL=C awk -v prefix="$prefix" '
+ NR==1 { for (i=2;i<=8;i++) t1+=$i; d1=$5+$6 }
+ NR==2 {
+ for (i=2;i<=8;i++) t2+=$i; d2=$5+$6; d=t2-t1
+ printf "%s%d%%\n", prefix, (d>0 ? (1-(d2-d1)/d)*100 : 0)
+ }'
+ ;;
+mem)
+ LC_ALL=C free -h | awk '/^Mem:/{print "Mem: " $3"/"$2}'
+ ;;
+cores)
+ # two /proc/stat samples paired up by position via an awk array --
+ # no process substitution, since /bin/sh may be dash
+ a=$(grep '^cpu[0-9]' /proc/stat)
+ n=$(printf '%s\n' "$a" | wc -l)
+ sleep 0.2
+ b=$(grep '^cpu[0-9]' /proc/stat)
+
+ printf '%s\n%s\n' "$a" "$b" | LC_ALL=C awk -v n="$n" '
+ NR<=n {
+ t1[NR]=0; for (i=2;i<=8;i++) t1[NR]+=$i
+ d1[NR]=$5+$6; name[NR]=$1
+ }
+ NR>n {
+ j=NR-n; t2=0; for (i=2;i<=8;i++) t2+=$i
+ d2=$5+$6; d=t2-t1[j]
+ pct=(d>0)?(1-(d2-d1[j])/d)*100:0
+ gsub(/cpu/,"",name[j])
+ printf "%s:%d%% ", name[j], pct
+ }
+ BEGIN { printf "Cores: " }
+ END { print "" }'
+ ;;
+esac
diff --git a/scripts/date.sh b/scripts/date.sh
new file mode 100755
index 0000000..58df95a
--- /dev/null
+++ b/scripts/date.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+# date module -- dispatched by subcommand:
+# date.sh -> bar text, "YYYY-MM-DD"
+# date.sh menu -> popup definition, read once at startup (see README,
+# "Module-declared menus")
+mode="${1:-text}"
+
+case "$mode" in
+menu)
+ echo 'popup : hover : buttons'
+ echo 'popup_item : "Open calendar" : "gsimplecal"'
+ ;;
+*)
+ date '+%Y-%m-%d'
+ ;;
+esac
diff --git a/scripts/media.sh b/scripts/media.sh
new file mode 100755
index 0000000..55db0ba
--- /dev/null
+++ b/scripts/media.sh
@@ -0,0 +1,69 @@
+#!/bin/sh
+# media module -- MPRIS media controls via playerctl (works with most
+# players automatically: Spotify, VLC, mpv, Firefox/Chromium tabs, etc.),
+# dispatched by subcommand. Controls whichever player playerctl considers
+# active (usually whichever was most recently active) -- run `playerctl -l`
+# yourself to see all available players if you run more than one at once.
+# media.sh -> bar text: play/pause glyph + "Artist - Title"
+# media.sh track -> "Artist - Title", undecorated (popup info row)
+# media.sh art -> path to a local album-art image file, or nothing
+# if the current track has none (popup image row;
+# downloads+caches remote art URLs via curl)
+# media.sh prev / playpause / next -> playerctl actions (popup buttons)
+# media.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-text}"
+
+track() {
+ playerctl metadata --format '{{artist}} - {{title}}' 2>/dev/null
+}
+
+case "$mode" in
+menu)
+ self="$0"
+ echo 'popup : hover : buttons'
+ echo "popup_image : \"$self art\""
+ echo "popup_info : \"$self track\""
+ echo "popup_buttons : \"\" : \"$self prev\" : \"\" : \"$self playpause\" : \"\" : \"$self next\""
+ ;;
+track)
+ track
+ ;;
+art)
+ url=$(playerctl metadata mpris:artUrl 2>/dev/null)
+ case "$url" in
+ file://*)
+ path="${url#file://}"
+ [ -f "$path" ] && printf '%s' "$path"
+ ;;
+ http://*|https://*)
+ cache="${XDG_CACHE_HOME:-$HOME/.cache}/sxbar-media-art"
+ mkdir -p "$cache" 2>/dev/null
+ hash=$(printf '%s' "$url" | cksum | awk '{print $1}')
+ file="$cache/$hash"
+ if [ ! -s "$file" ] && command -v curl >/dev/null 2>&1; then
+ curl -fsSL "$url" -o "$file" 2>/dev/null
+ fi
+ [ -s "$file" ] && printf '%s' "$file"
+ ;;
+ esac
+ ;;
+prev)
+ playerctl previous 2>/dev/null
+ ;;
+playpause)
+ playerctl play-pause 2>/dev/null
+ ;;
+next)
+ playerctl next 2>/dev/null
+ ;;
+*)
+ st=$(playerctl status 2>/dev/null)
+ case "$st" in
+ Playing) glyph=' > ' ;;
+ Paused) glyph=' || ' ;;
+ *) exit 0 ;;
+ esac
+ printf '%s%s\n' "$glyph" "$(track)"
+ ;;
+esac
diff --git a/scripts/network.sh b/scripts/network.sh
new file mode 100755
index 0000000..667d0cf
--- /dev/null
+++ b/scripts/network.sh
@@ -0,0 +1,59 @@
+#!/bin/sh
+# network module -- everything the module needs, dispatched by subcommand:
+# network.sh -> bar text, "Online"/"Offline" (default route exists?)
+# network.sh wifi -> WiFi row: first wireless interface + its IPv4 (popup)
+# network.sh ethernet -> Ethernet row: first physical wired interface + its IPv4 (popup)
+# network.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-status}"
+
+case "$mode" in
+menu)
+ self="$0"
+ echo 'popup : hover : buttons'
+ echo "popup_info : \"$self wifi\""
+ echo "popup_info : \"$self ethernet\""
+ ;;
+status)
+ ip route show default 2>/dev/null | grep -q . && echo Online || echo Offline
+ ;;
+wifi)
+ # first interface with a /sys/class/net/<if>/wireless directory
+ i=$(for d in /sys/class/net/*/wireless; do
+ [ -d "$d" ] && basename "$(dirname "$d")" && break
+ done)
+
+ if [ -z "$i" ]; then
+ echo 'WiFi: none'
+ else
+ ip=$(ip -4 -o addr show "$i" 2>/dev/null | awk '{print $4}' | cut -d/ -f1)
+ if [ -n "$ip" ]; then
+ echo "WiFi ($i): $ip"
+ else
+ echo "WiFi ($i): disconnected"
+ fi
+ fi
+ ;;
+ethernet)
+ # first non-virtual, non-wireless interface of ARPHRD_ETHER type
+ i=$(for d in /sys/class/net/*; do
+ n=$(basename "$d")
+ case "$n" in
+ lo|docker*|veth*|br-*|virbr*|tun*|tap*) continue ;;
+ esac
+ [ -d "$d/wireless" ] && continue
+ [ "$(cat "$d/type" 2>/dev/null)" = "1" ] && echo "$n" && break
+ done)
+
+ if [ -z "$i" ]; then
+ echo 'Ethernet: none'
+ else
+ ip=$(ip -4 -o addr show "$i" 2>/dev/null | awk '{print $4}' | cut -d/ -f1)
+ if [ -n "$ip" ]; then
+ echo "Ethernet ($i): $ip"
+ else
+ echo "Ethernet ($i): disconnected"
+ fi
+ fi
+ ;;
+esac
diff --git a/scripts/taskbar.sh b/scripts/taskbar.sh
new file mode 100755
index 0000000..73ffa4b
--- /dev/null
+++ b/scripts/taskbar.sh
@@ -0,0 +1,41 @@
+#!/bin/sh
+# taskbar module -- one clickable entry per window on the current
+# workspace, so you can switch focus between them (e.g. sxwm's monocle
+# mode only shows one window at a time; this is how you reach the rest).
+# Needs wmctrl, and a window manager that actually acts on a
+# _NET_ACTIVE_WINDOW client message (as of this writing, that means a
+# patched sxwm -- see the "workspace icons"-adjacent commit/PR that adds
+# a _NET_ACTIVE_WINDOW handler to hdl_client_msg()).
+# taskbar.sh -> internal listing, read fresh every refresh
+# interval -- not meant to be run by hand. One
+# line per current-workspace window:
+# "Title" : "0xWINDOW_ID" : "command"
+# taskbar.sh focus ID -> activates/raises that window (bar click action)
+#
+# No `menu` case: unlike every other built-in module, taskbar renders its
+# entries directly in the bar itself (see README/wiki), not a hover popup,
+# so there's nothing for `<script> menu` to declare -- explicitly a no-op
+# below rather than falling through to the listing logic.
+mode="${1:-list}"
+
+case "$mode" in
+menu)
+ exit 0
+ ;;
+focus)
+ wmctrl -i -a "$2" 2>/dev/null
+ ;;
+list)
+ self="$0"
+ cur=$(wmctrl -d 2>/dev/null | awk '$2 == "*" { print $1 }')
+ [ -z "$cur" ] && exit 0
+ wmctrl -l 2>/dev/null | awk -v cur="$cur" -v self="$self" '
+ $2 == cur {
+ id = $1
+ title = $0
+ sub(/^[^ \t]+[ \t]+[^ \t]+[ \t]+[^ \t]+[ \t]+/, "", title)
+ gsub(/"/, "'"'"'", title)
+ printf "\"%s\" : \"%s\" : \"%s focus %s\"\n", title, id, self, id
+ }'
+ ;;
+esac
diff --git a/scripts/usermenu.sh b/scripts/usermenu.sh
new file mode 100755
index 0000000..198e600
--- /dev/null
+++ b/scripts/usermenu.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+# usermenu module -- dispatched by subcommand:
+# usermenu.sh -> bar text, current username
+# usermenu.sh menu -> popup definition, read once at startup (see README,
+# "Module-declared menus")
+#
+# This *is* the user menu -- add, remove or reorder popup_item lines below
+# to customize it, no sxbarc editing needed. sxwm
+# (https://github.com/uint23/sxwm) has no session manager or external IPC
+# to trigger its own `quit` keybind, so "Log out" ends the X session by
+# killing the WM -- adjust `pkill sxwm` for your own WM/session.
+mode="${1:-text}"
+
+case "$mode" in
+menu)
+ echo 'popup : hover : buttons'
+ echo 'popup_item : "Sleep" : "systemctl suspend"'
+ echo 'popup_item : "Log out" : "pkill sxwm"'
+ echo 'popup_item : "Shut down" : "systemctl poweroff"'
+ ;;
+*)
+ whoami
+ ;;
+esac
diff --git a/scripts/volume.sh b/scripts/volume.sh
new file mode 100755
index 0000000..a4748c0
--- /dev/null
+++ b/scripts/volume.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+# volume module -- dispatched by subcommand:
+# volume.sh -> bar text / slider starting value, "NN%"
+# volume.sh set NN% -> slider drag target
+# volume.sh menu -> popup definition, read once at startup (see
+# README, "Module-declared menus")
+mode="${1:-get}"
+
+case "$mode" in
+menu)
+ echo 'popup : hover : slider'
+ echo "popup_set : \"$0 set\""
+ ;;
+get)
+ # awk does the arithmetic itself; no bc/bash/xargs needed
+ LC_ALL=C wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null |
+ LC_ALL=C awk '/Volume:/ {printf "%d%%\n", $2 * 100}'
+ ;;
+set)
+ wpctl set-volume @DEFAULT_AUDIO_SINK@ "$2"
+ ;;
+esac
diff --git a/src/defs.h b/src/defs.h
index fdfd6e8..d528e09 100644
--- a/src/defs.h
+++ b/src/defs.h
@@ -27,26 +27,63 @@
#define POPUP_TRIGGER_CLICK 0
#define POPUP_TRIGGER_HOVER 1
-#define POPUP_ROW_TEXT 0 /* purely informational -- not clickable at all */
-#define POPUP_ROW_BUTTON 1 /* spawns command and closes the popup on click */
-#define POPUP_ROW_SLIDER 2 /* draggable 0-100% track; doesn't close on click/drag */
+#define POPUP_ROW_TEXT 0 /* purely informational -- not clickable at all */
+#define POPUP_ROW_BUTTON 1 /* spawns command and closes the popup on click */
+#define POPUP_ROW_SLIDER 2 /* draggable 0-100% track; doesn't close on click/drag */
+#define POPUP_ROW_IMAGE 3 /* renders an image file (e.g. album art); not clickable */
+#define POPUP_ROW_BUTTONS 4 /* one row split into N equal-width button segments,
+ * e.g. media transport controls (prev/play/next) */
+
+/* one segment of a POPUP_ROW_BUTTONS row -- same label/command shape as a
+ * plain POPUP_ROW_BUTTON, just laid out side by side instead of stacked */
+typedef struct PopupButton {
+ char *label;
+ char *command;
+} PopupButton;
/* one row of a popup. label_command, if set, is re-run fresh (via
* run_command()) every time the popup opens instead of using a fixed
* label -- used by TEXT and BUTTON rows for live status text (label
* itself is then overwritten in place and freed/reused across opens). A
* SLIDER row instead seeds its value from the module's own command
- * output, and set_command receives the new value as $1 when dragged. */
+ * output, and set_command receives the new value as $1 when dragged. An
+ * IMAGE row's image_command is re-run the same way as label_command, but
+ * its output is a path to a local image file (or empty for "no image
+ * this time"); `image` is the XImage decoded (via vendored stb_image.h)
+ * and scaled from that path by the most recent popup_open() (opaque here
+ * -- only sxbar.c touches it directly), sized image_w x image_h. A
+ * BUTTONS row's `buttons`/`button_count` hold its segments; labels are
+ * static (no per-segment label_command). A TEXT/BUTTON row whose label
+ * doesn't fit the popup's width (e.g. the popup's width came from an
+ * IMAGE/SLIDER/BUTTONS row instead of growing to fit this text) scrolls
+ * within it instead, using its own scroll_offset -- same marquee scheme
+ * as a bar module's max_width, just scoped to one popup row. */
typedef struct PopupItem {
int type;
char *label;
char *command;
char *label_command;
char *set_command;
+ char *image_command;
+ void *image;
+ int image_w, image_h;
+ PopupButton *buttons;
+ int button_count;
+ int scroll_offset; /* TEXT/BUTTON: marquee position, in pixels */
int value; /* SLIDER: current 0-100 */
int last_spawned; /* SLIDER: last value set_command was actually run for */
} PopupItem;
+/* one window entry in the built-in `taskbar` module -- see
+ * update_taskbar() (src/sxbar.c) for how these get populated from
+ * scripts/taskbar.sh's internal listing format, and id's role in
+ * highlighting whichever entry is the current _NET_ACTIVE_WINDOW */
+typedef struct TaskbarEntry {
+ char *label; /* window title */
+ char *command; /* spawned on click, e.g. "taskbar.sh focus 0x0140..." */
+ Window id;
+} TaskbarEntry;
+
typedef struct Module {
char *name;
char *command;
@@ -58,6 +95,10 @@ typedef struct Module {
char *prefix_command;
char *prefix_cached;
int min_width;
+ int max_width; /* 0 = no cap; text wider than this scrolls (marquee)
+ * instead of stretching the bar -- see max_width in
+ * sxbarc */
+ int scroll_offset; /* marquee: current scroll position, in pixels */
int on_secondary;
int align;
int icon_only; /* show only the prefix/icon, never the module's own text */
@@ -75,8 +116,22 @@ typedef struct Module {
int popup_item_max;
int popup_items_from_config; /* config popup_item/popup_info lines replace the built-in defaults, once */
int slider_item_idx; /* which popup_items[] entry popup_set manages, or -1 */
+ /* the built-in `taskbar` module only: renders one clickable segment
+ * per current-workspace window directly in the bar itself, instead
+ * of a single cached_output string -- see update_taskbar() and the
+ * dedicated block in draw_bar_into() (src/sxbar.c) */
+ TaskbarEntry *taskbar_entries;
+ int taskbar_entry_count;
} Module;
+/* maps a workspace's displayed label -- its _NET_DESKTOP_NAMES string,
+ * e.g. "1" -- to replacement text, e.g. a Nerd Font glyph, via the
+ * `workspace_icon` config directive */
+typedef struct WorkspaceIcon {
+ char *name;
+ char *icon;
+} WorkspaceIcon;
+
typedef struct Config {
int bottom_bar;
int height;
@@ -95,6 +150,9 @@ typedef struct Config {
int module_count;
int max_modules;
int secondary_bar;
+ WorkspaceIcon *workspace_icons;
+ int workspace_icon_count;
+ int workspace_icon_max;
} Config;
/* one on-screen bar window: either the primary bar (workspaces + all
@@ -118,7 +176,8 @@ typedef struct Popup {
int bar_idx;
int trigger;
int x, y, w, h;
- int hover_row; /* row index highlighted (BUTTON rows only), or -1 */
+ int hover_row; /* row index highlighted (BUTTON/BUTTONS rows only), or -1 */
+ int hover_col; /* BUTTONS row: which segment is highlighted, or -1 */
int dragging_row; /* row index of the SLIDER row being dragged, or -1 */
} Popup;
diff --git a/src/parser.c b/src/parser.c
index b0b76a3..8559200 100644
--- a/src/parser.c
+++ b/src/parser.c
@@ -134,6 +134,15 @@ static void clear_builtin_popup_items(Module *m)
free(m->popup_items[i].command);
free(m->popup_items[i].label_command);
free(m->popup_items[i].set_command);
+ free(m->popup_items[i].image_command);
+ /* .image itself is only ever populated by popup_open() (sxbar.c) at
+ * runtime, never during config parsing -- this always runs before
+ * any popup has opened, so there's nothing loaded yet to free here */
+ for (int b = 0; b < m->popup_items[i].button_count; b++) {
+ free(m->popup_items[i].buttons[b].label);
+ free(m->popup_items[i].buttons[b].command);
+ }
+ free(m->popup_items[i].buttons);
}
m->popup_item_count = 0;
m->slider_item_idx = -1;
@@ -153,6 +162,399 @@ static int grow_popup_items(Module *m)
return 0;
}
+/* ---- shared popup-directive application ----
+ *
+ * Each of these takes the directive's value with the module-name field
+ * already stripped off (e.g. "hover : buttons" for `popup`, or
+ * "\"Label\" : \"command\"" for `popup_item`), plus `ctx`/`lineno` to
+ * identify the source in error messages. This lets the exact same parsing
+ * be driven both by sxbarc lines (which have a name field to strip first)
+ * and by a module script's own `<script> menu` output (which never has a
+ * name field, since a script only ever describes itself).
+ *
+ * `from_sxbarc` on the item/info variants controls whether the built-in
+ * default rows get cleared first: sxbarc directives should replace a
+ * script's default rows on their first line (same as they used to replace
+ * the old compile-time defaults), but a script's own `menu` output *is*
+ * the set of default rows, so loading it must not trip that "already
+ * customized by sxbarc" flag. */
+
+static int apply_popup(Module *m, char *rest, const char *ctx, int lineno)
+{
+ char *p2 = strchr(rest, ':');
+ if (!p2) {
+ fprintf(stderr, "%s:%d: popup missing trigger/type\n", ctx, lineno);
+ return -1;
+ }
+ *p2 = '\0';
+ char *trig_s = strip(rest);
+ char *type_s = strip(p2 + 1);
+ strip_comment(type_s);
+ if (!strcmp(trig_s, "hover")) {
+ m->popup_trigger = POPUP_TRIGGER_HOVER;
+ } else if (!strcmp(trig_s, "click")) {
+ m->popup_trigger = POPUP_TRIGGER_CLICK;
+ } else {
+ fprintf(stderr, "%s:%d: popup: trigger must be 'hover' or 'click', got '%s'\n",
+ ctx, lineno, trig_s);
+ return -1;
+ }
+ /* popups are just a list of rows now (text/button/slider can be mixed
+ * freely via popup_item/popup_info/popup_set) -- this field only still
+ * exists so older configs keep parsing; both values just mean "this
+ * module has a popup" */
+ if (!strcmp(type_s, "buttons") || !strcmp(type_s, "slider")) {
+ m->popup_type = POPUP_BUTTONS;
+ } else {
+ fprintf(stderr, "%s:%d: popup: type must be 'buttons' or 'slider', got '%s'\n",
+ ctx, lineno, type_s);
+ return -1;
+ }
+ return 0;
+}
+
+static int apply_popup_item(Module *m, char *rest, const char *ctx, int lineno, int from_sxbarc)
+{
+ char *after = strip(rest);
+ if (*after != '"' && *after != '\'') {
+ fprintf(stderr, "%s:%d: popup_item label must be quoted\n", ctx, lineno);
+ return -1;
+ }
+ char q = *after;
+ char *label_start = after + 1;
+ char *closing = strchr(label_start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_item label missing closing quote\n", ctx, lineno);
+ return -1;
+ }
+ *closing = '\0';
+
+ char *tail = strip(closing + 1);
+ if (*tail != ':') {
+ fprintf(stderr, "%s:%d: popup_item missing command\n", ctx, lineno);
+ return -1;
+ }
+ tail = strip(tail + 1);
+ if (*tail != '"' && *tail != '\'') {
+ fprintf(stderr, "%s:%d: popup_item command must be quoted\n", ctx, lineno);
+ return -1;
+ }
+ q = *tail;
+ char *cmd_start = tail + 1;
+ closing = strchr(cmd_start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_item command missing closing quote\n", ctx, lineno);
+ return -1;
+ }
+ *closing = '\0';
+
+ if (from_sxbarc)
+ clear_builtin_popup_items(m);
+ if (grow_popup_items(m) < 0) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ return -1;
+ }
+ m->popup_items[m->popup_item_count].type = POPUP_ROW_BUTTON;
+ m->popup_items[m->popup_item_count].label = strdup(label_start);
+ m->popup_items[m->popup_item_count].command = expand_home(cmd_start);
+ m->popup_items[m->popup_item_count].label_command = NULL;
+ m->popup_items[m->popup_item_count].set_command = NULL;
+ m->popup_items[m->popup_item_count].image_command = NULL;
+ m->popup_items[m->popup_item_count].image = NULL;
+ m->popup_items[m->popup_item_count].image_w = 0;
+ m->popup_items[m->popup_item_count].image_h = 0;
+ m->popup_items[m->popup_item_count].buttons = NULL;
+ m->popup_items[m->popup_item_count].button_count = 0;
+ m->popup_items[m->popup_item_count].scroll_offset = 0;
+ m->popup_item_count++;
+ return 0;
+}
+
+static int apply_popup_info(Module *m, char *rest, const char *ctx, int lineno, int from_sxbarc)
+{
+ char *after = strip(rest);
+ if (*after != '"' && *after != '\'') {
+ fprintf(stderr, "%s:%d: popup_info command must be quoted\n", ctx, lineno);
+ return -1;
+ }
+ char q = *after;
+ char *cmd_start = after + 1;
+ char *closing = strchr(cmd_start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_info command missing closing quote\n", ctx, lineno);
+ return -1;
+ }
+ *closing = '\0';
+
+ if (from_sxbarc)
+ clear_builtin_popup_items(m);
+ if (grow_popup_items(m) < 0) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ return -1;
+ }
+ m->popup_items[m->popup_item_count].type = POPUP_ROW_TEXT;
+ m->popup_items[m->popup_item_count].label = NULL;
+ m->popup_items[m->popup_item_count].command = NULL;
+ m->popup_items[m->popup_item_count].label_command = expand_home(cmd_start);
+ m->popup_items[m->popup_item_count].set_command = NULL;
+ m->popup_items[m->popup_item_count].image_command = NULL;
+ m->popup_items[m->popup_item_count].image = NULL;
+ m->popup_items[m->popup_item_count].image_w = 0;
+ m->popup_items[m->popup_item_count].image_h = 0;
+ m->popup_items[m->popup_item_count].buttons = NULL;
+ m->popup_items[m->popup_item_count].button_count = 0;
+ m->popup_items[m->popup_item_count].scroll_offset = 0;
+ m->popup_item_count++;
+ return 0;
+}
+
+static int apply_popup_image(Module *m, char *rest, const char *ctx, int lineno, int from_sxbarc)
+{
+ /* rest: "command" -- stdout is a path to a local image file (e.g. album
+ * art), re-run fresh every time the popup opens, same convention as
+ * popup_info's label_command. Empty/failed output just means no image
+ * this time -- the row still exists, it renders blank. */
+ char *after = strip(rest);
+ if (*after != '"' && *after != '\'') {
+ fprintf(stderr, "%s:%d: popup_image command must be quoted\n", ctx, lineno);
+ return -1;
+ }
+ char q = *after;
+ char *cmd_start = after + 1;
+ char *closing = strchr(cmd_start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_image command missing closing quote\n", ctx, lineno);
+ return -1;
+ }
+ *closing = '\0';
+
+ if (from_sxbarc)
+ clear_builtin_popup_items(m);
+ if (grow_popup_items(m) < 0) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ return -1;
+ }
+ PopupItem *it = &m->popup_items[m->popup_item_count];
+ it->type = POPUP_ROW_IMAGE;
+ it->label = NULL;
+ it->command = NULL;
+ it->label_command = NULL;
+ it->set_command = NULL;
+ it->image_command = expand_home(cmd_start);
+ it->image = NULL;
+ it->image_w = 0;
+ it->image_h = 0;
+ it->buttons = NULL;
+ it->button_count = 0;
+ it->scroll_offset = 0;
+ m->popup_item_count++;
+ return 0;
+}
+
+/* free a partially- or fully-built button array on a parse error, before
+ * returning -- nothing has been attached to a Module yet at that point */
+static void free_parsed_buttons(PopupButton *btns, int count)
+{
+ for (int i = 0; i < count; i++) {
+ free(btns[i].label);
+ free(btns[i].command);
+ }
+ free(btns);
+}
+
+static int apply_popup_buttons(Module *m, char *rest, const char *ctx, int lineno, int from_sxbarc)
+{
+ /* rest: "Label1" : "command1" : "Label2" : "command2" ... -- one row
+ * split into N equal-width button segments side by side, e.g. media
+ * transport controls (glyphs work well as labels here: prev/play-pause/
+ * next icons instead of stacking three full-width text rows). */
+ PopupButton *btns = NULL;
+ int count = 0, max = 0;
+ char *p = rest;
+
+ for (;;) {
+ p = strip(p);
+ if (!*p)
+ break;
+ if (*p != '"' && *p != '\'') {
+ fprintf(stderr, "%s:%d: popup_buttons: expected a quoted label or command, got '%s'\n",
+ ctx, lineno, p);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+ char q = *p;
+ char *start = p + 1;
+ char *closing = strchr(start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_buttons: missing closing quote\n", ctx, lineno);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+ *closing = '\0';
+ p = closing + 1;
+
+ if (count % 2 == 0) {
+ if (count / 2 >= max) {
+ int newmax = max ? max * 2 : 4;
+ PopupButton *tmp = realloc(btns, newmax * sizeof *tmp);
+ if (!tmp) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+ btns = tmp;
+ max = newmax;
+ }
+ btns[count / 2].label = strdup(start);
+ btns[count / 2].command = NULL;
+ } else {
+ btns[count / 2].command = expand_home(start);
+ }
+ count++;
+
+ p = strip(p);
+ if (!*p)
+ break;
+ if (*p != ':') {
+ fprintf(stderr, "%s:%d: popup_buttons: expected ':' after \"%s\"\n", ctx, lineno, start);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+ p++;
+ }
+
+ if (count == 0 || count % 2 != 0) {
+ fprintf(stderr, "%s:%d: popup_buttons: needs an even number of \"label\" : \"command\" pairs\n",
+ ctx, lineno);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+
+ if (from_sxbarc)
+ clear_builtin_popup_items(m);
+ if (grow_popup_items(m) < 0) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ free_parsed_buttons(btns, count);
+ return -1;
+ }
+ PopupItem *it = &m->popup_items[m->popup_item_count];
+ it->type = POPUP_ROW_BUTTONS;
+ it->label = NULL;
+ it->command = NULL;
+ it->label_command = NULL;
+ it->set_command = NULL;
+ it->image_command = NULL;
+ it->image = NULL;
+ it->image_w = 0;
+ it->image_h = 0;
+ it->buttons = btns;
+ it->button_count = count / 2;
+ it->scroll_offset = 0;
+ m->popup_item_count++;
+ return 0;
+}
+
+static int apply_popup_set(Module *m, char *rest, const char *ctx, int lineno)
+{
+ char *after = strip(rest);
+ if (*after != '"' && *after != '\'') {
+ fprintf(stderr, "%s:%d: popup_set command must be quoted\n", ctx, lineno);
+ return -1;
+ }
+ char q = *after;
+ char *cmd_start = after + 1;
+ char *closing = strchr(cmd_start, q);
+ if (!closing) {
+ fprintf(stderr, "%s:%d: popup_set command missing closing quote\n", ctx, lineno);
+ return -1;
+ }
+ *closing = '\0';
+
+ if (m->slider_item_idx >= 0) {
+ free(m->popup_items[m->slider_item_idx].set_command);
+ m->popup_items[m->slider_item_idx].set_command = expand_home(cmd_start);
+ } else {
+ if (grow_popup_items(m) < 0) {
+ fprintf(stderr, "%s: out of memory\n", ctx);
+ return -1;
+ }
+ PopupItem *it = &m->popup_items[m->popup_item_count];
+ it->type = POPUP_ROW_SLIDER;
+ it->label = NULL;
+ it->command = NULL;
+ it->label_command = NULL;
+ it->set_command = expand_home(cmd_start);
+ it->image_command = NULL;
+ it->image = NULL;
+ it->image_w = 0;
+ it->image_h = 0;
+ it->buttons = NULL;
+ it->button_count = 0;
+ it->scroll_offset = 0;
+ it->value = 0;
+ it->last_spawned = 0;
+ m->slider_item_idx = m->popup_item_count;
+ m->popup_item_count++;
+ m->popup_type = POPUP_BUTTONS; /* "has a popup" */
+ }
+ return 0;
+}
+
+/* run "<script_path> menu" and apply each line of its output the same way
+ * sxbarc's own popup/popup_item/popup_info/popup_image/popup_set
+ * directives are applied, just without a module-name field to strip off
+ * first. These
+ * count as default rows, not sxbarc overrides: `popup_items_from_config`
+ * is left untouched, so sxbarc can still replace them afterwards exactly
+ * like it could replace the old compile-time defaults. */
+void load_popup_from_script(Module *m, const char *script_path)
+{
+ char cmd[PATH_MAX + 8];
+ snprintf(cmd, sizeof cmd, "%s menu", script_path);
+
+ FILE *fp = popen(cmd, "r");
+ if (!fp)
+ return;
+
+ char ctx[PATH_MAX + 8];
+ snprintf(ctx, sizeof ctx, "%s menu", script_path);
+
+ char line[1024];
+ int lineno = 0;
+ while (fgets(line, sizeof line, fp)) {
+ lineno++;
+ char *s = strip(line);
+ if (!*s || *s == '#')
+ continue;
+
+ char *sep = strchr(s, ':');
+ if (!sep) {
+ fprintf(stderr, "%s:%d: missing ':'\n", ctx, lineno);
+ continue;
+ }
+ *sep = '\0';
+ char *key = strip(s);
+ char *rest = strip(sep + 1);
+
+ if (!strcmp(key, "popup")) {
+ apply_popup(m, rest, ctx, lineno);
+ } else if (!strcmp(key, "popup_item")) {
+ apply_popup_item(m, rest, ctx, lineno, 0);
+ } else if (!strcmp(key, "popup_info")) {
+ apply_popup_info(m, rest, ctx, lineno, 0);
+ } else if (!strcmp(key, "popup_image")) {
+ apply_popup_image(m, rest, ctx, lineno, 0);
+ } else if (!strcmp(key, "popup_buttons")) {
+ apply_popup_buttons(m, rest, ctx, lineno, 0);
+ } else if (!strcmp(key, "popup_set")) {
+ apply_popup_set(m, rest, ctx, lineno);
+ } else {
+ fprintf(stderr, "%s:%d: unknown directive '%s'\n", ctx, lineno, key);
+ }
+ }
+ pclose(fp);
+}
+
int parse_config(Config *cfg)
{
char path[PATH_MAX];
@@ -215,6 +617,47 @@ int parse_config(Config *cfg)
/* enable a second bar on the opposite edge from `bottom_bar`,
* showing only modules tagged `bar : module_name : secondary` */
cfg->secondary_bar = parse_bool(rest);
+ } else if (!strcmp(key, "workspace_icon")) {
+ /* workspace_icon : name : "icon text" -- replaces a workspace's
+ * displayed label (its _NET_DESKTOP_NAMES string, e.g. "1")
+ * with this text instead, e.g. a Nerd Font glyph. Repeatable,
+ * one per workspace name. */
+ char *p1 = strchr(rest, ':');
+ if (!p1) {
+ fprintf(stderr, "sxbarc:%d: workspace_icon missing name and text\n", lineno);
+ continue;
+ }
+ *p1 = '\0';
+ char *name = strip(rest);
+ char *after = strip(p1 + 1);
+
+ if (*after != '"' && *after != '\'') {
+ fprintf(stderr, "sxbarc:%d: workspace_icon text must be quoted\n", lineno);
+ continue;
+ }
+ char q = *after;
+ char *text_start = after + 1;
+ char *closing = strchr(text_start, q);
+ if (!closing) {
+ fprintf(stderr, "sxbarc:%d: workspace_icon text missing closing quote\n", lineno);
+ continue;
+ }
+ *closing = '\0';
+
+ if (cfg->workspace_icon_count >= cfg->workspace_icon_max) {
+ int newmax = cfg->workspace_icon_max ? cfg->workspace_icon_max * 2 : 4;
+ WorkspaceIcon *tmp = realloc(cfg->workspace_icons, newmax * sizeof *tmp);
+ if (!tmp) {
+ fprintf(stderr, "sxbarc: out of memory\n");
+ fclose(f);
+ return -1;
+ }
+ cfg->workspace_icons = tmp;
+ cfg->workspace_icon_max = newmax;
+ }
+ cfg->workspace_icons[cfg->workspace_icon_count].name = strdup(name);
+ cfg->workspace_icons[cfg->workspace_icon_count].icon = strdup(text_start);
+ cfg->workspace_icon_count++;
} else if (!strcmp(key, "module")) {
/* module : name : enabled : interval */
char *p1 = strchr(rest, ':');
@@ -337,6 +780,25 @@ int parse_config(Config *cfg)
continue;
}
m->min_width = atoi(val);
+ } else if (!strcmp(key, "max_width")) {
+ /* max_width : module_name : max_pixels -- caps the module's
+ * rendered text at this width; text wider than it scrolls
+ * (marquee) left instead of stretching the bar */
+ char *p1 = strchr(rest, ':');
+ if (!p1) {
+ fprintf(stderr, "sxbarc:%d: max_width missing name and value\n", lineno);
+ continue;
+ }
+ *p1 = '\0';
+ char *name = strip(rest);
+ char *val = strip(p1 + 1);
+ strip_comment(val);
+ Module *m = find_module(cfg, name);
+ if (!m) {
+ fprintf(stderr, "sxbarc:%d: max_width: unknown module '%s'\n", lineno, name);
+ continue;
+ }
+ m->max_width = atoi(val);
} else if (!strcmp(key, "bar")) {
/* bar : module_name : primary|secondary -- which bar the module
* is drawn on when secondary_bar is enabled (default: primary) */
@@ -417,40 +879,12 @@ int parse_config(Config *cfg)
*p1 = '\0';
char *name = strip(rest);
char *rest2 = strip(p1 + 1);
- char *p2 = strchr(rest2, ':');
- if (!p2) {
- fprintf(stderr, "sxbarc:%d: popup missing trigger/type\n", lineno);
- continue;
- }
- *p2 = '\0';
- char *trig_s = strip(rest2);
- char *type_s = strip(p2 + 1);
- strip_comment(type_s);
Module *m = find_module(cfg, name);
if (!m) {
fprintf(stderr, "sxbarc:%d: popup: unknown module '%s'\n", lineno, name);
continue;
}
- if (!strcmp(trig_s, "hover")) {
- m->popup_trigger = POPUP_TRIGGER_HOVER;
- } else if (!strcmp(trig_s, "click")) {
- m->popup_trigger = POPUP_TRIGGER_CLICK;
- } else {
- fprintf(stderr, "sxbarc:%d: popup: trigger must be 'hover' or 'click', got '%s'\n",
- lineno, trig_s);
- continue;
- }
- /* popups are just a list of rows now (text/button/slider can be
- * mixed freely via popup_item/popup_info/popup_set) -- this
- * field only still exists so older configs keep parsing; both
- * values just mean "this module has a popup" */
- if (!strcmp(type_s, "buttons") || !strcmp(type_s, "slider")) {
- m->popup_type = POPUP_BUTTONS;
- } else {
- fprintf(stderr, "sxbarc:%d: popup: type must be 'buttons' or 'slider', got '%s'\n",
- lineno, type_s);
- continue;
- }
+ apply_popup(m, rest2, "sxbarc", lineno);
} else if (!strcmp(key, "popup_item")) {
/* popup_item : module_name : "Label" : "command" -- one row of a
* POPUP_BUTTONS popup. The first popup_item line for a module
@@ -463,56 +897,12 @@ int parse_config(Config *cfg)
*p1 = '\0';
char *name = strip(rest);
char *after = strip(p1 + 1);
-
- if (*after != '"' && *after != '\'') {
- fprintf(stderr, "sxbarc:%d: popup_item label must be quoted\n", lineno);
- continue;
- }
- char q = *after;
- char *label_start = after + 1;
- char *closing = strchr(label_start, q);
- if (!closing) {
- fprintf(stderr, "sxbarc:%d: popup_item label missing closing quote\n", lineno);
- continue;
- }
- *closing = '\0';
-
- char *tail = strip(closing + 1);
- if (*tail != ':') {
- fprintf(stderr, "sxbarc:%d: popup_item missing command\n", lineno);
- continue;
- }
- tail = strip(tail + 1);
- if (*tail != '"' && *tail != '\'') {
- fprintf(stderr, "sxbarc:%d: popup_item command must be quoted\n", lineno);
- continue;
- }
- q = *tail;
- char *cmd_start = tail + 1;
- closing = strchr(cmd_start, q);
- if (!closing) {
- fprintf(stderr, "sxbarc:%d: popup_item command missing closing quote\n", lineno);
- continue;
- }
- *closing = '\0';
-
Module *m = find_module(cfg, name);
if (!m) {
fprintf(stderr, "sxbarc:%d: popup_item: unknown module '%s'\n", lineno, name);
continue;
}
- clear_builtin_popup_items(m);
- if (grow_popup_items(m) < 0) {
- fprintf(stderr, "sxbarc: out of memory\n");
- fclose(f);
- return -1;
- }
- m->popup_items[m->popup_item_count].type = POPUP_ROW_BUTTON;
- m->popup_items[m->popup_item_count].label = strdup(label_start);
- m->popup_items[m->popup_item_count].command = expand_home(cmd_start);
- m->popup_items[m->popup_item_count].label_command = NULL;
- m->popup_items[m->popup_item_count].set_command = NULL;
- m->popup_item_count++;
+ apply_popup_item(m, after, "sxbarc", lineno, 1);
} else if (!strcmp(key, "popup_info")) {
/* popup_info : module_name : "shell command" -- one purely
* informational row: its label is this command's output,
@@ -526,37 +916,50 @@ int parse_config(Config *cfg)
*p1 = '\0';
char *name = strip(rest);
char *after = strip(p1 + 1);
-
- if (*after != '"' && *after != '\'') {
- fprintf(stderr, "sxbarc:%d: popup_info command must be quoted\n", lineno);
+ Module *m = find_module(cfg, name);
+ if (!m) {
+ fprintf(stderr, "sxbarc:%d: popup_info: unknown module '%s'\n", lineno, name);
continue;
}
- char q = *after;
- char *cmd_start = after + 1;
- char *closing = strchr(cmd_start, q);
- if (!closing) {
- fprintf(stderr, "sxbarc:%d: popup_info command missing closing quote\n", lineno);
+ apply_popup_info(m, after, "sxbarc", lineno, 1);
+ } else if (!strcmp(key, "popup_image")) {
+ /* popup_image : module_name : "shell command" -- one image row:
+ * the command's stdout is a path to a local image file (e.g.
+ * album art), re-run fresh every time the popup opens. Not
+ * clickable, same as popup_info. */
+ char *p1 = strchr(rest, ':');
+ if (!p1) {
+ fprintf(stderr, "sxbarc:%d: popup_image missing name and command\n", lineno);
continue;
}
- *closing = '\0';
-
+ *p1 = '\0';
+ char *name = strip(rest);
+ char *after = strip(p1 + 1);
Module *m = find_module(cfg, name);
if (!m) {
- fprintf(stderr, "sxbarc:%d: popup_info: unknown module '%s'\n", lineno, name);
+ fprintf(stderr, "sxbarc:%d: popup_image: unknown module '%s'\n", lineno, name);
continue;
}
- clear_builtin_popup_items(m);
- if (grow_popup_items(m) < 0) {
- fprintf(stderr, "sxbarc: out of memory\n");
- fclose(f);
- return -1;
+ apply_popup_image(m, after, "sxbarc", lineno, 1);
+ } else if (!strcmp(key, "popup_buttons")) {
+ /* popup_buttons : module_name : "Label1" : "command1" : "Label2" :
+ * "command2" ... -- one row split into N equal-width button
+ * segments side by side (e.g. media transport controls), instead
+ * of N separate full-width popup_item rows. */
+ char *p1 = strchr(rest, ':');
+ if (!p1) {
+ fprintf(stderr, "sxbarc:%d: popup_buttons missing name and buttons\n", lineno);
+ continue;
+ }
+ *p1 = '\0';
+ char *name = strip(rest);
+ char *after = strip(p1 + 1);
+ Module *m = find_module(cfg, name);
+ if (!m) {
+ fprintf(stderr, "sxbarc:%d: popup_buttons: unknown module '%s'\n", lineno, name);
+ continue;
}
- m->popup_items[m->popup_item_count].type = POPUP_ROW_TEXT;
- m->popup_items[m->popup_item_count].label = NULL;
- m->popup_items[m->popup_item_count].command = NULL;
- m->popup_items[m->popup_item_count].label_command = expand_home(cmd_start);
- m->popup_items[m->popup_item_count].set_command = NULL;
- m->popup_item_count++;
+ apply_popup_buttons(m, after, "sxbarc", lineno, 1);
} else if (!strcmp(key, "popup_set")) {
/* popup_set : module_name : "command" -- adds (or updates) one
* slider row for this module; receives the new value (0-100)
@@ -571,46 +974,12 @@ int parse_config(Config *cfg)
*p1 = '\0';
char *name = strip(rest);
char *after = strip(p1 + 1);
-
- if (*after != '"' && *after != '\'') {
- fprintf(stderr, "sxbarc:%d: popup_set command must be quoted\n", lineno);
- continue;
- }
- char q = *after;
- char *cmd_start = after + 1;
- char *closing = strchr(cmd_start, q);
- if (!closing) {
- fprintf(stderr, "sxbarc:%d: popup_set command missing closing quote\n", lineno);
- continue;
- }
- *closing = '\0';
-
Module *m = find_module(cfg, name);
if (!m) {
fprintf(stderr, "sxbarc:%d: popup_set: unknown module '%s'\n", lineno, name);
continue;
}
- if (m->slider_item_idx >= 0) {
- free(m->popup_items[m->slider_item_idx].set_command);
- m->popup_items[m->slider_item_idx].set_command = expand_home(cmd_start);
- } else {
- if (grow_popup_items(m) < 0) {
- fprintf(stderr, "sxbarc: out of memory\n");
- fclose(f);
- return -1;
- }
- PopupItem *it = &m->popup_items[m->popup_item_count];
- it->type = POPUP_ROW_SLIDER;
- it->label = NULL;
- it->command = NULL;
- it->label_command = NULL;
- it->set_command = expand_home(cmd_start);
- it->value = 0;
- it->last_spawned = 0;
- m->slider_item_idx = m->popup_item_count;
- m->popup_item_count++;
- m->popup_type = POPUP_BUTTONS; /* "has a popup" */
- }
+ apply_popup_set(m, after, "sxbarc", lineno);
} else if (!strcmp(key, "click") || !strcmp(key, "scroll_up") || !strcmp(key, "scroll_down") ||
!strcmp(key, "prefix_cmd") || !strcmp(key, "icon_cmd")) {
/* click/scroll_up/scroll_down/prefix_cmd/icon_cmd : module_name : "command" */
diff --git a/src/parser.h b/src/parser.h
index d5f8237..1552099 100644
--- a/src/parser.h
+++ b/src/parser.h
@@ -2,3 +2,12 @@
#include "defs.h"
int parse_config(Config *cfg);
+
+/* run "<script_path> menu" and apply whatever popup/popup_item/popup_info/
+ * popup_image/popup_set lines it prints to m, exactly as sxbarc's own directives are
+ * applied (minus the module-name field, since a script only ever describes
+ * itself) -- lets a built-in module's script declare its own default popup
+ * content instead of it being hardcoded in init_modules(). sxbarc can still
+ * override the result afterwards, same as it could override the old
+ * compile-time defaults. */
+void load_popup_from_script(Module *m, const char *script_path);
diff --git a/src/stb_image.h b/src/stb_image.h
new file mode 100644
index 0000000..9eedabe
--- /dev/null
+++ b/src/stb_image.h
@@ -0,0 +1,7988 @@
+/* stb_image - v2.30 - public domain image loader - http://nothings.org/stb
+ no warranty implied; use at your own risk
+
+ Do this:
+ #define STB_IMAGE_IMPLEMENTATION
+ before you include this file in *one* C or C++ file to create the implementation.
+
+ // i.e. it should look like this:
+ #include ...
+ #include ...
+ #include ...
+ #define STB_IMAGE_IMPLEMENTATION
+ #include "stb_image.h"
+
+ You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
+ And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
+
+
+ QUICK NOTES:
+ Primarily of interest to game developers and other people who can
+ avoid problematic images and only need the trivial interface
+
+ JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
+ PNG 1/2/4/8/16-bit-per-channel
+
+ TGA (not sure what subset, if a subset)
+ BMP non-1bpp, non-RLE
+ PSD (composited view only, no extra channels, 8/16 bit-per-channel)
+
+ GIF (*comp always reports as 4-channel)
+ HDR (radiance rgbE format)
+ PIC (Softimage PIC)
+ PNM (PPM and PGM binary only)
+
+ Animated GIF still needs a proper API, but here's one way to do it:
+ http://gist.github.com/urraka/685d9a6340b26b830d49
+
+ - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
+ - decode from arbitrary I/O callbacks
+ - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
+
+ Full documentation under "DOCUMENTATION" below.
+
+
+LICENSE
+
+ See end of file for license information.
+
+RECENT REVISION HISTORY:
+
+ 2.30 (2024-05-31) avoid erroneous gcc warning
+ 2.29 (2023-05-xx) optimizations
+ 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff
+ 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes
+ 2.26 (2020-07-13) many minor fixes
+ 2.25 (2020-02-02) fix warnings
+ 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically
+ 2.23 (2019-08-11) fix clang static analysis warning
+ 2.22 (2019-03-04) gif fixes, fix warnings
+ 2.21 (2019-02-25) fix typo in comment
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes
+ 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64
+ RGB-format JPEG; remove white matting in PSD;
+ allocate large structures on the stack;
+ correct channel count for PNG & BMP
+ 2.10 (2016-01-22) avoid warning introduced in 2.09
+ 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED
+
+ See end of file for full revision history.
+
+
+ ============================ Contributors =========================
+
+ Image formats Extensions, features
+ Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info)
+ Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info)
+ Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG)
+ Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks)
+ Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG)
+ Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip)
+ Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD)
+ github:urraka (animated gif) Junggon Kim (PNM comments)
+ Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA)
+ socks-the-fox (16-bit PNG)
+ Jeremy Sawicki (handle all ImageNet JPGs)
+ Optimizations & bugfixes Mikhail Morozov (1-bit BMP)
+ Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)
+ Arseny Kapoulkine Simon Breuss (16-bit PNM)
+ John-Mark Allen
+ Carmelo J Fdez-Aguera
+
+ Bug & warning fixes
+ Marc LeBlanc David Woo Guillaume George Martins Mozeiko
+ Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski
+ Phil Jordan Dave Moore Roy Eltham
+ Hayaki Saito Nathan Reed Won Chun
+ Luke Graham Johan Duparc Nick Verigakis the Horde3D community
+ Thomas Ruf Ronny Chevalier github:rlyeh
+ Janez Zemva John Bartholomew Michal Cichon github:romigrou
+ Jonathan Blow Ken Hamada Tero Hanninen github:svdijk
+ Eugene Golushkov Laurent Gomila Cort Stratton github:snagar
+ Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex
+ Cass Everitt Ryamond Barbiero github:grim210
+ Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw
+ Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus
+ Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo
+ Julian Raschke Gregory Mullen Christian Floisand github:darealshinji
+ Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007
+ Brad Weinberger Matvey Cherevko github:mosra
+ Luca Sas Alexander Veselov Zack Middleton [reserved]
+ Ryan C. Gordon [reserved] [reserved]
+ DO NOT ADD YOUR NAME HERE
+
+ Jacko Dirks
+
+ To add your name to the credits, pick a random blank space in the middle and fill it.
+ 80% of merge conflicts on stb PRs are due to people adding their name at the end
+ of the credits.
+*/
+
+#ifndef STBI_INCLUDE_STB_IMAGE_H
+#define STBI_INCLUDE_STB_IMAGE_H
+
+// DOCUMENTATION
+//
+// Limitations:
+// - no 12-bit-per-channel JPEG
+// - no JPEGs with arithmetic coding
+// - GIF always returns *comp=4
+//
+// Basic usage (see HDR discussion below for HDR usage):
+// int x,y,n;
+// unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
+// // ... process data if not NULL ...
+// // ... x = width, y = height, n = # 8-bit components per pixel ...
+// // ... replace '0' with '1'..'4' to force that many components per pixel
+// // ... but 'n' will always be the number that it would have been if you said 0
+// stbi_image_free(data);
+//
+// Standard parameters:
+// int *x -- outputs image width in pixels
+// int *y -- outputs image height in pixels
+// int *channels_in_file -- outputs # of image components in image file
+// int desired_channels -- if non-zero, # of image components requested in result
+//
+// The return value from an image loader is an 'unsigned char *' which points
+// to the pixel data, or NULL on an allocation failure or if the image is
+// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
+// with each pixel consisting of N interleaved 8-bit components; the first
+// pixel pointed to is top-left-most in the image. There is no padding between
+// image scanlines or between pixels, regardless of format. The number of
+// components N is 'desired_channels' if desired_channels is non-zero, or
+// *channels_in_file otherwise. If desired_channels is non-zero,
+// *channels_in_file has the number of components that _would_ have been
+// output otherwise. E.g. if you set desired_channels to 4, you will always
+// get RGBA output, but you can check *channels_in_file to see if it's trivially
+// opaque because e.g. there were only 3 channels in the source image.
+//
+// An output image with N components has the following components interleaved
+// in this order in each pixel:
+//
+// N=#comp components
+// 1 grey
+// 2 grey, alpha
+// 3 red, green, blue
+// 4 red, green, blue, alpha
+//
+// If image loading fails for any reason, the return value will be NULL,
+// and *x, *y, *channels_in_file will be unchanged. The function
+// stbi_failure_reason() can be queried for an extremely brief, end-user
+// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS
+// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
+// more user-friendly ones.
+//
+// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
+//
+// To query the width, height and component count of an image without having to
+// decode the full file, you can use the stbi_info family of functions:
+//
+// int x,y,n,ok;
+// ok = stbi_info(filename, &x, &y, &n);
+// // returns ok=1 and sets x, y, n if image is a supported format,
+// // 0 otherwise.
+//
+// Note that stb_image pervasively uses ints in its public API for sizes,
+// including sizes of memory buffers. This is now part of the API and thus
+// hard to change without causing breakage. As a result, the various image
+// loaders all have certain limits on image size; these differ somewhat
+// by format but generally boil down to either just under 2GB or just under
+// 1GB. When the decoded image would be larger than this, stb_image decoding
+// will fail.
+//
+// Additionally, stb_image will reject image files that have any of their
+// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,
+// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,
+// the only way to have an image with such dimensions load correctly
+// is for it to have a rather extreme aspect ratio. Either way, the
+// assumption here is that such larger images are likely to be malformed
+// or malicious. If you do need to load an image with individual dimensions
+// larger than that, and it still fits in the overall size limit, you can
+// #define STBI_MAX_DIMENSIONS on your own to be something larger.
+//
+// ===========================================================================
+//
+// UNICODE:
+//
+// If compiling for Windows and you wish to use Unicode filenames, compile
+// with
+// #define STBI_WINDOWS_UTF8
+// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert
+// Windows wchar_t filenames to utf8.
+//
+// ===========================================================================
+//
+// Philosophy
+//
+// stb libraries are designed with the following priorities:
+//
+// 1. easy to use
+// 2. easy to maintain
+// 3. good performance
+//
+// Sometimes I let "good performance" creep up in priority over "easy to maintain",
+// and for best performance I may provide less-easy-to-use APIs that give higher
+// performance, in addition to the easy-to-use ones. Nevertheless, it's important
+// to keep in mind that from the standpoint of you, a client of this library,
+// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all.
+//
+// Some secondary priorities arise directly from the first two, some of which
+// provide more explicit reasons why performance can't be emphasized.
+//
+// - Portable ("ease of use")
+// - Small source code footprint ("easy to maintain")
+// - No dependencies ("ease of use")
+//
+// ===========================================================================
+//
+// I/O callbacks
+//
+// I/O callbacks allow you to read from arbitrary sources, like packaged
+// files or some other source. Data read from callbacks are processed
+// through a small internal buffer (currently 128 bytes) to try to reduce
+// overhead.
+//
+// The three functions you must define are "read" (reads some bytes of data),
+// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
+//
+// ===========================================================================
+//
+// SIMD support
+//
+// The JPEG decoder will try to automatically use SIMD kernels on x86 when
+// supported by the compiler. For ARM Neon support, you must explicitly
+// request it.
+//
+// (The old do-it-yourself SIMD API is no longer supported in the current
+// code.)
+//
+// On x86, SSE2 will automatically be used when available based on a run-time
+// test; if not, the generic C versions are used as a fall-back. On ARM targets,
+// the typical path is to have separate builds for NEON and non-NEON devices
+// (at least this is true for iOS and Android). Therefore, the NEON support is
+// toggled by a build flag: define STBI_NEON to get NEON loops.
+//
+// If for some reason you do not want to use any of SIMD code, or if
+// you have issues compiling it, you can disable it entirely by
+// defining STBI_NO_SIMD.
+//
+// ===========================================================================
+//
+// HDR image support (disable by defining STBI_NO_HDR)
+//
+// stb_image supports loading HDR images in general, and currently the Radiance
+// .HDR file format specifically. You can still load any file through the existing
+// interface; if you attempt to load an HDR file, it will be automatically remapped
+// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
+// both of these constants can be reconfigured through this interface:
+//
+// stbi_hdr_to_ldr_gamma(2.2f);
+// stbi_hdr_to_ldr_scale(1.0f);
+//
+// (note, do not use _inverse_ constants; stbi_image will invert them
+// appropriately).
+//
+// Additionally, there is a new, parallel interface for loading files as
+// (linear) floats to preserve the full dynamic range:
+//
+// float *data = stbi_loadf(filename, &x, &y, &n, 0);
+//
+// If you load LDR images through this interface, those images will
+// be promoted to floating point values, run through the inverse of
+// constants corresponding to the above:
+//
+// stbi_ldr_to_hdr_scale(1.0f);
+// stbi_ldr_to_hdr_gamma(2.2f);
+//
+// Finally, given a filename (or an open file or memory block--see header
+// file for details) containing image data, you can query for the "most
+// appropriate" interface to use (that is, whether the image is HDR or
+// not), using:
+//
+// stbi_is_hdr(char *filename);
+//
+// ===========================================================================
+//
+// iPhone PNG support:
+//
+// We optionally support converting iPhone-formatted PNGs (which store
+// premultiplied BGRA) back to RGB, even though they're internally encoded
+// differently. To enable this conversion, call
+// stbi_convert_iphone_png_to_rgb(1).
+//
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
+// pixel to remove any premultiplied alpha *only* if the image file explicitly
+// says there's premultiplied data (currently only happens in iPhone images,
+// and only if iPhone convert-to-rgb processing is on).
+//
+// ===========================================================================
+//
+// ADDITIONAL CONFIGURATION
+//
+// - You can suppress implementation of any of the decoders to reduce
+// your code footprint by #defining one or more of the following
+// symbols before creating the implementation.
+//
+// STBI_NO_JPEG
+// STBI_NO_PNG
+// STBI_NO_BMP
+// STBI_NO_PSD
+// STBI_NO_TGA
+// STBI_NO_GIF
+// STBI_NO_HDR
+// STBI_NO_PIC
+// STBI_NO_PNM (.ppm and .pgm)
+//
+// - You can request *only* certain decoders and suppress all other ones
+// (this will be more forward-compatible, as addition of new decoders
+// doesn't require you to disable them explicitly):
+//
+// STBI_ONLY_JPEG
+// STBI_ONLY_PNG
+// STBI_ONLY_BMP
+// STBI_ONLY_PSD
+// STBI_ONLY_TGA
+// STBI_ONLY_GIF
+// STBI_ONLY_HDR
+// STBI_ONLY_PIC
+// STBI_ONLY_PNM (.ppm and .pgm)
+//
+// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
+// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
+//
+// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater
+// than that size (in either width or height) without further processing.
+// This is to let programs in the wild set an upper bound to prevent
+// denial-of-service attacks on untrusted data, as one could generate a
+// valid image of gigantic dimensions and force stb_image to allocate a
+// huge block of memory and spend disproportionate time decoding it. By
+// default this is set to (1 << 24), which is 16777216, but that's still
+// very big.
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif // STBI_NO_STDIO
+
+#define STBI_VERSION 1
+
+enum
+{
+ STBI_default = 0, // only used for desired_channels
+
+ STBI_grey = 1,
+ STBI_grey_alpha = 2,
+ STBI_rgb = 3,
+ STBI_rgb_alpha = 4
+};
+
+#include <stdlib.h>
+typedef unsigned char stbi_uc;
+typedef unsigned short stbi_us;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef STBIDEF
+#ifdef STB_IMAGE_STATIC
+#define STBIDEF static
+#else
+#define STBIDEF extern
+#endif
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PRIMARY API - works on images of any type
+//
+
+//
+// load image by filename, open file, or memory buffer
+//
+
+typedef struct
+{
+ int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
+ void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
+ int (*eof) (void *user); // returns nonzero if we are at end of file/data
+} stbi_io_callbacks;
+
+////////////////////////////////////
+//
+// 8-bits-per-channel interface
+//
+
+STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+// for stbi_load_from_file, file pointer is left pointing immediately after image
+#endif
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+#endif
+
+#ifdef STBI_WINDOWS_UTF8
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input);
+#endif
+
+////////////////////////////////////
+//
+// 16-bits-per-channel interface
+//
+
+STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+#ifndef STBI_NO_STDIO
+STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+#endif
+
+////////////////////////////////////
+//
+// float-per-channel interface
+//
+#ifndef STBI_NO_LINEAR
+ STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);
+
+ #ifndef STBI_NO_STDIO
+ STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);
+ STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);
+ #endif
+#endif
+
+#ifndef STBI_NO_HDR
+ STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
+ STBIDEF void stbi_hdr_to_ldr_scale(float scale);
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_LINEAR
+ STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
+ STBIDEF void stbi_ldr_to_hdr_scale(float scale);
+#endif // STBI_NO_LINEAR
+
+// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename);
+STBIDEF int stbi_is_hdr_from_file(FILE *f);
+#endif // STBI_NO_STDIO
+
+
+// get a VERY brief reason for failure
+// on most compilers (and ALL modern mainstream compilers) this is threadsafe
+STBIDEF const char *stbi_failure_reason (void);
+
+// free the loaded image -- this is just free()
+STBIDEF void stbi_image_free (void *retval_from_stbi_load);
+
+// get image dimensions & components without fully decoding
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len);
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
+STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
+STBIDEF int stbi_is_16_bit (char const *filename);
+STBIDEF int stbi_is_16_bit_from_file(FILE *f);
+#endif
+
+
+
+// for image formats that explicitly notate that they have premultiplied alpha,
+// we just return the colors as stored in the file. set this flag to force
+// unpremultiplication. results are undefined if the unpremultiply overflow.
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+
+// indicate whether we should process iphone images back to canonical format,
+// or just pass them through "as-is"
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
+
+// flip the image vertically, so the first pixel in the output array is the bottom left
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
+
+// as above, but only applies to images loaded on the thread that calls the function
+// this function is only available if your compiler supports thread-local variables;
+// calling it will fail to link if your compiler doesn't
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply);
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert);
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip);
+
+// ZLIB client - used by PNG, available for other purposes
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
+STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+//
+//
+//// end header file /////////////////////////////////////////////////////
+#endif // STBI_INCLUDE_STB_IMAGE_H
+
+#ifdef STB_IMAGE_IMPLEMENTATION
+
+#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
+ || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
+ || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
+ || defined(STBI_ONLY_ZLIB)
+ #ifndef STBI_ONLY_JPEG
+ #define STBI_NO_JPEG
+ #endif
+ #ifndef STBI_ONLY_PNG
+ #define STBI_NO_PNG
+ #endif
+ #ifndef STBI_ONLY_BMP
+ #define STBI_NO_BMP
+ #endif
+ #ifndef STBI_ONLY_PSD
+ #define STBI_NO_PSD
+ #endif
+ #ifndef STBI_ONLY_TGA
+ #define STBI_NO_TGA
+ #endif
+ #ifndef STBI_ONLY_GIF
+ #define STBI_NO_GIF
+ #endif
+ #ifndef STBI_ONLY_HDR
+ #define STBI_NO_HDR
+ #endif
+ #ifndef STBI_ONLY_PIC
+ #define STBI_NO_PIC
+ #endif
+ #ifndef STBI_ONLY_PNM
+ #define STBI_NO_PNM
+ #endif
+#endif
+
+#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
+#define STBI_NO_ZLIB
+#endif
+
+
+#include <stdarg.h>
+#include <stddef.h> // ptrdiff_t on osx
+#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
+#include <math.h> // ldexp, pow
+#endif
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif
+
+#ifndef STBI_ASSERT
+#include <assert.h>
+#define STBI_ASSERT(x) assert(x)
+#endif
+
+#ifdef __cplusplus
+#define STBI_EXTERN extern "C"
+#else
+#define STBI_EXTERN extern
+#endif
+
+
+#ifndef _MSC_VER
+ #ifdef __cplusplus
+ #define stbi_inline inline
+ #else
+ #define stbi_inline
+ #endif
+#else
+ #define stbi_inline __forceinline
+#endif
+
+#ifndef STBI_NO_THREAD_LOCALS
+ #if defined(__cplusplus) && __cplusplus >= 201103L
+ #define STBI_THREAD_LOCAL thread_local
+ #elif defined(__GNUC__) && __GNUC__ < 5
+ #define STBI_THREAD_LOCAL __thread
+ #elif defined(_MSC_VER)
+ #define STBI_THREAD_LOCAL __declspec(thread)
+ #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)
+ #define STBI_THREAD_LOCAL _Thread_local
+ #endif
+
+ #ifndef STBI_THREAD_LOCAL
+ #if defined(__GNUC__)
+ #define STBI_THREAD_LOCAL __thread
+ #endif
+ #endif
+#endif
+
+#if defined(_MSC_VER) || defined(__SYMBIAN32__)
+typedef unsigned short stbi__uint16;
+typedef signed short stbi__int16;
+typedef unsigned int stbi__uint32;
+typedef signed int stbi__int32;
+#else
+#include <stdint.h>
+typedef uint16_t stbi__uint16;
+typedef int16_t stbi__int16;
+typedef uint32_t stbi__uint32;
+typedef int32_t stbi__int32;
+#endif
+
+// should produce compiler error if size is wrong
+typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
+
+#ifdef _MSC_VER
+#define STBI_NOTUSED(v) (void)(v)
+#else
+#define STBI_NOTUSED(v) (void)sizeof(v)
+#endif
+
+#ifdef _MSC_VER
+#define STBI_HAS_LROTL
+#endif
+
+#ifdef STBI_HAS_LROTL
+ #define stbi_lrot(x,y) _lrotl(x,y)
+#else
+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31)))
+#endif
+
+#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))
+// ok
+#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED)
+// ok
+#else
+#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)."
+#endif
+
+#ifndef STBI_MALLOC
+#define STBI_MALLOC(sz) malloc(sz)
+#define STBI_REALLOC(p,newsz) realloc(p,newsz)
+#define STBI_FREE(p) free(p)
+#endif
+
+#ifndef STBI_REALLOC_SIZED
+#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz)
+#endif
+
+// x86/x64 detection
+#if defined(__x86_64__) || defined(_M_X64)
+#define STBI__X64_TARGET
+#elif defined(__i386) || defined(_M_IX86)
+#define STBI__X86_TARGET
+#endif
+
+#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
+// gcc doesn't support sse2 intrinsics unless you compile with -msse2,
+// which in turn means it gets to use SSE2 everywhere. This is unfortunate,
+// but previous attempts to provide the SSE2 functions with runtime
+// detection caused numerous issues. The way architecture extensions are
+// exposed in GCC/Clang is, sadly, not really suited for one-file libs.
+// New behavior: if compiled with -msse2, we use SSE2 without any
+// detection; if not, we don't use it at all.
+#define STBI_NO_SIMD
+#endif
+
+#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
+// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
+//
+// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
+// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
+// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
+// simultaneously enabling "-mstackrealign".
+//
+// See https://github.com/nothings/stb/issues/81 for more information.
+//
+// So default to no SSE2 on 32-bit MinGW. If you've read this far and added
+// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
+#define STBI_NO_SIMD
+#endif
+
+#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET))
+#define STBI_SSE2
+#include <emmintrin.h>
+
+#ifdef _MSC_VER
+
+#if _MSC_VER >= 1400 // not VC6
+#include <intrin.h> // __cpuid
+static int stbi__cpuid3(void)
+{
+ int info[4];
+ __cpuid(info,1);
+ return info[3];
+}
+#else
+static int stbi__cpuid3(void)
+{
+ int res;
+ __asm {
+ mov eax,1
+ cpuid
+ mov res,edx
+ }
+ return res;
+}
+#endif
+
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ int info3 = stbi__cpuid3();
+ return ((info3 >> 26) & 1) != 0;
+}
+#endif
+
+#else // assume GCC-style if not VC++
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+
+#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2)
+static int stbi__sse2_available(void)
+{
+ // If we're even attempting to compile this on GCC/Clang, that means
+ // -msse2 is on, which means the compiler is allowed to use SSE2
+ // instructions at will, and so are we.
+ return 1;
+}
+#endif
+
+#endif
+#endif
+
+// ARM NEON
+#if defined(STBI_NO_SIMD) && defined(STBI_NEON)
+#undef STBI_NEON
+#endif
+
+#ifdef STBI_NEON
+#include <arm_neon.h>
+#ifdef _MSC_VER
+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
+#else
+#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
+#endif
+#endif
+
+#ifndef STBI_SIMD_ALIGN
+#define STBI_SIMD_ALIGN(type, name) type name
+#endif
+
+#ifndef STBI_MAX_DIMENSIONS
+#define STBI_MAX_DIMENSIONS (1 << 24)
+#endif
+
+///////////////////////////////////////////////
+//
+// stbi__context struct and start_xxx functions
+
+// stbi__context structure is our basic context used by all images, so it
+// contains all the IO context, plus some basic image information
+typedef struct
+{
+ stbi__uint32 img_x, img_y;
+ int img_n, img_out_n;
+
+ stbi_io_callbacks io;
+ void *io_user_data;
+
+ int read_from_callbacks;
+ int buflen;
+ stbi_uc buffer_start[128];
+ int callback_already_read;
+
+ stbi_uc *img_buffer, *img_buffer_end;
+ stbi_uc *img_buffer_original, *img_buffer_original_end;
+} stbi__context;
+
+
+static void stbi__refill_buffer(stbi__context *s);
+
+// initialize a memory-decode context
+static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
+{
+ s->io.read = NULL;
+ s->read_from_callbacks = 0;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
+ s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len;
+}
+
+// initialize a callback-based context
+static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
+{
+ s->io = *c;
+ s->io_user_data = user;
+ s->buflen = sizeof(s->buffer_start);
+ s->read_from_callbacks = 1;
+ s->callback_already_read = 0;
+ s->img_buffer = s->img_buffer_original = s->buffer_start;
+ stbi__refill_buffer(s);
+ s->img_buffer_original_end = s->img_buffer_end;
+}
+
+#ifndef STBI_NO_STDIO
+
+static int stbi__stdio_read(void *user, char *data, int size)
+{
+ return (int) fread(data,1,size,(FILE*) user);
+}
+
+static void stbi__stdio_skip(void *user, int n)
+{
+ int ch;
+ fseek((FILE*) user, n, SEEK_CUR);
+ ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */
+ if (ch != EOF) {
+ ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */
+ }
+}
+
+static int stbi__stdio_eof(void *user)
+{
+ return feof((FILE*) user) || ferror((FILE *) user);
+}
+
+static stbi_io_callbacks stbi__stdio_callbacks =
+{
+ stbi__stdio_read,
+ stbi__stdio_skip,
+ stbi__stdio_eof,
+};
+
+static void stbi__start_file(stbi__context *s, FILE *f)
+{
+ stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
+}
+
+//static void stop_file(stbi__context *s) { }
+
+#endif // !STBI_NO_STDIO
+
+static void stbi__rewind(stbi__context *s)
+{
+ // conceptually rewind SHOULD rewind to the beginning of the stream,
+ // but we just rewind to the beginning of the initial buffer, because
+ // we only use it after doing 'test', which only ever looks at at most 92 bytes
+ s->img_buffer = s->img_buffer_original;
+ s->img_buffer_end = s->img_buffer_original_end;
+}
+
+enum
+{
+ STBI_ORDER_RGB,
+ STBI_ORDER_BGR
+};
+
+typedef struct
+{
+ int bits_per_channel;
+ int num_channels;
+ int channel_order;
+} stbi__result_info;
+
+#ifndef STBI_NO_JPEG
+static int stbi__jpeg_test(stbi__context *s);
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNG
+static int stbi__png_test(stbi__context *s);
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__png_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test(stbi__context *s);
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_TGA
+static int stbi__tga_test(stbi__context *s);
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s);
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc);
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__psd_is16(stbi__context *s);
+#endif
+
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test(stbi__context *s);
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_test(stbi__context *s);
+static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_GIF
+static int stbi__gif_test(stbi__context *s);
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp);
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
+#endif
+
+#ifndef STBI_NO_PNM
+static int stbi__pnm_test(stbi__context *s);
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
+static int stbi__pnm_is16(stbi__context *s);
+#endif
+
+static
+#ifdef STBI_THREAD_LOCAL
+STBI_THREAD_LOCAL
+#endif
+const char *stbi__g_failure_reason;
+
+STBIDEF const char *stbi_failure_reason(void)
+{
+ return stbi__g_failure_reason;
+}
+
+#ifndef STBI_NO_FAILURE_STRINGS
+static int stbi__err(const char *str)
+{
+ stbi__g_failure_reason = str;
+ return 0;
+}
+#endif
+
+static void *stbi__malloc(size_t size)
+{
+ return STBI_MALLOC(size);
+}
+
+// stb_image uses ints pervasively, including for offset calculations.
+// therefore the largest decoded image size we can support with the
+// current code, even on 64-bit targets, is INT_MAX. this is not a
+// significant limitation for the intended use case.
+//
+// we do, however, need to make sure our size calculations don't
+// overflow. hence a few helper functions for size calculations that
+// multiply integers together, making sure that they're non-negative
+// and no overflow occurs.
+
+// return 1 if the sum is valid, 0 on overflow.
+// negative terms are considered invalid.
+static int stbi__addsizes_valid(int a, int b)
+{
+ if (b < 0) return 0;
+ // now 0 <= b <= INT_MAX, hence also
+ // 0 <= INT_MAX - b <= INTMAX.
+ // And "a + b <= INT_MAX" (which might overflow) is the
+ // same as a <= INT_MAX - b (no overflow)
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product is valid, 0 on overflow.
+// negative factors are considered invalid.
+static int stbi__mul2sizes_valid(int a, int b)
+{
+ if (a < 0 || b < 0) return 0;
+ if (b == 0) return 1; // mul-by-0 is always safe
+ // portable way to check for no overflows in a*b
+ return a <= INT_MAX/b;
+}
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad2sizes_valid(int a, int b, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);
+}
+#endif
+
+// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow
+static int stbi__mad3sizes_valid(int a, int b, int c, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__addsizes_valid(a*b*c, add);
+}
+
+// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)
+{
+ return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&
+ stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);
+}
+#endif
+
+#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR)
+// mallocs with size overflow checking
+static void *stbi__malloc_mad2(int a, int b, int add)
+{
+ if (!stbi__mad2sizes_valid(a, b, add)) return NULL;
+ return stbi__malloc(a*b + add);
+}
+#endif
+
+static void *stbi__malloc_mad3(int a, int b, int c, int add)
+{
+ if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;
+ return stbi__malloc(a*b*c + add);
+}
+
+#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM)
+static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)
+{
+ if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;
+ return stbi__malloc(a*b*c*d + add);
+}
+#endif
+
+// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow.
+static int stbi__addints_valid(int a, int b)
+{
+ if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow
+ if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0.
+ return a <= INT_MAX - b;
+}
+
+// returns 1 if the product of two ints fits in a signed short, 0 on overflow.
+static int stbi__mul2shorts_valid(int a, int b)
+{
+ if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow
+ if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid
+ if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN
+ return a >= SHRT_MIN / b;
+}
+
+// stbi__err - error
+// stbi__errpf - error returning pointer to float
+// stbi__errpuc - error returning pointer to unsigned char
+
+#ifdef STBI_NO_FAILURE_STRINGS
+ #define stbi__err(x,y) 0
+#elif defined(STBI_FAILURE_USERMSG)
+ #define stbi__err(x,y) stbi__err(y)
+#else
+ #define stbi__err(x,y) stbi__err(x)
+#endif
+
+#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL))
+#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL))
+
+STBIDEF void stbi_image_free(void *retval_from_stbi_load)
+{
+ STBI_FREE(retval_from_stbi_load);
+}
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
+#endif
+
+#ifndef STBI_NO_HDR
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
+#endif
+
+static int stbi__vertically_flip_on_load_global = 0;
+
+STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_global = flag_true_if_should_flip;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global
+#else
+static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set;
+
+STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip)
+{
+ stbi__vertically_flip_on_load_local = flag_true_if_should_flip;
+ stbi__vertically_flip_on_load_set = 1;
+}
+
+#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \
+ ? stbi__vertically_flip_on_load_local \
+ : stbi__vertically_flip_on_load_global)
+#endif // STBI_THREAD_LOCAL
+
+static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields
+ ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed
+ ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order
+ ri->num_channels = 0;
+
+ // test the formats with a very explicit header first (at least a FOURCC
+ // or distinctive magic number first)
+ #ifndef STBI_NO_PNG
+ if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc);
+ #else
+ STBI_NOTUSED(bpc);
+ #endif
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ // then the formats that can end up attempting to load with just 1 or 2
+ // bytes matching expectations; these are prone to false positives, so
+ // try them later
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);
+ #endif
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri);
+ return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
+ }
+ #endif
+
+ #ifndef STBI_NO_TGA
+ // test tga last because it's a crappy test!
+ if (stbi__tga_test(s))
+ return stbi__tga_load(s,x,y,comp,req_comp, ri);
+ #endif
+
+ return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi_uc *reduced;
+
+ reduced = (stbi_uc *) stbi__malloc(img_len);
+ if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling
+
+ STBI_FREE(orig);
+ return reduced;
+}
+
+static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)
+{
+ int i;
+ int img_len = w * h * channels;
+ stbi__uint16 *enlarged;
+
+ enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);
+ if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+
+ for (i = 0; i < img_len; ++i)
+ enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff
+
+ STBI_FREE(orig);
+ return enlarged;
+}
+
+static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel)
+{
+ int row;
+ size_t bytes_per_row = (size_t)w * bytes_per_pixel;
+ stbi_uc temp[2048];
+ stbi_uc *bytes = (stbi_uc *)image;
+
+ for (row = 0; row < (h>>1); row++) {
+ stbi_uc *row0 = bytes + row*bytes_per_row;
+ stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row;
+ // swap row0 with row1
+ size_t bytes_left = bytes_per_row;
+ while (bytes_left) {
+ size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp);
+ memcpy(temp, row0, bytes_copy);
+ memcpy(row0, row1, bytes_copy);
+ memcpy(row1, temp, bytes_copy);
+ row0 += bytes_copy;
+ row1 += bytes_copy;
+ bytes_left -= bytes_copy;
+ }
+ }
+}
+
+#ifndef STBI_NO_GIF
+static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel)
+{
+ int slice;
+ int slice_size = w * h * bytes_per_pixel;
+
+ stbi_uc *bytes = (stbi_uc *)image;
+ for (slice = 0; slice < z; ++slice) {
+ stbi__vertical_flip(bytes, w, h, bytes_per_pixel);
+ bytes += slice_size;
+ }
+}
+#endif
+
+static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 8) {
+ result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 8;
+ }
+
+ // @TODO: move stbi__convert_format to here
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc));
+ }
+
+ return (unsigned char *) result;
+}
+
+static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__result_info ri;
+ void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);
+
+ if (result == NULL)
+ return NULL;
+
+ // it is the responsibility of the loaders to make sure we get either 8 or 16 bit.
+ STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16);
+
+ if (ri.bits_per_channel != 16) {
+ result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);
+ ri.bits_per_channel = 16;
+ }
+
+ // @TODO: move stbi__convert_format16 to here
+ // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision
+
+ if (stbi__vertically_flip_on_load) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16));
+ }
+
+ return (stbi__uint16 *) result;
+}
+
+#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR)
+static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
+{
+ if (stbi__vertically_flip_on_load && result != NULL) {
+ int channels = req_comp ? req_comp : *comp;
+ stbi__vertical_flip(result, *x, *y, channels * sizeof(float));
+ }
+}
+#endif
+
+#ifndef STBI_NO_STDIO
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);
+STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);
+#endif
+
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)
+{
+ return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);
+}
+#endif
+
+static FILE *stbi__fopen(char const *filename, char const *mode)
+{
+ FILE *f;
+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)
+ wchar_t wMode[64];
+ wchar_t wFilename[1024];
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))
+ return 0;
+
+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))
+ return 0;
+
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != _wfopen_s(&f, wFilename, wMode))
+ f = 0;
+#else
+ f = _wfopen(wFilename, wMode);
+#endif
+
+#elif defined(_MSC_VER) && _MSC_VER >= 1400
+ if (0 != fopen_s(&f, filename, mode))
+ f=0;
+#else
+ f = fopen(filename, mode);
+#endif
+ return f;
+}
+
+
+STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ unsigned char *result;
+ if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__uint16 *result;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp);
+ if (result) {
+ // need to 'unget' all the characters in the IO buffer
+ fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
+ }
+ return result;
+}
+
+STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ stbi__uint16 *result;
+ if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");
+ result = stbi_load_from_file_16(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+
+#endif //!STBI_NO_STDIO
+
+STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user);
+ return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels);
+}
+
+STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_GIF
+STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ unsigned char *result;
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+
+ result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp);
+ if (stbi__vertically_flip_on_load) {
+ stbi__vertical_flip_slices( result, *x, *y, *z, *comp );
+ }
+
+ return result;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
+{
+ unsigned char *data;
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_test(s)) {
+ stbi__result_info ri;
+ float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri);
+ if (hdr_data)
+ stbi__float_postprocess(hdr_data,x,y,comp,req_comp);
+ return hdr_data;
+ }
+ #endif
+ data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);
+ if (data)
+ return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+ return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
+}
+
+STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+ float *result;
+ FILE *f = stbi__fopen(filename, "rb");
+ if (!f) return stbi__errpf("can't fopen", "Unable to open file");
+ result = stbi_loadf_from_file(f,x,y,comp,req_comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+ stbi__context s;
+ stbi__start_file(&s,f);
+ return stbi__loadf_main(&s,x,y,comp,req_comp);
+}
+#endif // !STBI_NO_STDIO
+
+#endif // !STBI_NO_LINEAR
+
+// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
+// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
+// reports false!
+
+STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(buffer);
+ STBI_NOTUSED(len);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_is_hdr (char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result=0;
+ if (f) {
+ result = stbi_is_hdr_from_file(f);
+ fclose(f);
+ }
+ return result;
+}
+
+STBIDEF int stbi_is_hdr_from_file(FILE *f)
+{
+ #ifndef STBI_NO_HDR
+ long pos = ftell(f);
+ int res;
+ stbi__context s;
+ stbi__start_file(&s,f);
+ res = stbi__hdr_test(&s);
+ fseek(f, pos, SEEK_SET);
+ return res;
+ #else
+ STBI_NOTUSED(f);
+ return 0;
+ #endif
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
+{
+ #ifndef STBI_NO_HDR
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+ return stbi__hdr_test(&s);
+ #else
+ STBI_NOTUSED(clbk);
+ STBI_NOTUSED(user);
+ return 0;
+ #endif
+}
+
+#ifndef STBI_NO_LINEAR
+static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
+
+STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
+STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
+#endif
+
+static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
+
+STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
+STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Common code used by all image loaders
+//
+
+enum
+{
+ STBI__SCAN_load=0,
+ STBI__SCAN_type,
+ STBI__SCAN_header
+};
+
+static void stbi__refill_buffer(stbi__context *s)
+{
+ int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
+ s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original);
+ if (n == 0) {
+ // at end of file, treat same as if from memory, but need to handle case
+ // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
+ s->read_from_callbacks = 0;
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start+1;
+ *s->img_buffer = 0;
+ } else {
+ s->img_buffer = s->buffer_start;
+ s->img_buffer_end = s->buffer_start + n;
+ }
+}
+
+stbi_inline static stbi_uc stbi__get8(stbi__context *s)
+{
+ if (s->img_buffer < s->img_buffer_end)
+ return *s->img_buffer++;
+ if (s->read_from_callbacks) {
+ stbi__refill_buffer(s);
+ return *s->img_buffer++;
+ }
+ return 0;
+}
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+stbi_inline static int stbi__at_eof(stbi__context *s)
+{
+ if (s->io.read) {
+ if (!(s->io.eof)(s->io_user_data)) return 0;
+ // if feof() is true, check if buffer = end
+ // special case: we've only got the special 0 character at the end
+ if (s->read_from_callbacks == 0) return 1;
+ }
+
+ return s->img_buffer >= s->img_buffer_end;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC)
+// nothing
+#else
+static void stbi__skip(stbi__context *s, int n)
+{
+ if (n == 0) return; // already there!
+ if (n < 0) {
+ s->img_buffer = s->img_buffer_end;
+ return;
+ }
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ s->img_buffer = s->img_buffer_end;
+ (s->io.skip)(s->io_user_data, n - blen);
+ return;
+ }
+ }
+ s->img_buffer += n;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM)
+// nothing
+#else
+static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
+{
+ if (s->io.read) {
+ int blen = (int) (s->img_buffer_end - s->img_buffer);
+ if (blen < n) {
+ int res, count;
+
+ memcpy(buffer, s->img_buffer, blen);
+
+ count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
+ res = (count == (n-blen));
+ s->img_buffer = s->img_buffer_end;
+ return res;
+ }
+ }
+
+ if (s->img_buffer+n <= s->img_buffer_end) {
+ memcpy(buffer, s->img_buffer, n);
+ s->img_buffer += n;
+ return 1;
+ } else
+ return 0;
+}
+#endif
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static int stbi__get16be(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return (z << 8) + stbi__get8(s);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC)
+// nothing
+#else
+static stbi__uint32 stbi__get32be(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16be(s);
+ return (z << 16) + stbi__get16be(s);
+}
+#endif
+
+#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF)
+// nothing
+#else
+static int stbi__get16le(stbi__context *s)
+{
+ int z = stbi__get8(s);
+ return z + (stbi__get8(s) << 8);
+}
+#endif
+
+#ifndef STBI_NO_BMP
+static stbi__uint32 stbi__get32le(stbi__context *s)
+{
+ stbi__uint32 z = stbi__get16le(s);
+ z += (stbi__uint32)stbi__get16le(s) << 16;
+ return z;
+}
+#endif
+
+#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
+
+#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+//////////////////////////////////////////////////////////////////////////////
+//
+// generic converter from built-in img_n to req_comp
+// individual types do this automatically as much as possible (e.g. jpeg
+// does all cases internally since it needs to colorspace convert anyway,
+// and it never has alpha, so very few cases ). png can automatically
+// interleave an alpha=255 channel, but falls back to this for other cases
+//
+// assume data buffer is malloced, so malloc a new one and free that one
+// only failure mode is malloc failing
+
+static stbi_uc stbi__compute_y(int r, int g, int b)
+{
+ return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)
+// nothing
+#else
+static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ unsigned char *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ unsigned char *src = data + j * x * img_n ;
+ unsigned char *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 stbi__compute_y_16(int r, int g, int b)
+{
+ return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8);
+}
+#endif
+
+#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD)
+// nothing
+#else
+static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)
+{
+ int i,j;
+ stbi__uint16 *good;
+
+ if (req_comp == img_n) return data;
+ STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
+
+ good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);
+ if (good == NULL) {
+ STBI_FREE(data);
+ return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");
+ }
+
+ for (j=0; j < (int) y; ++j) {
+ stbi__uint16 *src = data + j * x * img_n ;
+ stbi__uint16 *dest = good + j * x * req_comp;
+
+ #define STBI__COMBO(a,b) ((a)*8+(b))
+ #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+ // convert source image with img_n components to one with req_comp components;
+ // avoid switch per pixel, so use switch per scanline and massive macros
+ switch (STBI__COMBO(img_n, req_comp)) {
+ STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break;
+ STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break;
+ STBI__CASE(2,1) { dest[0]=src[0]; } break;
+ STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;
+ STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break;
+ STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break;
+ STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break;
+ STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;
+ STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break;
+ STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break;
+ default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion");
+ }
+ #undef STBI__CASE
+ }
+
+ STBI_FREE(data);
+ return good;
+}
+#endif
+
+#ifndef STBI_NO_LINEAR
+static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
+{
+ int i,k,n;
+ float *output;
+ if (!data) return NULL;
+ output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
+ }
+ }
+ if (n < comp) {
+ for (i=0; i < x*y; ++i) {
+ output[i*comp + n] = data[i*comp + n]/255.0f;
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+#ifndef STBI_NO_HDR
+#define stbi__float2int(x) ((int) (x))
+static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
+{
+ int i,k,n;
+ stbi_uc *output;
+ if (!data) return NULL;
+ output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0);
+ if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }
+ // compute number of non-alpha components
+ if (comp & 1) n = comp; else n = comp-1;
+ for (i=0; i < x*y; ++i) {
+ for (k=0; k < n; ++k) {
+ float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ if (k < comp) {
+ float z = data[i*comp+k] * 255 + 0.5f;
+ if (z < 0) z = 0;
+ if (z > 255) z = 255;
+ output[i*comp + k] = (stbi_uc) stbi__float2int(z);
+ }
+ }
+ STBI_FREE(data);
+ return output;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// "baseline" JPEG/JFIF decoder
+//
+// simple implementation
+// - doesn't support delayed output of y-dimension
+// - simple interface (only one output format: 8-bit interleaved RGB)
+// - doesn't try to recover corrupt jpegs
+// - doesn't allow partial loading, loading multiple at once
+// - still fast on x86 (copying globals into locals doesn't help x86)
+// - allocates lots of intermediate memory (full size of all components)
+// - non-interleaved case requires this anyway
+// - allows good upsampling (see next)
+// high-quality
+// - upsampled channels are bilinearly interpolated, even across blocks
+// - quality integer IDCT derived from IJG's 'slow'
+// performance
+// - fast huffman; reasonable integer IDCT
+// - some SIMD kernels for common paths on targets with SSE2/NEON
+// - uses a lot of intermediate memory, could cache poorly
+
+#ifndef STBI_NO_JPEG
+
+// huffman decoding acceleration
+#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
+
+typedef struct
+{
+ stbi_uc fast[1 << FAST_BITS];
+ // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
+ stbi__uint16 code[256];
+ stbi_uc values[256];
+ stbi_uc size[257];
+ unsigned int maxcode[18];
+ int delta[17]; // old 'firstsymbol' - old 'firstcode'
+} stbi__huffman;
+
+typedef struct
+{
+ stbi__context *s;
+ stbi__huffman huff_dc[4];
+ stbi__huffman huff_ac[4];
+ stbi__uint16 dequant[4][64];
+ stbi__int16 fast_ac[4][1 << FAST_BITS];
+
+// sizes for components, interleaved MCUs
+ int img_h_max, img_v_max;
+ int img_mcu_x, img_mcu_y;
+ int img_mcu_w, img_mcu_h;
+
+// definition of jpeg image component
+ struct
+ {
+ int id;
+ int h,v;
+ int tq;
+ int hd,ha;
+ int dc_pred;
+
+ int x,y,w2,h2;
+ stbi_uc *data;
+ void *raw_data, *raw_coeff;
+ stbi_uc *linebuf;
+ short *coeff; // progressive only
+ int coeff_w, coeff_h; // number of 8x8 coefficient blocks
+ } img_comp[4];
+
+ stbi__uint32 code_buffer; // jpeg entropy-coded buffer
+ int code_bits; // number of valid bits
+ unsigned char marker; // marker seen while filling entropy buffer
+ int nomore; // flag if we saw a marker so must stop
+
+ int progressive;
+ int spec_start;
+ int spec_end;
+ int succ_high;
+ int succ_low;
+ int eob_run;
+ int jfif;
+ int app14_color_transform; // Adobe APP14 tag
+ int rgb;
+
+ int scan_n, order[4];
+ int restart_interval, todo;
+
+// kernels
+ void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);
+ void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);
+ stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);
+} stbi__jpeg;
+
+static int stbi__build_huffman(stbi__huffman *h, int *count)
+{
+ int i,j,k=0;
+ unsigned int code;
+ // build size list for each symbol (from JPEG spec)
+ for (i=0; i < 16; ++i) {
+ for (j=0; j < count[i]; ++j) {
+ h->size[k++] = (stbi_uc) (i+1);
+ if(k >= 257) return stbi__err("bad size list","Corrupt JPEG");
+ }
+ }
+ h->size[k] = 0;
+
+ // compute actual symbols (from jpeg spec)
+ code = 0;
+ k = 0;
+ for(j=1; j <= 16; ++j) {
+ // compute delta to add to code to compute symbol id
+ h->delta[j] = k - code;
+ if (h->size[k] == j) {
+ while (h->size[k] == j)
+ h->code[k++] = (stbi__uint16) (code++);
+ if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG");
+ }
+ // compute largest code + 1 for this size, preshifted as needed later
+ h->maxcode[j] = code << (16-j);
+ code <<= 1;
+ }
+ h->maxcode[j] = 0xffffffff;
+
+ // build non-spec acceleration table; 255 is flag for not-accelerated
+ memset(h->fast, 255, 1 << FAST_BITS);
+ for (i=0; i < k; ++i) {
+ int s = h->size[i];
+ if (s <= FAST_BITS) {
+ int c = h->code[i] << (FAST_BITS-s);
+ int m = 1 << (FAST_BITS-s);
+ for (j=0; j < m; ++j) {
+ h->fast[c+j] = (stbi_uc) i;
+ }
+ }
+ }
+ return 1;
+}
+
+// build a table that decodes both magnitude and value of small ACs in
+// one go.
+static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
+{
+ int i;
+ for (i=0; i < (1 << FAST_BITS); ++i) {
+ stbi_uc fast = h->fast[i];
+ fast_ac[i] = 0;
+ if (fast < 255) {
+ int rs = h->values[fast];
+ int run = (rs >> 4) & 15;
+ int magbits = rs & 15;
+ int len = h->size[fast];
+
+ if (magbits && len + magbits <= FAST_BITS) {
+ // magnitude code followed by receive_extend code
+ int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
+ int m = 1 << (magbits - 1);
+ if (k < m) k += (~0U << magbits) + 1;
+ // if the result is small enough, we can fit it in fast_ac table
+ if (k >= -128 && k <= 127)
+ fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits));
+ }
+ }
+ }
+}
+
+static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
+{
+ do {
+ unsigned int b = j->nomore ? 0 : stbi__get8(j->s);
+ if (b == 0xff) {
+ int c = stbi__get8(j->s);
+ while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes
+ if (c != 0) {
+ j->marker = (unsigned char) c;
+ j->nomore = 1;
+ return;
+ }
+ }
+ j->code_buffer |= b << (24 - j->code_bits);
+ j->code_bits += 8;
+ } while (j->code_bits <= 24);
+}
+
+// (1 << n) - 1
+static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
+
+// decode a jpeg huffman value from the bitstream
+stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
+{
+ unsigned int temp;
+ int c,k;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ // look at the top FAST_BITS and determine what symbol ID it is,
+ // if the code is <= FAST_BITS
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ k = h->fast[c];
+ if (k < 255) {
+ int s = h->size[k];
+ if (s > j->code_bits)
+ return -1;
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ return h->values[k];
+ }
+
+ // naive test is to shift the code_buffer down so k bits are
+ // valid, then test against maxcode. To speed this up, we've
+ // preshifted maxcode left so that it has (16-k) 0s at the
+ // end; in other words, regardless of the number of bits, it
+ // wants to be compared against something shifted to have 16;
+ // that way we don't need to shift inside the loop.
+ temp = j->code_buffer >> 16;
+ for (k=FAST_BITS+1 ; ; ++k)
+ if (temp < h->maxcode[k])
+ break;
+ if (k == 17) {
+ // error! code not found
+ j->code_bits -= 16;
+ return -1;
+ }
+
+ if (k > j->code_bits)
+ return -1;
+
+ // convert the huffman code to the symbol id
+ c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
+ if(c < 0 || c >= 256) // symbol id out of bounds!
+ return -1;
+ STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
+
+ // convert the id to a symbol
+ j->code_bits -= k;
+ j->code_buffer <<= k;
+ return h->values[c];
+}
+
+// bias[n] = (-1<<n) + 1
+static const int stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};
+
+// combined JPEG 'receive' and JPEG 'extend', since baseline
+// always extends everything it receives.
+stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ int sgn;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+
+ sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k + (stbi__jbias[n] & (sgn - 1));
+}
+
+// get some unsigned bits
+stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
+{
+ unsigned int k;
+ if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = stbi_lrot(j->code_buffer, n);
+ j->code_buffer = k & ~stbi__bmask[n];
+ k &= stbi__bmask[n];
+ j->code_bits -= n;
+ return k;
+}
+
+stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
+{
+ unsigned int k;
+ if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
+ if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing
+ k = j->code_buffer;
+ j->code_buffer <<= 1;
+ --j->code_bits;
+ return k & 0x80000000;
+}
+
+// given a value that's at position X in the zigzag stream,
+// where does it appear in the 8x8 matrix coded as row-major?
+static const stbi_uc stbi__jpeg_dezigzag[64+15] =
+{
+ 0, 1, 8, 16, 9, 2, 3, 10,
+ 17, 24, 32, 25, 18, 11, 4, 5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63,
+ // let corrupt input sample past end
+ 63, 63, 63, 63, 63, 63, 63, 63,
+ 63, 63, 63, 63, 63, 63, 63
+};
+
+// decode one 64-entry block--
+static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant)
+{
+ int diff,dc,k;
+ int t;
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG");
+
+ // 0 all the ac values now so we can do it 32-bits at a time
+ memset(data,0,64*sizeof(data[0]));
+
+ diff = t ? stbi__extend_receive(j, t) : 0;
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * dequant[0]);
+
+ // decode AC components, see JPEG spec
+ k = 1;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * dequant[zig]);
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (rs != 0xf0) break; // end block
+ k += 16;
+ } else {
+ k += r;
+ // decode into unzigzag'd location
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);
+ }
+ }
+ } while (k < 64);
+ return 1;
+}
+
+static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)
+{
+ int diff,dc;
+ int t;
+ if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+
+ if (j->succ_high == 0) {
+ // first scan for DC coefficient, must be first
+ memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
+ t = stbi__jpeg_huff_decode(j, hdc);
+ if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ diff = t ? stbi__extend_receive(j, t) : 0;
+
+ if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG");
+ dc = j->img_comp[b].dc_pred + diff;
+ j->img_comp[b].dc_pred = dc;
+ if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+ data[0] = (short) (dc * (1 << j->succ_low));
+ } else {
+ // refinement scan for DC coefficient
+ if (stbi__jpeg_get_bit(j))
+ data[0] += (short) (1 << j->succ_low);
+ }
+ return 1;
+}
+
+// @OPTIMIZE: store non-zigzagged during the decode passes,
+// and only de-zigzag when dequantizing
+static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)
+{
+ int k;
+ if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
+
+ if (j->succ_high == 0) {
+ int shift = j->succ_low;
+
+ if (j->eob_run) {
+ --j->eob_run;
+ return 1;
+ }
+
+ k = j->spec_start;
+ do {
+ unsigned int zig;
+ int c,r,s;
+ if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
+ c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+ r = fac[c];
+ if (r) { // fast-AC path
+ k += (r >> 4) & 15; // run
+ s = r & 15; // combined length
+ if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available");
+ j->code_buffer <<= s;
+ j->code_bits -= s;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) ((r >> 8) * (1 << shift));
+ } else {
+ int rs = stbi__jpeg_huff_decode(j, hac);
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r);
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ --j->eob_run;
+ break;
+ }
+ k += 16;
+ } else {
+ k += r;
+ zig = stbi__jpeg_dezigzag[k++];
+ data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));
+ }
+ }
+ } while (k <= j->spec_end);
+ } else {
+ // refinement scan for these AC coefficients
+
+ short bit = (short) (1 << j->succ_low);
+
+ if (j->eob_run) {
+ --j->eob_run;
+ for (k = j->spec_start; k <= j->spec_end; ++k) {
+ short *p = &data[stbi__jpeg_dezigzag[k]];
+ if (*p != 0)
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ }
+ } else {
+ k = j->spec_start;
+ do {
+ int r,s;
+ int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
+ if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
+ s = rs & 15;
+ r = rs >> 4;
+ if (s == 0) {
+ if (r < 15) {
+ j->eob_run = (1 << r) - 1;
+ if (r)
+ j->eob_run += stbi__jpeg_get_bits(j, r);
+ r = 64; // force end of block
+ } else {
+ // r=15 s=0 should write 16 0s, so we just do
+ // a run of 15 0s and then write s (which is 0),
+ // so we don't have to do anything special here
+ }
+ } else {
+ if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
+ // sign bit
+ if (stbi__jpeg_get_bit(j))
+ s = bit;
+ else
+ s = -bit;
+ }
+
+ // advance by r
+ while (k <= j->spec_end) {
+ short *p = &data[stbi__jpeg_dezigzag[k++]];
+ if (*p != 0) {
+ if (stbi__jpeg_get_bit(j))
+ if ((*p & bit)==0) {
+ if (*p > 0)
+ *p += bit;
+ else
+ *p -= bit;
+ }
+ } else {
+ if (r == 0) {
+ *p = (short) s;
+ break;
+ }
+ --r;
+ }
+ }
+ } while (k <= j->spec_end);
+ }
+ }
+ return 1;
+}
+
+// take a -128..127 value and stbi__clamp it and convert to 0..255
+stbi_inline static stbi_uc stbi__clamp(int x)
+{
+ // trick to use a single test to catch both cases
+ if ((unsigned int) x > 255) {
+ if (x < 0) return 0;
+ if (x > 255) return 255;
+ }
+ return (stbi_uc) x;
+}
+
+#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5)))
+#define stbi__fsh(x) ((x) * 4096)
+
+// derived from jidctint -- DCT_ISLOW
+#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
+ int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
+ p2 = s2; \
+ p3 = s6; \
+ p1 = (p2+p3) * stbi__f2f(0.5411961f); \
+ t2 = p1 + p3*stbi__f2f(-1.847759065f); \
+ t3 = p1 + p2*stbi__f2f( 0.765366865f); \
+ p2 = s0; \
+ p3 = s4; \
+ t0 = stbi__fsh(p2+p3); \
+ t1 = stbi__fsh(p2-p3); \
+ x0 = t0+t3; \
+ x3 = t0-t3; \
+ x1 = t1+t2; \
+ x2 = t1-t2; \
+ t0 = s7; \
+ t1 = s5; \
+ t2 = s3; \
+ t3 = s1; \
+ p3 = t0+t2; \
+ p4 = t1+t3; \
+ p1 = t0+t3; \
+ p2 = t1+t2; \
+ p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
+ t0 = t0*stbi__f2f( 0.298631336f); \
+ t1 = t1*stbi__f2f( 2.053119869f); \
+ t2 = t2*stbi__f2f( 3.072711026f); \
+ t3 = t3*stbi__f2f( 1.501321110f); \
+ p1 = p5 + p1*stbi__f2f(-0.899976223f); \
+ p2 = p5 + p2*stbi__f2f(-2.562915447f); \
+ p3 = p3*stbi__f2f(-1.961570560f); \
+ p4 = p4*stbi__f2f(-0.390180644f); \
+ t3 += p1+p4; \
+ t2 += p2+p3; \
+ t1 += p2+p4; \
+ t0 += p1+p3;
+
+static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
+{
+ int i,val[64],*v=val;
+ stbi_uc *o;
+ short *d = data;
+
+ // columns
+ for (i=0; i < 8; ++i,++d, ++v) {
+ // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
+ if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
+ && d[40]==0 && d[48]==0 && d[56]==0) {
+ // no shortcut 0 seconds
+ // (1|2|3|4|5|6|7)==0 0 seconds
+ // all separate -0.047 seconds
+ // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
+ int dcterm = d[0]*4;
+ v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
+ } else {
+ STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])
+ // constants scaled things up by 1<<12; let's bring them back
+ // down, but keep 2 extra bits of precision
+ x0 += 512; x1 += 512; x2 += 512; x3 += 512;
+ v[ 0] = (x0+t3) >> 10;
+ v[56] = (x0-t3) >> 10;
+ v[ 8] = (x1+t2) >> 10;
+ v[48] = (x1-t2) >> 10;
+ v[16] = (x2+t1) >> 10;
+ v[40] = (x2-t1) >> 10;
+ v[24] = (x3+t0) >> 10;
+ v[32] = (x3-t0) >> 10;
+ }
+ }
+
+ for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
+ // no fast case since the first 1D IDCT spread components out
+ STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
+ // constants scaled things up by 1<<12, plus we had 1<<2 from first
+ // loop, plus horizontal and vertical each scale by sqrt(8) so together
+ // we've got an extra 1<<3, so 1<<17 total we need to remove.
+ // so we want to round that, which means adding 0.5 * 1<<17,
+ // aka 65536. Also, we'll end up with -128 to 127 that we want
+ // to encode as 0..255 by adding 128, so we'll add that before the shift
+ x0 += 65536 + (128<<17);
+ x1 += 65536 + (128<<17);
+ x2 += 65536 + (128<<17);
+ x3 += 65536 + (128<<17);
+ // tried computing the shifts into temps, or'ing the temps to see
+ // if any were out of range, but that was slower
+ o[0] = stbi__clamp((x0+t3) >> 17);
+ o[7] = stbi__clamp((x0-t3) >> 17);
+ o[1] = stbi__clamp((x1+t2) >> 17);
+ o[6] = stbi__clamp((x1-t2) >> 17);
+ o[2] = stbi__clamp((x2+t1) >> 17);
+ o[5] = stbi__clamp((x2-t1) >> 17);
+ o[3] = stbi__clamp((x3+t0) >> 17);
+ o[4] = stbi__clamp((x3-t0) >> 17);
+ }
+}
+
+#ifdef STBI_SSE2
+// sse2 integer IDCT. not the fastest possible implementation but it
+// produces bit-identical results to the generic C version so it's
+// fully "transparent".
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ // This is constructed to match our regular (generic) integer IDCT exactly.
+ __m128i row0, row1, row2, row3, row4, row5, row6, row7;
+ __m128i tmp;
+
+ // dot product constant: even elems=x, odd elems=y
+ #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))
+
+ // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
+ // out(1) = c1[even]*x + c1[odd]*y
+ #define dct_rot(out0,out1, x,y,c0,c1) \
+ __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \
+ __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \
+ __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
+ __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
+ __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
+ __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
+
+ // out = in << 12 (in 16-bit, out 32-bit)
+ #define dct_widen(out, in) \
+ __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
+ __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
+
+ // wide add
+ #define dct_wadd(out, a, b) \
+ __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_add_epi32(a##_h, b##_h)
+
+ // wide sub
+ #define dct_wsub(out, a, b) \
+ __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
+ __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
+
+ // butterfly a/b, add bias, then shift by "s" and pack
+ #define dct_bfly32o(out0, out1, a,b,bias,s) \
+ { \
+ __m128i abiased_l = _mm_add_epi32(a##_l, bias); \
+ __m128i abiased_h = _mm_add_epi32(a##_h, bias); \
+ dct_wadd(sum, abiased, b); \
+ dct_wsub(dif, abiased, b); \
+ out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
+ out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
+ }
+
+ // 8-bit interleave step (for transposes)
+ #define dct_interleave8(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi8(a, b); \
+ b = _mm_unpackhi_epi8(tmp, b)
+
+ // 16-bit interleave step (for transposes)
+ #define dct_interleave16(a, b) \
+ tmp = a; \
+ a = _mm_unpacklo_epi16(a, b); \
+ b = _mm_unpackhi_epi16(tmp, b)
+
+ #define dct_pass(bias,shift) \
+ { \
+ /* even part */ \
+ dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \
+ __m128i sum04 = _mm_add_epi16(row0, row4); \
+ __m128i dif04 = _mm_sub_epi16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \
+ dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \
+ __m128i sum17 = _mm_add_epi16(row1, row7); \
+ __m128i sum35 = _mm_add_epi16(row3, row5); \
+ dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \
+ dct_wadd(x4, y0o, y4o); \
+ dct_wadd(x5, y1o, y5o); \
+ dct_wadd(x6, y2o, y5o); \
+ dct_wadd(x7, y3o, y4o); \
+ dct_bfly32o(row0,row7, x0,x7,bias,shift); \
+ dct_bfly32o(row1,row6, x1,x6,bias,shift); \
+ dct_bfly32o(row2,row5, x2,x5,bias,shift); \
+ dct_bfly32o(row3,row4, x3,x4,bias,shift); \
+ }
+
+ __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
+ __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));
+ __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
+ __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
+ __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));
+ __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));
+ __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));
+ __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));
+
+ // rounding biases in column/row passes, see stbi__idct_block for explanation.
+ __m128i bias_0 = _mm_set1_epi32(512);
+ __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));
+
+ // load
+ row0 = _mm_load_si128((const __m128i *) (data + 0*8));
+ row1 = _mm_load_si128((const __m128i *) (data + 1*8));
+ row2 = _mm_load_si128((const __m128i *) (data + 2*8));
+ row3 = _mm_load_si128((const __m128i *) (data + 3*8));
+ row4 = _mm_load_si128((const __m128i *) (data + 4*8));
+ row5 = _mm_load_si128((const __m128i *) (data + 5*8));
+ row6 = _mm_load_si128((const __m128i *) (data + 6*8));
+ row7 = _mm_load_si128((const __m128i *) (data + 7*8));
+
+ // column pass
+ dct_pass(bias_0, 10);
+
+ {
+ // 16bit 8x8 transpose pass 1
+ dct_interleave16(row0, row4);
+ dct_interleave16(row1, row5);
+ dct_interleave16(row2, row6);
+ dct_interleave16(row3, row7);
+
+ // transpose pass 2
+ dct_interleave16(row0, row2);
+ dct_interleave16(row1, row3);
+ dct_interleave16(row4, row6);
+ dct_interleave16(row5, row7);
+
+ // transpose pass 3
+ dct_interleave16(row0, row1);
+ dct_interleave16(row2, row3);
+ dct_interleave16(row4, row5);
+ dct_interleave16(row6, row7);
+ }
+
+ // row pass
+ dct_pass(bias_1, 17);
+
+ {
+ // pack
+ __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
+ __m128i p1 = _mm_packus_epi16(row2, row3);
+ __m128i p2 = _mm_packus_epi16(row4, row5);
+ __m128i p3 = _mm_packus_epi16(row6, row7);
+
+ // 8bit 8x8 transpose pass 1
+ dct_interleave8(p0, p2); // a0e0a1e1...
+ dct_interleave8(p1, p3); // c0g0c1g1...
+
+ // transpose pass 2
+ dct_interleave8(p0, p1); // a0c0e0g0...
+ dct_interleave8(p2, p3); // b0d0f0h0...
+
+ // transpose pass 3
+ dct_interleave8(p0, p2); // a0b0c0d0...
+ dct_interleave8(p1, p3); // a4b4c4d4...
+
+ // store
+ _mm_storel_epi64((__m128i *) out, p0); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p2); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p1); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, p3); out += out_stride;
+ _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));
+ }
+
+#undef dct_const
+#undef dct_rot
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_interleave8
+#undef dct_interleave16
+#undef dct_pass
+}
+
+#endif // STBI_SSE2
+
+#ifdef STBI_NEON
+
+// NEON integer IDCT. should produce bit-identical
+// results to the generic C version.
+static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
+{
+ int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
+
+ int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
+ int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
+ int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));
+ int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));
+ int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
+ int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
+ int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
+ int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
+ int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));
+ int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));
+ int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));
+ int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));
+
+#define dct_long_mul(out, inq, coeff) \
+ int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
+
+#define dct_long_mac(out, acc, inq, coeff) \
+ int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
+ int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
+
+#define dct_widen(out, inq) \
+ int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
+ int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
+
+// wide add
+#define dct_wadd(out, a, b) \
+ int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
+
+// wide sub
+#define dct_wsub(out, a, b) \
+ int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
+ int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
+
+// butterfly a/b, then shift using "shiftop" by "s" and pack
+#define dct_bfly32o(out0,out1, a,b,shiftop,s) \
+ { \
+ dct_wadd(sum, a, b); \
+ dct_wsub(dif, a, b); \
+ out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
+ out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
+ }
+
+#define dct_pass(shiftop, shift) \
+ { \
+ /* even part */ \
+ int16x8_t sum26 = vaddq_s16(row2, row6); \
+ dct_long_mul(p1e, sum26, rot0_0); \
+ dct_long_mac(t2e, p1e, row6, rot0_1); \
+ dct_long_mac(t3e, p1e, row2, rot0_2); \
+ int16x8_t sum04 = vaddq_s16(row0, row4); \
+ int16x8_t dif04 = vsubq_s16(row0, row4); \
+ dct_widen(t0e, sum04); \
+ dct_widen(t1e, dif04); \
+ dct_wadd(x0, t0e, t3e); \
+ dct_wsub(x3, t0e, t3e); \
+ dct_wadd(x1, t1e, t2e); \
+ dct_wsub(x2, t1e, t2e); \
+ /* odd part */ \
+ int16x8_t sum15 = vaddq_s16(row1, row5); \
+ int16x8_t sum17 = vaddq_s16(row1, row7); \
+ int16x8_t sum35 = vaddq_s16(row3, row5); \
+ int16x8_t sum37 = vaddq_s16(row3, row7); \
+ int16x8_t sumodd = vaddq_s16(sum17, sum35); \
+ dct_long_mul(p5o, sumodd, rot1_0); \
+ dct_long_mac(p1o, p5o, sum17, rot1_1); \
+ dct_long_mac(p2o, p5o, sum35, rot1_2); \
+ dct_long_mul(p3o, sum37, rot2_0); \
+ dct_long_mul(p4o, sum15, rot2_1); \
+ dct_wadd(sump13o, p1o, p3o); \
+ dct_wadd(sump24o, p2o, p4o); \
+ dct_wadd(sump23o, p2o, p3o); \
+ dct_wadd(sump14o, p1o, p4o); \
+ dct_long_mac(x4, sump13o, row7, rot3_0); \
+ dct_long_mac(x5, sump24o, row5, rot3_1); \
+ dct_long_mac(x6, sump23o, row3, rot3_2); \
+ dct_long_mac(x7, sump14o, row1, rot3_3); \
+ dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \
+ dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \
+ dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \
+ dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \
+ }
+
+ // load
+ row0 = vld1q_s16(data + 0*8);
+ row1 = vld1q_s16(data + 1*8);
+ row2 = vld1q_s16(data + 2*8);
+ row3 = vld1q_s16(data + 3*8);
+ row4 = vld1q_s16(data + 4*8);
+ row5 = vld1q_s16(data + 5*8);
+ row6 = vld1q_s16(data + 6*8);
+ row7 = vld1q_s16(data + 7*8);
+
+ // add DC bias
+ row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
+
+ // column pass
+ dct_pass(vrshrn_n_s32, 10);
+
+ // 16bit 8x8 transpose
+ {
+// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
+// whether compilers actually get this is another story, sadly.
+#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }
+#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }
+
+ // pass 1
+ dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
+ dct_trn16(row2, row3);
+ dct_trn16(row4, row5);
+ dct_trn16(row6, row7);
+
+ // pass 2
+ dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
+ dct_trn32(row1, row3);
+ dct_trn32(row4, row6);
+ dct_trn32(row5, row7);
+
+ // pass 3
+ dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
+ dct_trn64(row1, row5);
+ dct_trn64(row2, row6);
+ dct_trn64(row3, row7);
+
+#undef dct_trn16
+#undef dct_trn32
+#undef dct_trn64
+ }
+
+ // row pass
+ // vrshrn_n_s32 only supports shifts up to 16, we need
+ // 17. so do a non-rounding shift of 16 first then follow
+ // up with a rounding shift by 1.
+ dct_pass(vshrn_n_s32, 16);
+
+ {
+ // pack and round
+ uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
+ uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
+ uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
+ uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
+ uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
+ uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
+ uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
+ uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
+
+ // again, these can translate into one instruction, but often don't.
+#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }
+#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }
+#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }
+
+ // sadly can't use interleaved stores here since we only write
+ // 8 bytes to each scan line!
+
+ // 8x8 8-bit transpose pass 1
+ dct_trn8_8(p0, p1);
+ dct_trn8_8(p2, p3);
+ dct_trn8_8(p4, p5);
+ dct_trn8_8(p6, p7);
+
+ // pass 2
+ dct_trn8_16(p0, p2);
+ dct_trn8_16(p1, p3);
+ dct_trn8_16(p4, p6);
+ dct_trn8_16(p5, p7);
+
+ // pass 3
+ dct_trn8_32(p0, p4);
+ dct_trn8_32(p1, p5);
+ dct_trn8_32(p2, p6);
+ dct_trn8_32(p3, p7);
+
+ // store
+ vst1_u8(out, p0); out += out_stride;
+ vst1_u8(out, p1); out += out_stride;
+ vst1_u8(out, p2); out += out_stride;
+ vst1_u8(out, p3); out += out_stride;
+ vst1_u8(out, p4); out += out_stride;
+ vst1_u8(out, p5); out += out_stride;
+ vst1_u8(out, p6); out += out_stride;
+ vst1_u8(out, p7);
+
+#undef dct_trn8_8
+#undef dct_trn8_16
+#undef dct_trn8_32
+ }
+
+#undef dct_long_mul
+#undef dct_long_mac
+#undef dct_widen
+#undef dct_wadd
+#undef dct_wsub
+#undef dct_bfly32o
+#undef dct_pass
+}
+
+#endif // STBI_NEON
+
+#define STBI__MARKER_none 0xff
+// if there's a pending marker from the entropy stream, return that
+// otherwise, fetch from the stream and get a marker. if there's no
+// marker, return 0xff, which is never a valid marker value
+static stbi_uc stbi__get_marker(stbi__jpeg *j)
+{
+ stbi_uc x;
+ if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
+ x = stbi__get8(j->s);
+ if (x != 0xff) return STBI__MARKER_none;
+ while (x == 0xff)
+ x = stbi__get8(j->s); // consume repeated 0xff fill bytes
+ return x;
+}
+
+// in each scan, we'll have scan_n components, and the order
+// of the components is specified by order[]
+#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
+
+// after a restart interval, stbi__jpeg_reset the entropy decoder and
+// the dc prediction
+static void stbi__jpeg_reset(stbi__jpeg *j)
+{
+ j->code_bits = 0;
+ j->code_buffer = 0;
+ j->nomore = 0;
+ j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0;
+ j->marker = STBI__MARKER_none;
+ j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
+ j->eob_run = 0;
+ // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
+ // since we don't even allow 1<<30 pixels
+}
+
+static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
+{
+ stbi__jpeg_reset(z);
+ if (!z->progressive) {
+ if (z->scan_n == 1) {
+ int i,j;
+ STBI_SIMD_ALIGN(short, data[64]);
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ // if it's NOT a restart, then just bail, so we get corrupt data
+ // rather than no data
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ STBI_SIMD_ALIGN(short, data[64]);
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x)*8;
+ int y2 = (j*z->img_comp[n].v + y)*8;
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ } else {
+ if (z->scan_n == 1) {
+ int i,j;
+ int n = z->order[0];
+ // non-interleaved data, we just need to process one block at a time,
+ // in trivial scanline order
+ // number of blocks to do just depends on how many actual "pixels" this
+ // component has, independent of interleaved MCU blocking and such
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ if (z->spec_start == 0) {
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ } else {
+ int ha = z->img_comp[n].ha;
+ if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
+ return 0;
+ }
+ // every data block is an MCU, so countdown the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ } else { // interleaved
+ int i,j,k,x,y;
+ for (j=0; j < z->img_mcu_y; ++j) {
+ for (i=0; i < z->img_mcu_x; ++i) {
+ // scan an interleaved mcu... process scan_n components in order
+ for (k=0; k < z->scan_n; ++k) {
+ int n = z->order[k];
+ // scan out an mcu's worth of this component; that's just determined
+ // by the basic H and V specified for the component
+ for (y=0; y < z->img_comp[n].v; ++y) {
+ for (x=0; x < z->img_comp[n].h; ++x) {
+ int x2 = (i*z->img_comp[n].h + x);
+ int y2 = (j*z->img_comp[n].v + y);
+ short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
+ if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
+ return 0;
+ }
+ }
+ }
+ // after all interleaved components, that's an interleaved MCU,
+ // so now count down the restart interval
+ if (--z->todo <= 0) {
+ if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
+ if (!STBI__RESTART(z->marker)) return 1;
+ stbi__jpeg_reset(z);
+ }
+ }
+ }
+ return 1;
+ }
+ }
+}
+
+static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant)
+{
+ int i;
+ for (i=0; i < 64; ++i)
+ data[i] *= dequant[i];
+}
+
+static void stbi__jpeg_finish(stbi__jpeg *z)
+{
+ if (z->progressive) {
+ // dequantize and idct the data
+ int i,j,n;
+ for (n=0; n < z->s->img_n; ++n) {
+ int w = (z->img_comp[n].x+7) >> 3;
+ int h = (z->img_comp[n].y+7) >> 3;
+ for (j=0; j < h; ++j) {
+ for (i=0; i < w; ++i) {
+ short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
+ stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
+ z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
+ }
+ }
+ }
+ }
+}
+
+static int stbi__process_marker(stbi__jpeg *z, int m)
+{
+ int L;
+ switch (m) {
+ case STBI__MARKER_none: // no marker found
+ return stbi__err("expected marker","Corrupt JPEG");
+
+ case 0xDD: // DRI - specify restart interval
+ if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
+ z->restart_interval = stbi__get16be(z->s);
+ return 1;
+
+ case 0xDB: // DQT - define quantization table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ int q = stbi__get8(z->s);
+ int p = q >> 4, sixteen = (p != 0);
+ int t = q & 15,i;
+ if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG");
+ if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
+
+ for (i=0; i < 64; ++i)
+ z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s));
+ L -= (sixteen ? 129 : 65);
+ }
+ return L==0;
+
+ case 0xC4: // DHT - define huffman table
+ L = stbi__get16be(z->s)-2;
+ while (L > 0) {
+ stbi_uc *v;
+ int sizes[16],i,n=0;
+ int q = stbi__get8(z->s);
+ int tc = q >> 4;
+ int th = q & 15;
+ if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
+ for (i=0; i < 16; ++i) {
+ sizes[i] = stbi__get8(z->s);
+ n += sizes[i];
+ }
+ if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values!
+ L -= 17;
+ if (tc == 0) {
+ if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
+ v = z->huff_dc[th].values;
+ } else {
+ if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
+ v = z->huff_ac[th].values;
+ }
+ for (i=0; i < n; ++i)
+ v[i] = stbi__get8(z->s);
+ if (tc != 0)
+ stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
+ L -= n;
+ }
+ return L==0;
+ }
+
+ // check for comment block or APP blocks
+ if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
+ L = stbi__get16be(z->s);
+ if (L < 2) {
+ if (m == 0xFE)
+ return stbi__err("bad COM len","Corrupt JPEG");
+ else
+ return stbi__err("bad APP len","Corrupt JPEG");
+ }
+ L -= 2;
+
+ if (m == 0xE0 && L >= 5) { // JFIF APP0 segment
+ static const unsigned char tag[5] = {'J','F','I','F','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 5; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 5;
+ if (ok)
+ z->jfif = 1;
+ } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment
+ static const unsigned char tag[6] = {'A','d','o','b','e','\0'};
+ int ok = 1;
+ int i;
+ for (i=0; i < 6; ++i)
+ if (stbi__get8(z->s) != tag[i])
+ ok = 0;
+ L -= 6;
+ if (ok) {
+ stbi__get8(z->s); // version
+ stbi__get16be(z->s); // flags0
+ stbi__get16be(z->s); // flags1
+ z->app14_color_transform = stbi__get8(z->s); // color transform
+ L -= 6;
+ }
+ }
+
+ stbi__skip(z->s, L);
+ return 1;
+ }
+
+ return stbi__err("unknown marker","Corrupt JPEG");
+}
+
+// after we see SOS
+static int stbi__process_scan_header(stbi__jpeg *z)
+{
+ int i;
+ int Ls = stbi__get16be(z->s);
+ z->scan_n = stbi__get8(z->s);
+ if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG");
+ if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG");
+ for (i=0; i < z->scan_n; ++i) {
+ int id = stbi__get8(z->s), which;
+ int q = stbi__get8(z->s);
+ for (which = 0; which < z->s->img_n; ++which)
+ if (z->img_comp[which].id == id)
+ break;
+ if (which == z->s->img_n) return 0; // no match
+ z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
+ z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
+ z->order[i] = which;
+ }
+
+ {
+ int aa;
+ z->spec_start = stbi__get8(z->s);
+ z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
+ aa = stbi__get8(z->s);
+ z->succ_high = (aa >> 4);
+ z->succ_low = (aa & 15);
+ if (z->progressive) {
+ if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
+ return stbi__err("bad SOS", "Corrupt JPEG");
+ } else {
+ if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG");
+ z->spec_end = 63;
+ }
+ }
+
+ return 1;
+}
+
+static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why)
+{
+ int i;
+ for (i=0; i < ncomp; ++i) {
+ if (z->img_comp[i].raw_data) {
+ STBI_FREE(z->img_comp[i].raw_data);
+ z->img_comp[i].raw_data = NULL;
+ z->img_comp[i].data = NULL;
+ }
+ if (z->img_comp[i].raw_coeff) {
+ STBI_FREE(z->img_comp[i].raw_coeff);
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].coeff = 0;
+ }
+ if (z->img_comp[i].linebuf) {
+ STBI_FREE(z->img_comp[i].linebuf);
+ z->img_comp[i].linebuf = NULL;
+ }
+ }
+ return why;
+}
+
+static int stbi__process_frame_header(stbi__jpeg *z, int scan)
+{
+ stbi__context *s = z->s;
+ int Lf,p,i,q, h_max=1,v_max=1,c;
+ Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
+ p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
+ s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
+ s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ c = stbi__get8(s);
+ if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG");
+ s->img_n = c;
+ for (i=0; i < c; ++i) {
+ z->img_comp[i].data = NULL;
+ z->img_comp[i].linebuf = NULL;
+ }
+
+ if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
+
+ z->rgb = 0;
+ for (i=0; i < s->img_n; ++i) {
+ static const unsigned char rgb[3] = { 'R', 'G', 'B' };
+ z->img_comp[i].id = stbi__get8(s);
+ if (s->img_n == 3 && z->img_comp[i].id == rgb[i])
+ ++z->rgb;
+ q = stbi__get8(s);
+ z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
+ z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
+ z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
+ }
+
+ if (scan != STBI__SCAN_load) return 1;
+
+ if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode");
+
+ for (i=0; i < s->img_n; ++i) {
+ if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
+ if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
+ }
+
+ // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios
+ // and I've never seen a non-corrupted JPEG file actually use them
+ for (i=0; i < s->img_n; ++i) {
+ if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG");
+ if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG");
+ }
+
+ // compute interleaved mcu info
+ z->img_h_max = h_max;
+ z->img_v_max = v_max;
+ z->img_mcu_w = h_max * 8;
+ z->img_mcu_h = v_max * 8;
+ // these sizes can't be more than 17 bits
+ z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
+ z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
+
+ for (i=0; i < s->img_n; ++i) {
+ // number of effective pixels (e.g. for non-interleaved MCU)
+ z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
+ z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
+ // to simplify generation, we'll allocate enough memory to decode
+ // the bogus oversized data from using interleaved MCUs and their
+ // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
+ // discard the extra data until colorspace conversion
+ //
+ // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)
+ // so these muls can't overflow with 32-bit ints (which we require)
+ z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
+ z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
+ z->img_comp[i].coeff = 0;
+ z->img_comp[i].raw_coeff = 0;
+ z->img_comp[i].linebuf = NULL;
+ z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);
+ if (z->img_comp[i].raw_data == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ // align blocks for idct using mmx/sse
+ z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
+ if (z->progressive) {
+ // w2, h2 are multiples of 8 (see above)
+ z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;
+ z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;
+ z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);
+ if (z->img_comp[i].raw_coeff == NULL)
+ return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));
+ z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
+ }
+ }
+
+ return 1;
+}
+
+// use comparisons since in some cases we handle more than one case (e.g. SOF)
+#define stbi__DNL(x) ((x) == 0xdc)
+#define stbi__SOI(x) ((x) == 0xd8)
+#define stbi__EOI(x) ((x) == 0xd9)
+#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
+#define stbi__SOS(x) ((x) == 0xda)
+
+#define stbi__SOF_progressive(x) ((x) == 0xc2)
+
+static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
+{
+ int m;
+ z->jfif = 0;
+ z->app14_color_transform = -1; // valid values are 0,1,2
+ z->marker = STBI__MARKER_none; // initialize cached marker to empty
+ m = stbi__get_marker(z);
+ if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG");
+ if (scan == STBI__SCAN_type) return 1;
+ m = stbi__get_marker(z);
+ while (!stbi__SOF(m)) {
+ if (!stbi__process_marker(z,m)) return 0;
+ m = stbi__get_marker(z);
+ while (m == STBI__MARKER_none) {
+ // some files have extra padding after their blocks, so ok, we'll scan
+ if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
+ m = stbi__get_marker(z);
+ }
+ }
+ z->progressive = stbi__SOF_progressive(m);
+ if (!stbi__process_frame_header(z, scan)) return 0;
+ return 1;
+}
+
+static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j)
+{
+ // some JPEGs have junk at end, skip over it but if we find what looks
+ // like a valid marker, resume there
+ while (!stbi__at_eof(j->s)) {
+ stbi_uc x = stbi__get8(j->s);
+ while (x == 0xff) { // might be a marker
+ if (stbi__at_eof(j->s)) return STBI__MARKER_none;
+ x = stbi__get8(j->s);
+ if (x != 0x00 && x != 0xff) {
+ // not a stuffed zero or lead-in to another marker, looks
+ // like an actual marker, return it
+ return x;
+ }
+ // stuffed zero has x=0 now which ends the loop, meaning we go
+ // back to regular scan loop.
+ // repeated 0xff keeps trying to read the next byte of the marker.
+ }
+ }
+ return STBI__MARKER_none;
+}
+
+// decode image to YCbCr format
+static int stbi__decode_jpeg_image(stbi__jpeg *j)
+{
+ int m;
+ for (m = 0; m < 4; m++) {
+ j->img_comp[m].raw_data = NULL;
+ j->img_comp[m].raw_coeff = NULL;
+ }
+ j->restart_interval = 0;
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
+ m = stbi__get_marker(j);
+ while (!stbi__EOI(m)) {
+ if (stbi__SOS(m)) {
+ if (!stbi__process_scan_header(j)) return 0;
+ if (!stbi__parse_entropy_coded_data(j)) return 0;
+ if (j->marker == STBI__MARKER_none ) {
+ j->marker = stbi__skip_jpeg_junk_at_end(j);
+ // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
+ }
+ m = stbi__get_marker(j);
+ if (STBI__RESTART(m))
+ m = stbi__get_marker(j);
+ } else if (stbi__DNL(m)) {
+ int Ld = stbi__get16be(j->s);
+ stbi__uint32 NL = stbi__get16be(j->s);
+ if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG");
+ if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG");
+ m = stbi__get_marker(j);
+ } else {
+ if (!stbi__process_marker(j, m)) return 1;
+ m = stbi__get_marker(j);
+ }
+ }
+ if (j->progressive)
+ stbi__jpeg_finish(j);
+ return 1;
+}
+
+// static jfif-centered resampling (across block boundaries)
+
+typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
+ int w, int hs);
+
+#define stbi__div4(x) ((stbi_uc) ((x) >> 2))
+
+static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ STBI_NOTUSED(out);
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(w);
+ STBI_NOTUSED(hs);
+ return in_near;
+}
+
+static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples vertically for every one in input
+ int i;
+ STBI_NOTUSED(hs);
+ for (i=0; i < w; ++i)
+ out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
+ return out;
+}
+
+static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate two samples horizontally for every one in input
+ int i;
+ stbi_uc *input = in_near;
+
+ if (w == 1) {
+ // if only one sample, can't do any interpolation
+ out[0] = out[1] = input[0];
+ return out;
+ }
+
+ out[0] = input[0];
+ out[1] = stbi__div4(input[0]*3 + input[1] + 2);
+ for (i=1; i < w-1; ++i) {
+ int n = 3*input[i]+2;
+ out[i*2+0] = stbi__div4(n+input[i-1]);
+ out[i*2+1] = stbi__div4(n+input[i+1]);
+ }
+ out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
+ out[i*2+1] = input[w-1];
+
+ STBI_NOTUSED(in_far);
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#define stbi__div16(x) ((stbi_uc) ((x) >> 4))
+
+static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i,t0,t1;
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ out[0] = stbi__div4(t1+2);
+ for (i=1; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // need to generate 2x2 samples for every one in input
+ int i=0,t0,t1;
+
+ if (w == 1) {
+ out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
+ return out;
+ }
+
+ t1 = 3*in_near[0] + in_far[0];
+ // process groups of 8 pixels for as long as we can.
+ // note we can't handle the last pixel in a row in this loop
+ // because we need to handle the filter boundary conditions.
+ for (; i < ((w-1) & ~7); i += 8) {
+#if defined(STBI_SSE2)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ __m128i zero = _mm_setzero_si128();
+ __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i));
+ __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));
+ __m128i farw = _mm_unpacklo_epi8(farb, zero);
+ __m128i nearw = _mm_unpacklo_epi8(nearb, zero);
+ __m128i diff = _mm_sub_epi16(farw, nearw);
+ __m128i nears = _mm_slli_epi16(nearw, 2);
+ __m128i curr = _mm_add_epi16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ __m128i prv0 = _mm_slli_si128(curr, 2);
+ __m128i nxt0 = _mm_srli_si128(curr, 2);
+ __m128i prev = _mm_insert_epi16(prv0, t1, 0);
+ __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ __m128i bias = _mm_set1_epi16(8);
+ __m128i curs = _mm_slli_epi16(curr, 2);
+ __m128i prvd = _mm_sub_epi16(prev, curr);
+ __m128i nxtd = _mm_sub_epi16(next, curr);
+ __m128i curb = _mm_add_epi16(curs, bias);
+ __m128i even = _mm_add_epi16(prvd, curb);
+ __m128i odd = _mm_add_epi16(nxtd, curb);
+
+ // interleave even and odd pixels, then undo scaling.
+ __m128i int0 = _mm_unpacklo_epi16(even, odd);
+ __m128i int1 = _mm_unpackhi_epi16(even, odd);
+ __m128i de0 = _mm_srli_epi16(int0, 4);
+ __m128i de1 = _mm_srli_epi16(int1, 4);
+
+ // pack and write output
+ __m128i outv = _mm_packus_epi16(de0, de1);
+ _mm_storeu_si128((__m128i *) (out + i*2), outv);
+#elif defined(STBI_NEON)
+ // load and perform the vertical filtering pass
+ // this uses 3*x + y = 4*x + (y - x)
+ uint8x8_t farb = vld1_u8(in_far + i);
+ uint8x8_t nearb = vld1_u8(in_near + i);
+ int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
+ int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
+ int16x8_t curr = vaddq_s16(nears, diff); // current row
+
+ // horizontal filter works the same based on shifted vers of current
+ // row. "prev" is current row shifted right by 1 pixel; we need to
+ // insert the previous pixel value (from t1).
+ // "next" is current row shifted left by 1 pixel, with first pixel
+ // of next block of 8 pixels added in.
+ int16x8_t prv0 = vextq_s16(curr, curr, 7);
+ int16x8_t nxt0 = vextq_s16(curr, curr, 1);
+ int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
+ int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);
+
+ // horizontal filter, polyphase implementation since it's convenient:
+ // even pixels = 3*cur + prev = cur*4 + (prev - cur)
+ // odd pixels = 3*cur + next = cur*4 + (next - cur)
+ // note the shared term.
+ int16x8_t curs = vshlq_n_s16(curr, 2);
+ int16x8_t prvd = vsubq_s16(prev, curr);
+ int16x8_t nxtd = vsubq_s16(next, curr);
+ int16x8_t even = vaddq_s16(curs, prvd);
+ int16x8_t odd = vaddq_s16(curs, nxtd);
+
+ // undo scaling and round, then store with even/odd phases interleaved
+ uint8x8x2_t o;
+ o.val[0] = vqrshrun_n_s16(even, 4);
+ o.val[1] = vqrshrun_n_s16(odd, 4);
+ vst2_u8(out + i*2, o);
+#endif
+
+ // "previous" value for next iter
+ t1 = 3*in_near[i+7] + in_far[i+7];
+ }
+
+ t0 = t1;
+ t1 = 3*in_near[i] + in_far[i];
+ out[i*2] = stbi__div16(3*t1 + t0 + 8);
+
+ for (++i; i < w; ++i) {
+ t0 = t1;
+ t1 = 3*in_near[i]+in_far[i];
+ out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
+ out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
+ }
+ out[w*2-1] = stbi__div4(t1+2);
+
+ STBI_NOTUSED(hs);
+
+ return out;
+}
+#endif
+
+static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
+{
+ // resample with nearest-neighbor
+ int i,j;
+ STBI_NOTUSED(in_far);
+ for (i=0; i < w; ++i)
+ for (j=0; j < hs; ++j)
+ out[i*hs+j] = in_near[i];
+ return out;
+}
+
+// this is a reduced-precision calculation of YCbCr-to-RGB introduced
+// to make sure the code produces the same results in both SIMD and scalar
+#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
+static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
+{
+ int i;
+ for (i=0; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+
+#if defined(STBI_SSE2) || defined(STBI_NEON)
+static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)
+{
+ int i = 0;
+
+#ifdef STBI_SSE2
+ // step == 3 is pretty ugly on the final interleave, and i'm not convinced
+ // it's useful in practice (you wouldn't use it for textures, for example).
+ // so just accelerate step == 4 case.
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ __m128i signflip = _mm_set1_epi8(-0x80);
+ __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f));
+ __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));
+ __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));
+ __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f));
+ __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
+ __m128i xw = _mm_set1_epi16(255); // alpha channel
+
+ for (; i+7 < count; i += 8) {
+ // load
+ __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));
+ __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));
+ __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));
+ __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
+ __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
+
+ // unpack to short (and left-shift cr, cb by 8)
+ __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
+ __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
+ __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
+
+ // color transform
+ __m128i yws = _mm_srli_epi16(yw, 4);
+ __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
+ __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
+ __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
+ __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
+ __m128i rws = _mm_add_epi16(cr0, yws);
+ __m128i gwt = _mm_add_epi16(cb0, yws);
+ __m128i bws = _mm_add_epi16(yws, cb1);
+ __m128i gws = _mm_add_epi16(gwt, cr1);
+
+ // descale
+ __m128i rw = _mm_srai_epi16(rws, 4);
+ __m128i bw = _mm_srai_epi16(bws, 4);
+ __m128i gw = _mm_srai_epi16(gws, 4);
+
+ // back to byte, set up for transpose
+ __m128i brb = _mm_packus_epi16(rw, bw);
+ __m128i gxb = _mm_packus_epi16(gw, xw);
+
+ // transpose to interleave channels
+ __m128i t0 = _mm_unpacklo_epi8(brb, gxb);
+ __m128i t1 = _mm_unpackhi_epi8(brb, gxb);
+ __m128i o0 = _mm_unpacklo_epi16(t0, t1);
+ __m128i o1 = _mm_unpackhi_epi16(t0, t1);
+
+ // store
+ _mm_storeu_si128((__m128i *) (out + 0), o0);
+ _mm_storeu_si128((__m128i *) (out + 16), o1);
+ out += 32;
+ }
+ }
+#endif
+
+#ifdef STBI_NEON
+ // in this version, step=3 support would be easy to add. but is there demand?
+ if (step == 4) {
+ // this is a fairly straightforward implementation and not super-optimized.
+ uint8x8_t signflip = vdup_n_u8(0x80);
+ int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f));
+ int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));
+ int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));
+ int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f));
+
+ for (; i+7 < count; i += 8) {
+ // load
+ uint8x8_t y_bytes = vld1_u8(y + i);
+ uint8x8_t cr_bytes = vld1_u8(pcr + i);
+ uint8x8_t cb_bytes = vld1_u8(pcb + i);
+ int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
+ int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
+
+ // expand to s16
+ int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
+ int16x8_t crw = vshll_n_s8(cr_biased, 7);
+ int16x8_t cbw = vshll_n_s8(cb_biased, 7);
+
+ // color transform
+ int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
+ int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
+ int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
+ int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
+ int16x8_t rws = vaddq_s16(yws, cr0);
+ int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
+ int16x8_t bws = vaddq_s16(yws, cb1);
+
+ // undo scaling, round, convert to byte
+ uint8x8x4_t o;
+ o.val[0] = vqrshrun_n_s16(rws, 4);
+ o.val[1] = vqrshrun_n_s16(gws, 4);
+ o.val[2] = vqrshrun_n_s16(bws, 4);
+ o.val[3] = vdup_n_u8(255);
+
+ // store, interleaving r/g/b/a
+ vst4_u8(out, o);
+ out += 8*4;
+ }
+ }
+#endif
+
+ for (; i < count; ++i) {
+ int y_fixed = (y[i] << 20) + (1<<19); // rounding
+ int r,g,b;
+ int cr = pcr[i] - 128;
+ int cb = pcb[i] - 128;
+ r = y_fixed + cr* stbi__float2fixed(1.40200f);
+ g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000);
+ b = y_fixed + cb* stbi__float2fixed(1.77200f);
+ r >>= 20;
+ g >>= 20;
+ b >>= 20;
+ if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
+ if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
+ if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
+ out[0] = (stbi_uc)r;
+ out[1] = (stbi_uc)g;
+ out[2] = (stbi_uc)b;
+ out[3] = 255;
+ out += step;
+ }
+}
+#endif
+
+// set up the kernels
+static void stbi__setup_jpeg(stbi__jpeg *j)
+{
+ j->idct_block_kernel = stbi__idct_block;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
+
+#ifdef STBI_SSE2
+ if (stbi__sse2_available()) {
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+ }
+#endif
+
+#ifdef STBI_NEON
+ j->idct_block_kernel = stbi__idct_simd;
+ j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
+ j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
+#endif
+}
+
+// clean up the temporary component buffers
+static void stbi__cleanup_jpeg(stbi__jpeg *j)
+{
+ stbi__free_jpeg_components(j, j->s->img_n, 0);
+}
+
+typedef struct
+{
+ resample_row_func resample;
+ stbi_uc *line0,*line1;
+ int hs,vs; // expansion factor in each axis
+ int w_lores; // horizontal pixels pre-expansion
+ int ystep; // how far through vertical expansion we are
+ int ypos; // which pre-expansion row we're on
+} stbi__resample;
+
+// fast 0..255 * 0..255 => 0..255 rounded multiplication
+static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y)
+{
+ unsigned int t = x*y + 128;
+ return (stbi_uc) ((t + (t >>8)) >> 8);
+}
+
+static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
+{
+ int n, decode_n, is_rgb;
+ z->s->img_n = 0; // make stbi__cleanup_jpeg safe
+
+ // validate req_comp
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+
+ // load a jpeg image from whichever source, but leave in YCbCr format
+ if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // determine actual number of components to generate
+ n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1;
+
+ is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif));
+
+ if (z->s->img_n == 3 && n < 3 && !is_rgb)
+ decode_n = 1;
+ else
+ decode_n = z->s->img_n;
+
+ // nothing to do if no components requested; check this now to avoid
+ // accessing uninitialized coutput[0] later
+ if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; }
+
+ // resample and color-convert
+ {
+ int k;
+ unsigned int i,j;
+ stbi_uc *output;
+ stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL };
+
+ stbi__resample res_comp[4];
+
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+
+ // allocate line buffer big enough for upsampling off the edges
+ // with upsample factor of 4
+ z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
+ if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ r->hs = z->img_h_max / z->img_comp[k].h;
+ r->vs = z->img_v_max / z->img_comp[k].v;
+ r->ystep = r->vs >> 1;
+ r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
+ r->ypos = 0;
+ r->line0 = r->line1 = z->img_comp[k].data;
+
+ if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
+ else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
+ else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
+ else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
+ else r->resample = stbi__resample_row_generic;
+ }
+
+ // can't error after this so, this is safe
+ output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);
+ if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
+
+ // now go ahead and resample
+ for (j=0; j < z->s->img_y; ++j) {
+ stbi_uc *out = output + n * z->s->img_x * j;
+ for (k=0; k < decode_n; ++k) {
+ stbi__resample *r = &res_comp[k];
+ int y_bot = r->ystep >= (r->vs >> 1);
+ coutput[k] = r->resample(z->img_comp[k].linebuf,
+ y_bot ? r->line1 : r->line0,
+ y_bot ? r->line0 : r->line1,
+ r->w_lores, r->hs);
+ if (++r->ystep >= r->vs) {
+ r->ystep = 0;
+ r->line0 = r->line1;
+ if (++r->ypos < z->img_comp[k].y)
+ r->line1 += z->img_comp[k].w2;
+ }
+ }
+ if (n >= 3) {
+ stbi_uc *y = coutput[0];
+ if (z->s->img_n == 3) {
+ if (is_rgb) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = y[i];
+ out[1] = coutput[1][i];
+ out[2] = coutput[2][i];
+ out[3] = 255;
+ out += n;
+ }
+ } else {
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else if (z->s->img_n == 4) {
+ if (z->app14_color_transform == 0) { // CMYK
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(coutput[0][i], m);
+ out[1] = stbi__blinn_8x8(coutput[1][i], m);
+ out[2] = stbi__blinn_8x8(coutput[2][i], m);
+ out[3] = 255;
+ out += n;
+ }
+ } else if (z->app14_color_transform == 2) { // YCCK
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ out[0] = stbi__blinn_8x8(255 - out[0], m);
+ out[1] = stbi__blinn_8x8(255 - out[1], m);
+ out[2] = stbi__blinn_8x8(255 - out[2], m);
+ out += n;
+ }
+ } else { // YCbCr + alpha? Ignore the fourth channel for now
+ z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
+ }
+ } else
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = out[1] = out[2] = y[i];
+ out[3] = 255; // not used if n==3
+ out += n;
+ }
+ } else {
+ if (is_rgb) {
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i)
+ *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ else {
+ for (i=0; i < z->s->img_x; ++i, out += 2) {
+ out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]);
+ out[1] = 255;
+ }
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 0) {
+ for (i=0; i < z->s->img_x; ++i) {
+ stbi_uc m = coutput[3][i];
+ stbi_uc r = stbi__blinn_8x8(coutput[0][i], m);
+ stbi_uc g = stbi__blinn_8x8(coutput[1][i], m);
+ stbi_uc b = stbi__blinn_8x8(coutput[2][i], m);
+ out[0] = stbi__compute_y(r, g, b);
+ out[1] = 255;
+ out += n;
+ }
+ } else if (z->s->img_n == 4 && z->app14_color_transform == 2) {
+ for (i=0; i < z->s->img_x; ++i) {
+ out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]);
+ out[1] = 255;
+ out += n;
+ }
+ } else {
+ stbi_uc *y = coutput[0];
+ if (n == 1)
+ for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
+ else
+ for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; }
+ }
+ }
+ }
+ stbi__cleanup_jpeg(z);
+ *out_x = z->s->img_x;
+ *out_y = z->s->img_y;
+ if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output
+ return output;
+ }
+}
+
+static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ unsigned char* result;
+ stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__errpuc("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ STBI_NOTUSED(ri);
+ j->s = s;
+ stbi__setup_jpeg(j);
+ result = load_jpeg_image(j, x,y,comp,req_comp);
+ STBI_FREE(j);
+ return result;
+}
+
+static int stbi__jpeg_test(stbi__context *s)
+{
+ int r;
+ stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ stbi__setup_jpeg(j);
+ r = stbi__decode_jpeg_header(j, STBI__SCAN_type);
+ stbi__rewind(s);
+ STBI_FREE(j);
+ return r;
+}
+
+static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
+{
+ if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
+ stbi__rewind( j->s );
+ return 0;
+ }
+ if (x) *x = j->s->img_x;
+ if (y) *y = j->s->img_y;
+ if (comp) *comp = j->s->img_n >= 3 ? 3 : 1;
+ return 1;
+}
+
+static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int result;
+ stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));
+ if (!j) return stbi__err("outofmem", "Out of memory");
+ memset(j, 0, sizeof(stbi__jpeg));
+ j->s = s;
+ result = stbi__jpeg_info_raw(j, x, y, comp);
+ STBI_FREE(j);
+ return result;
+}
+#endif
+
+// public domain zlib decode v0.2 Sean Barrett 2006-11-18
+// simple implementation
+// - all input must be provided in an upfront buffer
+// - all output is written to a single output buffer (can malloc/realloc)
+// performance
+// - fast huffman
+
+#ifndef STBI_NO_ZLIB
+
+// fast-way is faster to check than jpeg huffman, but slow way is slower
+#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
+#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
+#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet
+
+// zlib-style huffman encoding
+// (jpegs packs from left, zlib from right, so can't share code)
+typedef struct
+{
+ stbi__uint16 fast[1 << STBI__ZFAST_BITS];
+ stbi__uint16 firstcode[16];
+ int maxcode[17];
+ stbi__uint16 firstsymbol[16];
+ stbi_uc size[STBI__ZNSYMS];
+ stbi__uint16 value[STBI__ZNSYMS];
+} stbi__zhuffman;
+
+stbi_inline static int stbi__bitreverse16(int n)
+{
+ n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
+ n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
+ n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
+ n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
+ return n;
+}
+
+stbi_inline static int stbi__bit_reverse(int v, int bits)
+{
+ STBI_ASSERT(bits <= 16);
+ // to bit reverse n bits, reverse 16 and shift
+ // e.g. 11 bits, bit reverse and shift away 5
+ return stbi__bitreverse16(v) >> (16-bits);
+}
+
+static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num)
+{
+ int i,k=0;
+ int code, next_code[16], sizes[17];
+
+ // DEFLATE spec for generating codes
+ memset(sizes, 0, sizeof(sizes));
+ memset(z->fast, 0, sizeof(z->fast));
+ for (i=0; i < num; ++i)
+ ++sizes[sizelist[i]];
+ sizes[0] = 0;
+ for (i=1; i < 16; ++i)
+ if (sizes[i] > (1 << i))
+ return stbi__err("bad sizes", "Corrupt PNG");
+ code = 0;
+ for (i=1; i < 16; ++i) {
+ next_code[i] = code;
+ z->firstcode[i] = (stbi__uint16) code;
+ z->firstsymbol[i] = (stbi__uint16) k;
+ code = (code + sizes[i]);
+ if (sizes[i])
+ if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
+ z->maxcode[i] = code << (16-i); // preshift for inner loop
+ code <<= 1;
+ k += sizes[i];
+ }
+ z->maxcode[16] = 0x10000; // sentinel
+ for (i=0; i < num; ++i) {
+ int s = sizelist[i];
+ if (s) {
+ int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
+ stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
+ z->size [c] = (stbi_uc ) s;
+ z->value[c] = (stbi__uint16) i;
+ if (s <= STBI__ZFAST_BITS) {
+ int j = stbi__bit_reverse(next_code[s],s);
+ while (j < (1 << STBI__ZFAST_BITS)) {
+ z->fast[j] = fastv;
+ j += (1 << s);
+ }
+ }
+ ++next_code[s];
+ }
+ }
+ return 1;
+}
+
+// zlib-from-memory implementation for PNG reading
+// because PNG allows splitting the zlib stream arbitrarily,
+// and it's annoying structurally to have PNG call ZLIB call PNG,
+// we require PNG read all the IDATs and combine them into a single
+// memory buffer
+
+typedef struct
+{
+ stbi_uc *zbuffer, *zbuffer_end;
+ int num_bits;
+ int hit_zeof_once;
+ stbi__uint32 code_buffer;
+
+ char *zout;
+ char *zout_start;
+ char *zout_end;
+ int z_expandable;
+
+ stbi__zhuffman z_length, z_distance;
+} stbi__zbuf;
+
+stbi_inline static int stbi__zeof(stbi__zbuf *z)
+{
+ return (z->zbuffer >= z->zbuffer_end);
+}
+
+stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
+{
+ return stbi__zeof(z) ? 0 : *z->zbuffer++;
+}
+
+static void stbi__fill_bits(stbi__zbuf *z)
+{
+ do {
+ if (z->code_buffer >= (1U << z->num_bits)) {
+ z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */
+ return;
+ }
+ z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits;
+ z->num_bits += 8;
+ } while (z->num_bits <= 24);
+}
+
+stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
+{
+ unsigned int k;
+ if (z->num_bits < n) stbi__fill_bits(z);
+ k = z->code_buffer & ((1 << n) - 1);
+ z->code_buffer >>= n;
+ z->num_bits -= n;
+ return k;
+}
+
+static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s,k;
+ // not resolved by fast table, so compute it the slow way
+ // use jpeg approach, which requires MSbits at top
+ k = stbi__bit_reverse(a->code_buffer, 16);
+ for (s=STBI__ZFAST_BITS+1; ; ++s)
+ if (k < z->maxcode[s])
+ break;
+ if (s >= 16) return -1; // invalid code!
+ // code size is s, so:
+ b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
+ if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!
+ if (z->size[b] != s) return -1; // was originally an assert, but report failure instead.
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return z->value[b];
+}
+
+stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
+{
+ int b,s;
+ if (a->num_bits < 16) {
+ if (stbi__zeof(a)) {
+ if (!a->hit_zeof_once) {
+ // This is the first time we hit eof, insert 16 extra padding btis
+ // to allow us to keep going; if we actually consume any of them
+ // though, that is invalid data. This is caught later.
+ a->hit_zeof_once = 1;
+ a->num_bits += 16; // add 16 implicit zero bits
+ } else {
+ // We already inserted our extra 16 padding bits and are again
+ // out, this stream is actually prematurely terminated.
+ return -1;
+ }
+ } else {
+ stbi__fill_bits(a);
+ }
+ }
+ b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
+ if (b) {
+ s = b >> 9;
+ a->code_buffer >>= s;
+ a->num_bits -= s;
+ return b & 511;
+ }
+ return stbi__zhuffman_decode_slowpath(a, z);
+}
+
+static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes
+{
+ char *q;
+ unsigned int cur, limit, old_limit;
+ z->zout = zout;
+ if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
+ cur = (unsigned int) (z->zout - z->zout_start);
+ limit = old_limit = (unsigned) (z->zout_end - z->zout_start);
+ if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory");
+ while (cur + n > limit) {
+ if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory");
+ limit *= 2;
+ }
+ q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit);
+ STBI_NOTUSED(old_limit);
+ if (q == NULL) return stbi__err("outofmem", "Out of memory");
+ z->zout_start = q;
+ z->zout = q + cur;
+ z->zout_end = q + limit;
+ return 1;
+}
+
+static const int stbi__zlength_base[31] = {
+ 3,4,5,6,7,8,9,10,11,13,
+ 15,17,19,23,27,31,35,43,51,59,
+ 67,83,99,115,131,163,195,227,258,0,0 };
+
+static const int stbi__zlength_extra[31]=
+{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
+
+static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
+257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
+
+static const int stbi__zdist_extra[32] =
+{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+static int stbi__parse_huffman_block(stbi__zbuf *a)
+{
+ char *zout = a->zout;
+ for(;;) {
+ int z = stbi__zhuffman_decode(a, &a->z_length);
+ if (z < 256) {
+ if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
+ if (zout >= a->zout_end) {
+ if (!stbi__zexpand(a, zout, 1)) return 0;
+ zout = a->zout;
+ }
+ *zout++ = (char) z;
+ } else {
+ stbi_uc *p;
+ int len,dist;
+ if (z == 256) {
+ a->zout = zout;
+ if (a->hit_zeof_once && a->num_bits < 16) {
+ // The first time we hit zeof, we inserted 16 extra zero bits into our bit
+ // buffer so the decoder can just do its speculative decoding. But if we
+ // actually consumed any of those bits (which is the case when num_bits < 16),
+ // the stream actually read past the end so it is malformed.
+ return stbi__err("unexpected end","Corrupt PNG");
+ }
+ return 1;
+ }
+ if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data
+ z -= 257;
+ len = stbi__zlength_base[z];
+ if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
+ z = stbi__zhuffman_decode(a, &a->z_distance);
+ if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data
+ dist = stbi__zdist_base[z];
+ if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
+ if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
+ if (len > a->zout_end - zout) {
+ if (!stbi__zexpand(a, zout, len)) return 0;
+ zout = a->zout;
+ }
+ p = (stbi_uc *) (zout - dist);
+ if (dist == 1) { // run of one byte; common in images.
+ stbi_uc v = *p;
+ if (len) { do *zout++ = v; while (--len); }
+ } else {
+ if (len) { do *zout++ = *p++; while (--len); }
+ }
+ }
+ }
+}
+
+static int stbi__compute_huffman_codes(stbi__zbuf *a)
+{
+ static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
+ stbi__zhuffman z_codelength;
+ stbi_uc lencodes[286+32+137];//padding for maximum single op
+ stbi_uc codelength_sizes[19];
+ int i,n;
+
+ int hlit = stbi__zreceive(a,5) + 257;
+ int hdist = stbi__zreceive(a,5) + 1;
+ int hclen = stbi__zreceive(a,4) + 4;
+ int ntot = hlit + hdist;
+
+ memset(codelength_sizes, 0, sizeof(codelength_sizes));
+ for (i=0; i < hclen; ++i) {
+ int s = stbi__zreceive(a,3);
+ codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
+ }
+ if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
+
+ n = 0;
+ while (n < ntot) {
+ int c = stbi__zhuffman_decode(a, &z_codelength);
+ if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
+ if (c < 16)
+ lencodes[n++] = (stbi_uc) c;
+ else {
+ stbi_uc fill = 0;
+ if (c == 16) {
+ c = stbi__zreceive(a,2)+3;
+ if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");
+ fill = lencodes[n-1];
+ } else if (c == 17) {
+ c = stbi__zreceive(a,3)+3;
+ } else if (c == 18) {
+ c = stbi__zreceive(a,7)+11;
+ } else {
+ return stbi__err("bad codelengths", "Corrupt PNG");
+ }
+ if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");
+ memset(lencodes+n, fill, c);
+ n += c;
+ }
+ }
+ if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG");
+ if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
+ return 1;
+}
+
+static int stbi__parse_uncompressed_block(stbi__zbuf *a)
+{
+ stbi_uc header[4];
+ int len,nlen,k;
+ if (a->num_bits & 7)
+ stbi__zreceive(a, a->num_bits & 7); // discard
+ // drain the bit-packed data into header
+ k = 0;
+ while (a->num_bits > 0) {
+ header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
+ a->code_buffer >>= 8;
+ a->num_bits -= 8;
+ }
+ if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG");
+ // now fill header the normal way
+ while (k < 4)
+ header[k++] = stbi__zget8(a);
+ len = header[1] * 256 + header[0];
+ nlen = header[3] * 256 + header[2];
+ if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
+ if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
+ if (a->zout + len > a->zout_end)
+ if (!stbi__zexpand(a, a->zout, len)) return 0;
+ memcpy(a->zout, a->zbuffer, len);
+ a->zbuffer += len;
+ a->zout += len;
+ return 1;
+}
+
+static int stbi__parse_zlib_header(stbi__zbuf *a)
+{
+ int cmf = stbi__zget8(a);
+ int cm = cmf & 15;
+ /* int cinfo = cmf >> 4; */
+ int flg = stbi__zget8(a);
+ if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
+ if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
+ if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
+ // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
+ return 1;
+}
+
+static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =
+{
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
+ 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8
+};
+static const stbi_uc stbi__zdefault_distance[32] =
+{
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5
+};
+/*
+Init algorithm:
+{
+ int i; // use <= to match clearly with spec
+ for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
+ for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
+ for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
+ for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
+
+ for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
+}
+*/
+
+static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
+{
+ int final, type;
+ if (parse_header)
+ if (!stbi__parse_zlib_header(a)) return 0;
+ a->num_bits = 0;
+ a->code_buffer = 0;
+ a->hit_zeof_once = 0;
+ do {
+ final = stbi__zreceive(a,1);
+ type = stbi__zreceive(a,2);
+ if (type == 0) {
+ if (!stbi__parse_uncompressed_block(a)) return 0;
+ } else if (type == 3) {
+ return 0;
+ } else {
+ if (type == 1) {
+ // use fixed code lengths
+ if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0;
+ if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
+ } else {
+ if (!stbi__compute_huffman_codes(a)) return 0;
+ }
+ if (!stbi__parse_huffman_block(a)) return 0;
+ }
+ } while (!final);
+ return 1;
+}
+
+static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
+{
+ a->zout_start = obuf;
+ a->zout = obuf;
+ a->zout_end = obuf + olen;
+ a->z_expandable = exp;
+
+ return stbi__parse_zlib(a, parse_header);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
+{
+ return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
+}
+
+STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(initial_size);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer + len;
+ if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+
+STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
+{
+ stbi__zbuf a;
+ char *p = (char *) stbi__malloc(16384);
+ if (p == NULL) return NULL;
+ a.zbuffer = (stbi_uc *) buffer;
+ a.zbuffer_end = (stbi_uc *) buffer+len;
+ if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
+ if (outlen) *outlen = (int) (a.zout - a.zout_start);
+ return a.zout_start;
+ } else {
+ STBI_FREE(a.zout_start);
+ return NULL;
+ }
+}
+
+STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
+{
+ stbi__zbuf a;
+ a.zbuffer = (stbi_uc *) ibuffer;
+ a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
+ if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
+ return (int) (a.zout - a.zout_start);
+ else
+ return -1;
+}
+#endif
+
+// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
+// simple implementation
+// - only 8-bit samples
+// - no CRC checking
+// - allocates lots of intermediate memory
+// - avoids problem of streaming data between subsystems
+// - avoids explicit window management
+// performance
+// - uses stb_zlib, a PD zlib implementation with fast huffman decoding
+
+#ifndef STBI_NO_PNG
+typedef struct
+{
+ stbi__uint32 length;
+ stbi__uint32 type;
+} stbi__pngchunk;
+
+static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
+{
+ stbi__pngchunk c;
+ c.length = stbi__get32be(s);
+ c.type = stbi__get32be(s);
+ return c;
+}
+
+static int stbi__check_png_header(stbi__context *s)
+{
+ static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
+ int i;
+ for (i=0; i < 8; ++i)
+ if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
+ return 1;
+}
+
+typedef struct
+{
+ stbi__context *s;
+ stbi_uc *idata, *expanded, *out;
+ int depth;
+} stbi__png;
+
+
+enum {
+ STBI__F_none=0,
+ STBI__F_sub=1,
+ STBI__F_up=2,
+ STBI__F_avg=3,
+ STBI__F_paeth=4,
+ // synthetic filter used for first scanline to avoid needing a dummy row of 0s
+ STBI__F_avg_first
+};
+
+static stbi_uc first_row_filter[5] =
+{
+ STBI__F_none,
+ STBI__F_sub,
+ STBI__F_none,
+ STBI__F_avg_first,
+ STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub
+};
+
+static int stbi__paeth(int a, int b, int c)
+{
+ // This formulation looks very different from the reference in the PNG spec, but is
+ // actually equivalent and has favorable data dependencies and admits straightforward
+ // generation of branch-free code, which helps performance significantly.
+ int thresh = c*3 - (a + b);
+ int lo = a < b ? a : b;
+ int hi = a < b ? b : a;
+ int t0 = (hi <= thresh) ? lo : c;
+ int t1 = (thresh <= lo) ? hi : t0;
+ return t1;
+}
+
+static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
+
+// adds an extra all-255 alpha channel
+// dest == src is legal
+// img_n must be 1 or 3
+static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n)
+{
+ int i;
+ // must process data backwards since we allow dest==src
+ if (img_n == 1) {
+ for (i=x-1; i >= 0; --i) {
+ dest[i*2+1] = 255;
+ dest[i*2+0] = src[i];
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i=x-1; i >= 0; --i) {
+ dest[i*4+3] = 255;
+ dest[i*4+2] = src[i*3+2];
+ dest[i*4+1] = src[i*3+1];
+ dest[i*4+0] = src[i*3+0];
+ }
+ }
+}
+
+// create the png data from post-deflated data
+static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ stbi__context *s = a->s;
+ stbi__uint32 i,j,stride = x*out_n*bytes;
+ stbi__uint32 img_len, img_width_bytes;
+ stbi_uc *filter_buf;
+ int all_ok = 1;
+ int k;
+ int img_n = s->img_n; // copy it into a local for later
+
+ int output_bytes = out_n*bytes;
+ int filter_bytes = img_n*bytes;
+ int width = x;
+
+ STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
+ a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into
+ if (!a->out) return stbi__err("outofmem", "Out of memory");
+
+ // note: error exits here don't need to clean up a->out individually,
+ // stbi__do_png always does on error.
+ if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG");
+ img_width_bytes = (((img_n * x * depth) + 7) >> 3);
+ if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG");
+ img_len = (img_width_bytes + 1) * y;
+
+ // we used to check for exact match between raw_len and img_len on non-interlaced PNGs,
+ // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros),
+ // so just check for raw_len < img_len always.
+ if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
+
+ // Allocate two scan lines worth of filter workspace buffer.
+ filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0);
+ if (!filter_buf) return stbi__err("outofmem", "Out of memory");
+
+ // Filtering for low-bit-depth images
+ if (depth < 8) {
+ filter_bytes = 1;
+ width = img_width_bytes;
+ }
+
+ for (j=0; j < y; ++j) {
+ // cur/prior filter buffers alternate
+ stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes;
+ stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes;
+ stbi_uc *dest = a->out + stride*j;
+ int nk = width * filter_bytes;
+ int filter = *raw++;
+
+ // check filter type
+ if (filter > 4) {
+ all_ok = stbi__err("invalid filter","Corrupt PNG");
+ break;
+ }
+
+ // if first row, use special filter that doesn't sample previous row
+ if (j == 0) filter = first_row_filter[filter];
+
+ // perform actual filtering
+ switch (filter) {
+ case STBI__F_none:
+ memcpy(cur, raw, nk);
+ break;
+ case STBI__F_sub:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]);
+ break;
+ case STBI__F_up:
+ for (k = 0; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]);
+ break;
+ case STBI__F_avg:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1));
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1));
+ break;
+ case STBI__F_paeth:
+ for (k = 0; k < filter_bytes; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0)
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes]));
+ break;
+ case STBI__F_avg_first:
+ memcpy(cur, raw, filter_bytes);
+ for (k = filter_bytes; k < nk; ++k)
+ cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1));
+ break;
+ }
+
+ raw += nk;
+
+ // expand decoded bits in cur to dest, also adding an extra alpha channel if desired
+ if (depth < 8) {
+ stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
+ stbi_uc *in = cur;
+ stbi_uc *out = dest;
+ stbi_uc inb = 0;
+ stbi__uint32 nsmp = x*img_n;
+
+ // expand bits to bytes first
+ if (depth == 4) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 1) == 0) inb = *in++;
+ *out++ = scale * (inb >> 4);
+ inb <<= 4;
+ }
+ } else if (depth == 2) {
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 3) == 0) inb = *in++;
+ *out++ = scale * (inb >> 6);
+ inb <<= 2;
+ }
+ } else {
+ STBI_ASSERT(depth == 1);
+ for (i=0; i < nsmp; ++i) {
+ if ((i & 7) == 0) inb = *in++;
+ *out++ = scale * (inb >> 7);
+ inb <<= 1;
+ }
+ }
+
+ // insert alpha=255 values if desired
+ if (img_n != out_n)
+ stbi__create_png_alpha_expand8(dest, dest, x, img_n);
+ } else if (depth == 8) {
+ if (img_n == out_n)
+ memcpy(dest, cur, x*img_n);
+ else
+ stbi__create_png_alpha_expand8(dest, cur, x, img_n);
+ } else if (depth == 16) {
+ // convert the image data from big-endian to platform-native
+ stbi__uint16 *dest16 = (stbi__uint16*)dest;
+ stbi__uint32 nsmp = x*img_n;
+
+ if (img_n == out_n) {
+ for (i = 0; i < nsmp; ++i, ++dest16, cur += 2)
+ *dest16 = (cur[0] << 8) | cur[1];
+ } else {
+ STBI_ASSERT(img_n+1 == out_n);
+ if (img_n == 1) {
+ for (i = 0; i < x; ++i, dest16 += 2, cur += 2) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = 0xffff;
+ }
+ } else {
+ STBI_ASSERT(img_n == 3);
+ for (i = 0; i < x; ++i, dest16 += 4, cur += 6) {
+ dest16[0] = (cur[0] << 8) | cur[1];
+ dest16[1] = (cur[2] << 8) | cur[3];
+ dest16[2] = (cur[4] << 8) | cur[5];
+ dest16[3] = 0xffff;
+ }
+ }
+ }
+ }
+ }
+
+ STBI_FREE(filter_buf);
+ if (!all_ok) return 0;
+
+ return 1;
+}
+
+static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
+{
+ int bytes = (depth == 16 ? 2 : 1);
+ int out_bytes = out_n * bytes;
+ stbi_uc *final;
+ int p;
+ if (!interlaced)
+ return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
+
+ // de-interlacing
+ final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);
+ if (!final) return stbi__err("outofmem", "Out of memory");
+ for (p=0; p < 7; ++p) {
+ int xorig[] = { 0,4,0,2,0,1,0 };
+ int yorig[] = { 0,0,4,0,2,0,1 };
+ int xspc[] = { 8,8,4,4,2,2,1 };
+ int yspc[] = { 8,8,8,4,4,2,2 };
+ int i,j,x,y;
+ // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
+ x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
+ y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
+ if (x && y) {
+ stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
+ if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
+ STBI_FREE(final);
+ return 0;
+ }
+ for (j=0; j < y; ++j) {
+ for (i=0; i < x; ++i) {
+ int out_y = j*yspc[p]+yorig[p];
+ int out_x = i*xspc[p]+xorig[p];
+ memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,
+ a->out + (j*x+i)*out_bytes, out_bytes);
+ }
+ }
+ STBI_FREE(a->out);
+ image_data += img_len;
+ image_data_len -= img_len;
+ }
+ }
+ a->out = final;
+
+ return 1;
+}
+
+static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 255 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i=0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 255);
+ p += 2;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi__uint16 *p = (stbi__uint16*) z->out;
+
+ // compute color-based transparency, assuming we've
+ // already got 65535 as the alpha value in the output
+ STBI_ASSERT(out_n == 2 || out_n == 4);
+
+ if (out_n == 2) {
+ for (i = 0; i < pixel_count; ++i) {
+ p[1] = (p[0] == tc[0] ? 0 : 65535);
+ p += 2;
+ }
+ } else {
+ for (i = 0; i < pixel_count; ++i) {
+ if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
+ p[3] = 0;
+ p += 4;
+ }
+ }
+ return 1;
+}
+
+static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
+{
+ stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
+ stbi_uc *p, *temp_out, *orig = a->out;
+
+ p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);
+ if (p == NULL) return stbi__err("outofmem", "Out of memory");
+
+ // between here and free(out) below, exitting would leak
+ temp_out = p;
+
+ if (pal_img_n == 3) {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p += 3;
+ }
+ } else {
+ for (i=0; i < pixel_count; ++i) {
+ int n = orig[i]*4;
+ p[0] = palette[n ];
+ p[1] = palette[n+1];
+ p[2] = palette[n+2];
+ p[3] = palette[n+3];
+ p += 4;
+ }
+ }
+ STBI_FREE(a->out);
+ a->out = temp_out;
+
+ STBI_NOTUSED(len);
+
+ return 1;
+}
+
+static int stbi__unpremultiply_on_load_global = 0;
+static int stbi__de_iphone_flag_global = 0;
+
+STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_global = flag_true_if_should_convert;
+}
+
+#ifndef STBI_THREAD_LOCAL
+#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global
+#define stbi__de_iphone_flag stbi__de_iphone_flag_global
+#else
+static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set;
+static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set;
+
+STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply)
+{
+ stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply;
+ stbi__unpremultiply_on_load_set = 1;
+}
+
+STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert)
+{
+ stbi__de_iphone_flag_local = flag_true_if_should_convert;
+ stbi__de_iphone_flag_set = 1;
+}
+
+#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \
+ ? stbi__unpremultiply_on_load_local \
+ : stbi__unpremultiply_on_load_global)
+#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \
+ ? stbi__de_iphone_flag_local \
+ : stbi__de_iphone_flag_global)
+#endif // STBI_THREAD_LOCAL
+
+static void stbi__de_iphone(stbi__png *z)
+{
+ stbi__context *s = z->s;
+ stbi__uint32 i, pixel_count = s->img_x * s->img_y;
+ stbi_uc *p = z->out;
+
+ if (s->img_out_n == 3) { // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 3;
+ }
+ } else {
+ STBI_ASSERT(s->img_out_n == 4);
+ if (stbi__unpremultiply_on_load) {
+ // convert bgr to rgb and unpremultiply
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc a = p[3];
+ stbi_uc t = p[0];
+ if (a) {
+ stbi_uc half = a / 2;
+ p[0] = (p[2] * 255 + half) / a;
+ p[1] = (p[1] * 255 + half) / a;
+ p[2] = ( t * 255 + half) / a;
+ } else {
+ p[0] = p[2];
+ p[2] = t;
+ }
+ p += 4;
+ }
+ } else {
+ // convert bgr to rgb
+ for (i=0; i < pixel_count; ++i) {
+ stbi_uc t = p[0];
+ p[0] = p[2];
+ p[2] = t;
+ p += 4;
+ }
+ }
+ }
+}
+
+#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d))
+
+static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
+{
+ stbi_uc palette[1024], pal_img_n=0;
+ stbi_uc has_trans=0, tc[3]={0};
+ stbi__uint16 tc16[3];
+ stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
+ int first=1,k,interlace=0, color=0, is_iphone=0;
+ stbi__context *s = z->s;
+
+ z->expanded = NULL;
+ z->idata = NULL;
+ z->out = NULL;
+
+ if (!stbi__check_png_header(s)) return 0;
+
+ if (scan == STBI__SCAN_type) return 1;
+
+ for (;;) {
+ stbi__pngchunk c = stbi__get_chunk_header(s);
+ switch (c.type) {
+ case STBI__PNG_TYPE('C','g','B','I'):
+ is_iphone = 1;
+ stbi__skip(s, c.length);
+ break;
+ case STBI__PNG_TYPE('I','H','D','R'): {
+ int comp,filter;
+ if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
+ first = 0;
+ if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
+ s->img_x = stbi__get32be(s);
+ s->img_y = stbi__get32be(s);
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only");
+ color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG");
+ if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
+ comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
+ filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
+ interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
+ if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
+ if (!pal_img_n) {
+ s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
+ if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
+ } else {
+ // if paletted, then pal_n is our final components, and
+ // img_n is # components to decompress/filter.
+ s->img_n = 1;
+ if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
+ }
+ // even with SCAN_header, have to scan to see if we have a tRNS
+ break;
+ }
+
+ case STBI__PNG_TYPE('P','L','T','E'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
+ pal_len = c.length / 3;
+ if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
+ for (i=0; i < pal_len; ++i) {
+ palette[i*4+0] = stbi__get8(s);
+ palette[i*4+1] = stbi__get8(s);
+ palette[i*4+2] = stbi__get8(s);
+ palette[i*4+3] = 255;
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('t','R','N','S'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
+ if (pal_img_n) {
+ if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
+ if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
+ if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
+ pal_img_n = 4;
+ for (i=0; i < c.length; ++i)
+ palette[i*4+3] = stbi__get8(s);
+ } else {
+ if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
+ if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
+ has_trans = 1;
+ // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now.
+ if (scan == STBI__SCAN_header) { ++s->img_n; return 1; }
+ if (z->depth == 16) {
+ for (k = 0; k < s->img_n && k < 3; ++k) // extra loop test to suppress false GCC warning
+ tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is
+ } else {
+ for (k = 0; k < s->img_n && k < 3; ++k)
+ tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger
+ }
+ }
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','D','A','T'): {
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
+ if (scan == STBI__SCAN_header) {
+ // header scan definitely stops at first IDAT
+ if (pal_img_n)
+ s->img_n = pal_img_n;
+ return 1;
+ }
+ if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes");
+ if ((int)(ioff + c.length) < (int)ioff) return 0;
+ if (ioff + c.length > idata_limit) {
+ stbi__uint32 idata_limit_old = idata_limit;
+ stbi_uc *p;
+ if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
+ while (ioff + c.length > idata_limit)
+ idata_limit *= 2;
+ STBI_NOTUSED(idata_limit_old);
+ p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
+ z->idata = p;
+ }
+ if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
+ ioff += c.length;
+ break;
+ }
+
+ case STBI__PNG_TYPE('I','E','N','D'): {
+ stbi__uint32 raw_len, bpl;
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if (scan != STBI__SCAN_load) return 1;
+ if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
+ // initial guess for decoded data size to avoid unnecessary reallocs
+ bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component
+ raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
+ z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
+ if (z->expanded == NULL) return 0; // zlib should set error
+ STBI_FREE(z->idata); z->idata = NULL;
+ if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
+ s->img_out_n = s->img_n+1;
+ else
+ s->img_out_n = s->img_n;
+ if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0;
+ if (has_trans) {
+ if (z->depth == 16) {
+ if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0;
+ } else {
+ if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
+ }
+ }
+ if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
+ stbi__de_iphone(z);
+ if (pal_img_n) {
+ // pal_img_n == 3 or 4
+ s->img_n = pal_img_n; // record the actual colors we had
+ s->img_out_n = pal_img_n;
+ if (req_comp >= 3) s->img_out_n = req_comp;
+ if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
+ return 0;
+ } else if (has_trans) {
+ // non-paletted image with tRNS -> source image has (constant) alpha
+ ++s->img_n;
+ }
+ STBI_FREE(z->expanded); z->expanded = NULL;
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ return 1;
+ }
+
+ default:
+ // if critical, fail
+ if (first) return stbi__err("first not IHDR", "Corrupt PNG");
+ if ((c.type & (1 << 29)) == 0) {
+ #ifndef STBI_NO_FAILURE_STRINGS
+ // not threadsafe
+ static char invalid_chunk[] = "XXXX PNG chunk not known";
+ invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
+ invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
+ invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
+ invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
+ #endif
+ return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
+ }
+ stbi__skip(s, c.length);
+ break;
+ }
+ // end of PNG chunk, read and skip CRC
+ stbi__get32be(s);
+ }
+}
+
+static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)
+{
+ void *result=NULL;
+ if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
+ if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
+ if (p->depth <= 8)
+ ri->bits_per_channel = 8;
+ else if (p->depth == 16)
+ ri->bits_per_channel = 16;
+ else
+ return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth");
+ result = p->out;
+ p->out = NULL;
+ if (req_comp && req_comp != p->s->img_out_n) {
+ if (ri->bits_per_channel == 8)
+ result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ else
+ result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
+ p->s->img_out_n = req_comp;
+ if (result == NULL) return result;
+ }
+ *x = p->s->img_x;
+ *y = p->s->img_y;
+ if (n) *n = p->s->img_n;
+ }
+ STBI_FREE(p->out); p->out = NULL;
+ STBI_FREE(p->expanded); p->expanded = NULL;
+ STBI_FREE(p->idata); p->idata = NULL;
+
+ return result;
+}
+
+static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__do_png(&p, x,y,comp,req_comp, ri);
+}
+
+static int stbi__png_test(stbi__context *s)
+{
+ int r;
+ r = stbi__check_png_header(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
+{
+ if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
+ stbi__rewind( p->s );
+ return 0;
+ }
+ if (x) *x = p->s->img_x;
+ if (y) *y = p->s->img_y;
+ if (comp) *comp = p->s->img_n;
+ return 1;
+}
+
+static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__png p;
+ p.s = s;
+ return stbi__png_info_raw(&p, x, y, comp);
+}
+
+static int stbi__png_is16(stbi__context *s)
+{
+ stbi__png p;
+ p.s = s;
+ if (!stbi__png_info_raw(&p, NULL, NULL, NULL))
+ return 0;
+ if (p.depth != 16) {
+ stbi__rewind(p.s);
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+// Microsoft/Windows BMP image
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_test_raw(stbi__context *s)
+{
+ int r;
+ int sz;
+ if (stbi__get8(s) != 'B') return 0;
+ if (stbi__get8(s) != 'M') return 0;
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ stbi__get32le(s); // discard data offset
+ sz = stbi__get32le(s);
+ r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
+ return r;
+}
+
+static int stbi__bmp_test(stbi__context *s)
+{
+ int r = stbi__bmp_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+
+// returns 0..31 for the highest set bit
+static int stbi__high_bit(unsigned int z)
+{
+ int n=0;
+ if (z == 0) return -1;
+ if (z >= 0x10000) { n += 16; z >>= 16; }
+ if (z >= 0x00100) { n += 8; z >>= 8; }
+ if (z >= 0x00010) { n += 4; z >>= 4; }
+ if (z >= 0x00004) { n += 2; z >>= 2; }
+ if (z >= 0x00002) { n += 1;/* >>= 1;*/ }
+ return n;
+}
+
+static int stbi__bitcount(unsigned int a)
+{
+ a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
+ a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
+ a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
+ a = (a + (a >> 8)); // max 16 per 8 bits
+ a = (a + (a >> 16)); // max 32 per 8 bits
+ return a & 0xff;
+}
+
+// extract an arbitrarily-aligned N-bit value (N=bits)
+// from v, and then make it 8-bits long and fractionally
+// extend it to full full range.
+static int stbi__shiftsigned(unsigned int v, int shift, int bits)
+{
+ static unsigned int mul_table[9] = {
+ 0,
+ 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/,
+ 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/,
+ };
+ static unsigned int shift_table[9] = {
+ 0, 0,0,1,0,2,4,6,0,
+ };
+ if (shift < 0)
+ v <<= -shift;
+ else
+ v >>= shift;
+ STBI_ASSERT(v < 256);
+ v >>= (8-bits);
+ STBI_ASSERT(bits >= 0 && bits <= 8);
+ return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits];
+}
+
+typedef struct
+{
+ int bpp, offset, hsz;
+ unsigned int mr,mg,mb,ma, all_a;
+ int extra_read;
+} stbi__bmp_data;
+
+static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress)
+{
+ // BI_BITFIELDS specifies masks explicitly, don't override
+ if (compress == 3)
+ return 1;
+
+ if (compress == 0) {
+ if (info->bpp == 16) {
+ info->mr = 31u << 10;
+ info->mg = 31u << 5;
+ info->mb = 31u << 0;
+ } else if (info->bpp == 32) {
+ info->mr = 0xffu << 16;
+ info->mg = 0xffu << 8;
+ info->mb = 0xffu << 0;
+ info->ma = 0xffu << 24;
+ info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0
+ } else {
+ // otherwise, use defaults, which is all-0
+ info->mr = info->mg = info->mb = info->ma = 0;
+ }
+ return 1;
+ }
+ return 0; // error
+}
+
+static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info)
+{
+ int hsz;
+ if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
+ stbi__get32le(s); // discard filesize
+ stbi__get16le(s); // discard reserved
+ stbi__get16le(s); // discard reserved
+ info->offset = stbi__get32le(s);
+ info->hsz = hsz = stbi__get32le(s);
+ info->mr = info->mg = info->mb = info->ma = 0;
+ info->extra_read = 14;
+
+ if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP");
+
+ if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
+ if (hsz == 12) {
+ s->img_x = stbi__get16le(s);
+ s->img_y = stbi__get16le(s);
+ } else {
+ s->img_x = stbi__get32le(s);
+ s->img_y = stbi__get32le(s);
+ }
+ if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
+ info->bpp = stbi__get16le(s);
+ if (hsz != 12) {
+ int compress = stbi__get32le(s);
+ if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
+ if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes
+ if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel
+ stbi__get32le(s); // discard sizeof
+ stbi__get32le(s); // discard hres
+ stbi__get32le(s); // discard vres
+ stbi__get32le(s); // discard colorsused
+ stbi__get32le(s); // discard max important
+ if (hsz == 40 || hsz == 56) {
+ if (hsz == 56) {
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ stbi__get32le(s);
+ }
+ if (info->bpp == 16 || info->bpp == 32) {
+ if (compress == 0) {
+ stbi__bmp_set_mask_defaults(info, compress);
+ } else if (compress == 3) {
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->extra_read += 12;
+ // not documented, but generated by photoshop and handled by mspaint
+ if (info->mr == info->mg && info->mg == info->mb) {
+ // ?!?!?
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else
+ return stbi__errpuc("bad BMP", "bad BMP");
+ }
+ } else {
+ // V4/V5 header
+ int i;
+ if (hsz != 108 && hsz != 124)
+ return stbi__errpuc("bad BMP", "bad BMP");
+ info->mr = stbi__get32le(s);
+ info->mg = stbi__get32le(s);
+ info->mb = stbi__get32le(s);
+ info->ma = stbi__get32le(s);
+ if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs
+ stbi__bmp_set_mask_defaults(info, compress);
+ stbi__get32le(s); // discard color space
+ for (i=0; i < 12; ++i)
+ stbi__get32le(s); // discard color space parameters
+ if (hsz == 124) {
+ stbi__get32le(s); // discard rendering intent
+ stbi__get32le(s); // discard offset of profile data
+ stbi__get32le(s); // discard size of profile data
+ stbi__get32le(s); // discard reserved
+ }
+ }
+ }
+ return (void *) 1;
+}
+
+
+static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ unsigned int mr=0,mg=0,mb=0,ma=0, all_a;
+ stbi_uc pal[256][4];
+ int psize=0,i,j,width;
+ int flip_vertically, pad, target;
+ stbi__bmp_data info;
+ STBI_NOTUSED(ri);
+
+ info.all_a = 255;
+ if (stbi__bmp_parse_header(s, &info) == NULL)
+ return NULL; // error code already set
+
+ flip_vertically = ((int) s->img_y) > 0;
+ s->img_y = abs((int) s->img_y);
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ mr = info.mr;
+ mg = info.mg;
+ mb = info.mb;
+ ma = info.ma;
+ all_a = info.all_a;
+
+ if (info.hsz == 12) {
+ if (info.bpp < 24)
+ psize = (info.offset - info.extra_read - 24) / 3;
+ } else {
+ if (info.bpp < 16)
+ psize = (info.offset - info.extra_read - info.hsz) >> 2;
+ }
+ if (psize == 0) {
+ // accept some number of extra bytes after the header, but if the offset points either to before
+ // the header ends or implies a large amount of extra data, reject the file as malformed
+ int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original);
+ int header_limit = 1024; // max we actually read is below 256 bytes currently.
+ int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size.
+ if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) {
+ return stbi__errpuc("bad header", "Corrupt BMP");
+ }
+ // we established that bytes_read_so_far is positive and sensible.
+ // the first half of this test rejects offsets that are either too small positives, or
+ // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn
+ // ensures the number computed in the second half of the test can't overflow.
+ if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) {
+ return stbi__errpuc("bad offset", "Corrupt BMP");
+ } else {
+ stbi__skip(s, info.offset - bytes_read_so_far);
+ }
+ }
+
+ if (info.bpp == 24 && ma == 0xff000000)
+ s->img_n = 3;
+ else
+ s->img_n = ma ? 4 : 3;
+ if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
+ target = req_comp;
+ else
+ target = s->img_n; // if they want monochrome, we'll post-convert
+
+ // sanity-check size
+ if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))
+ return stbi__errpuc("too large", "Corrupt BMP");
+
+ out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (info.bpp < 16) {
+ int z=0;
+ if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
+ for (i=0; i < psize; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ if (info.hsz != 12) stbi__get8(s);
+ pal[i][3] = 255;
+ }
+ stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4));
+ if (info.bpp == 1) width = (s->img_x + 7) >> 3;
+ else if (info.bpp == 4) width = (s->img_x + 1) >> 1;
+ else if (info.bpp == 8) width = s->img_x;
+ else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
+ pad = (-width)&3;
+ if (info.bpp == 1) {
+ for (j=0; j < (int) s->img_y; ++j) {
+ int bit_offset = 7, v = stbi__get8(s);
+ for (i=0; i < (int) s->img_x; ++i) {
+ int color = (v>>bit_offset)&0x1;
+ out[z++] = pal[color][0];
+ out[z++] = pal[color][1];
+ out[z++] = pal[color][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ if((--bit_offset) < 0) {
+ bit_offset = 7;
+ v = stbi__get8(s);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ } else {
+ for (j=0; j < (int) s->img_y; ++j) {
+ for (i=0; i < (int) s->img_x; i += 2) {
+ int v=stbi__get8(s),v2=0;
+ if (info.bpp == 4) {
+ v2 = v & 15;
+ v >>= 4;
+ }
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ if (i+1 == (int) s->img_x) break;
+ v = (info.bpp == 8) ? stbi__get8(s) : v2;
+ out[z++] = pal[v][0];
+ out[z++] = pal[v][1];
+ out[z++] = pal[v][2];
+ if (target == 4) out[z++] = 255;
+ }
+ stbi__skip(s, pad);
+ }
+ }
+ } else {
+ int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
+ int z = 0;
+ int easy=0;
+ stbi__skip(s, info.offset - info.extra_read - info.hsz);
+ if (info.bpp == 24) width = 3 * s->img_x;
+ else if (info.bpp == 16) width = 2*s->img_x;
+ else /* bpp = 32 and pad = 0 */ width=0;
+ pad = (-width) & 3;
+ if (info.bpp == 24) {
+ easy = 1;
+ } else if (info.bpp == 32) {
+ if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
+ easy = 2;
+ }
+ if (!easy) {
+ if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ // right shift amt to put high bit in position #7
+ rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
+ gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
+ bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
+ ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
+ if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
+ }
+ for (j=0; j < (int) s->img_y; ++j) {
+ if (easy) {
+ for (i=0; i < (int) s->img_x; ++i) {
+ unsigned char a;
+ out[z+2] = stbi__get8(s);
+ out[z+1] = stbi__get8(s);
+ out[z+0] = stbi__get8(s);
+ z += 3;
+ a = (easy == 2 ? stbi__get8(s) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = a;
+ }
+ } else {
+ int bpp = info.bpp;
+ for (i=0; i < (int) s->img_x; ++i) {
+ stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
+ unsigned int a;
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
+ out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
+ a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
+ all_a |= a;
+ if (target == 4) out[z++] = STBI__BYTECAST(a);
+ }
+ }
+ stbi__skip(s, pad);
+ }
+ }
+
+ // if alpha channel is all 0s, replace with all 255s
+ if (target == 4 && all_a == 0)
+ for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4)
+ out[i] = 255;
+
+ if (flip_vertically) {
+ stbi_uc t;
+ for (j=0; j < (int) s->img_y>>1; ++j) {
+ stbi_uc *p1 = out + j *s->img_x*target;
+ stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
+ for (i=0; i < (int) s->img_x*target; ++i) {
+ t = p1[i]; p1[i] = p2[i]; p2[i] = t;
+ }
+ }
+ }
+
+ if (req_comp && req_comp != target) {
+ out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+ return out;
+}
+#endif
+
+// Targa Truevision - TGA
+// by Jonathan Dummer
+#ifndef STBI_NO_TGA
+// returns STBI_rgb or whatever, 0 on error
+static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16)
+{
+ // only RGB or RGBA (incl. 16bit) or grey allowed
+ if (is_rgb16) *is_rgb16 = 0;
+ switch(bits_per_pixel) {
+ case 8: return STBI_grey;
+ case 16: if(is_grey) return STBI_grey_alpha;
+ // fallthrough
+ case 15: if(is_rgb16) *is_rgb16 = 1;
+ return STBI_rgb;
+ case 24: // fallthrough
+ case 32: return bits_per_pixel/8;
+ default: return 0;
+ }
+}
+
+static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp;
+ int sz, tga_colormap_type;
+ stbi__get8(s); // discard Offset
+ tga_colormap_type = stbi__get8(s); // colormap type
+ if( tga_colormap_type > 1 ) {
+ stbi__rewind(s);
+ return 0; // only RGB or indexed allowed
+ }
+ tga_image_type = stbi__get8(s); // image type
+ if ( tga_colormap_type == 1 ) { // colormapped (paletted) image
+ if (tga_image_type != 1 && tga_image_type != 9) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) {
+ stbi__rewind(s);
+ return 0;
+ }
+ stbi__skip(s,4); // skip image x and y origin
+ tga_colormap_bpp = sz;
+ } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE
+ if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) {
+ stbi__rewind(s);
+ return 0; // only RGB or grey allowed, +/- RLE
+ }
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ tga_colormap_bpp = 0;
+ }
+ tga_w = stbi__get16le(s);
+ if( tga_w < 1 ) {
+ stbi__rewind(s);
+ return 0; // test width
+ }
+ tga_h = stbi__get16le(s);
+ if( tga_h < 1 ) {
+ stbi__rewind(s);
+ return 0; // test height
+ }
+ tga_bits_per_pixel = stbi__get8(s); // bits per pixel
+ stbi__get8(s); // ignore alpha bits
+ if (tga_colormap_bpp != 0) {
+ if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) {
+ // when using a colormap, tga_bits_per_pixel is the size of the indexes
+ // I don't think anything but 8 or 16bit indexes makes sense
+ stbi__rewind(s);
+ return 0;
+ }
+ tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL);
+ } else {
+ tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL);
+ }
+ if(!tga_comp) {
+ stbi__rewind(s);
+ return 0;
+ }
+ if (x) *x = tga_w;
+ if (y) *y = tga_h;
+ if (comp) *comp = tga_comp;
+ return 1; // seems to have passed everything
+}
+
+static int stbi__tga_test(stbi__context *s)
+{
+ int res = 0;
+ int sz, tga_color_type;
+ stbi__get8(s); // discard Offset
+ tga_color_type = stbi__get8(s); // color type
+ if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed
+ sz = stbi__get8(s); // image type
+ if ( tga_color_type == 1 ) { // colormapped (paletted) image
+ if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9
+ stbi__skip(s,4); // skip index of first colormap entry and number of entries
+ sz = stbi__get8(s); // check bits per palette color entry
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+ stbi__skip(s,4); // skip image x and y origin
+ } else { // "normal" image w/o colormap
+ if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE
+ stbi__skip(s,9); // skip colormap specification and image x/y origin
+ }
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width
+ if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height
+ sz = stbi__get8(s); // bits per pixel
+ if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index
+ if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd;
+
+ res = 1; // if we got this far, everything's good and we can return 1 instead of 0
+
+errorEnd:
+ stbi__rewind(s);
+ return res;
+}
+
+// read 16bit value and convert to 24bit RGB
+static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)
+{
+ stbi__uint16 px = (stbi__uint16)stbi__get16le(s);
+ stbi__uint16 fiveBitMask = 31;
+ // we have 3 channels with 5bits each
+ int r = (px >> 10) & fiveBitMask;
+ int g = (px >> 5) & fiveBitMask;
+ int b = px & fiveBitMask;
+ // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later
+ out[0] = (stbi_uc)((r * 255)/31);
+ out[1] = (stbi_uc)((g * 255)/31);
+ out[2] = (stbi_uc)((b * 255)/31);
+
+ // some people claim that the most significant bit might be used for alpha
+ // (possibly if an alpha-bit is set in the "image descriptor byte")
+ // but that only made 16bit test images completely translucent..
+ // so let's treat all 15 and 16bit TGAs as RGB with no alpha.
+}
+
+static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ // read in the TGA header stuff
+ int tga_offset = stbi__get8(s);
+ int tga_indexed = stbi__get8(s);
+ int tga_image_type = stbi__get8(s);
+ int tga_is_RLE = 0;
+ int tga_palette_start = stbi__get16le(s);
+ int tga_palette_len = stbi__get16le(s);
+ int tga_palette_bits = stbi__get8(s);
+ int tga_x_origin = stbi__get16le(s);
+ int tga_y_origin = stbi__get16le(s);
+ int tga_width = stbi__get16le(s);
+ int tga_height = stbi__get16le(s);
+ int tga_bits_per_pixel = stbi__get8(s);
+ int tga_comp, tga_rgb16=0;
+ int tga_inverted = stbi__get8(s);
+ // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?)
+ // image data
+ unsigned char *tga_data;
+ unsigned char *tga_palette = NULL;
+ int i, j;
+ unsigned char raw_data[4] = {0};
+ int RLE_count = 0;
+ int RLE_repeating = 0;
+ int read_next_pixel = 1;
+ STBI_NOTUSED(ri);
+ STBI_NOTUSED(tga_x_origin); // @TODO
+ STBI_NOTUSED(tga_y_origin); // @TODO
+
+ if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // do a tiny bit of precessing
+ if ( tga_image_type >= 8 )
+ {
+ tga_image_type -= 8;
+ tga_is_RLE = 1;
+ }
+ tga_inverted = 1 - ((tga_inverted >> 5) & 1);
+
+ // If I'm paletted, then I'll use the number of bits from the palette
+ if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16);
+ else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16);
+
+ if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency
+ return stbi__errpuc("bad format", "Can't find out TGA pixelformat");
+
+ // tga info
+ *x = tga_width;
+ *y = tga_height;
+ if (comp) *comp = tga_comp;
+
+ if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))
+ return stbi__errpuc("too large", "Corrupt TGA");
+
+ tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);
+ if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
+
+ // skip to the data's starting position (offset usually = 0)
+ stbi__skip(s, tga_offset );
+
+ if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) {
+ for (i=0; i < tga_height; ++i) {
+ int row = tga_inverted ? tga_height -i - 1 : i;
+ stbi_uc *tga_row = tga_data + row*tga_width*tga_comp;
+ stbi__getn(s, tga_row, tga_width * tga_comp);
+ }
+ } else {
+ // do I need to load a palette?
+ if ( tga_indexed)
+ {
+ if (tga_palette_len == 0) { /* you have to have at least one entry! */
+ STBI_FREE(tga_data);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+
+ // any data to skip? (offset usually = 0)
+ stbi__skip(s, tga_palette_start );
+ // load the palette
+ tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);
+ if (!tga_palette) {
+ STBI_FREE(tga_data);
+ return stbi__errpuc("outofmem", "Out of memory");
+ }
+ if (tga_rgb16) {
+ stbi_uc *pal_entry = tga_palette;
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ for (i=0; i < tga_palette_len; ++i) {
+ stbi__tga_read_rgb16(s, pal_entry);
+ pal_entry += tga_comp;
+ }
+ } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) {
+ STBI_FREE(tga_data);
+ STBI_FREE(tga_palette);
+ return stbi__errpuc("bad palette", "Corrupt TGA");
+ }
+ }
+ // load the data
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
+ if ( tga_is_RLE )
+ {
+ if ( RLE_count == 0 )
+ {
+ // yep, get the next byte as a RLE command
+ int RLE_cmd = stbi__get8(s);
+ RLE_count = 1 + (RLE_cmd & 127);
+ RLE_repeating = RLE_cmd >> 7;
+ read_next_pixel = 1;
+ } else if ( !RLE_repeating )
+ {
+ read_next_pixel = 1;
+ }
+ } else
+ {
+ read_next_pixel = 1;
+ }
+ // OK, if I need to read a pixel, do it now
+ if ( read_next_pixel )
+ {
+ // load however much data we did have
+ if ( tga_indexed )
+ {
+ // read in index, then perform the lookup
+ int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s);
+ if ( pal_idx >= tga_palette_len ) {
+ // invalid index
+ pal_idx = 0;
+ }
+ pal_idx *= tga_comp;
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = tga_palette[pal_idx+j];
+ }
+ } else if(tga_rgb16) {
+ STBI_ASSERT(tga_comp == STBI_rgb);
+ stbi__tga_read_rgb16(s, raw_data);
+ } else {
+ // read in the data raw
+ for (j = 0; j < tga_comp; ++j) {
+ raw_data[j] = stbi__get8(s);
+ }
+ }
+ // clear the reading flag for the next pixel
+ read_next_pixel = 0;
+ } // end of reading a pixel
+
+ // copy data
+ for (j = 0; j < tga_comp; ++j)
+ tga_data[i*tga_comp+j] = raw_data[j];
+
+ // in case we're in RLE mode, keep counting down
+ --RLE_count;
+ }
+ // do I need to invert the image?
+ if ( tga_inverted )
+ {
+ for (j = 0; j*2 < tga_height; ++j)
+ {
+ int index1 = j * tga_width * tga_comp;
+ int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
+ for (i = tga_width * tga_comp; i > 0; --i)
+ {
+ unsigned char temp = tga_data[index1];
+ tga_data[index1] = tga_data[index2];
+ tga_data[index2] = temp;
+ ++index1;
+ ++index2;
+ }
+ }
+ }
+ // clear my palette, if I had one
+ if ( tga_palette != NULL )
+ {
+ STBI_FREE( tga_palette );
+ }
+ }
+
+ // swap RGB - if the source data was RGB16, it already is in the right order
+ if (tga_comp >= 3 && !tga_rgb16)
+ {
+ unsigned char* tga_pixel = tga_data;
+ for (i=0; i < tga_width * tga_height; ++i)
+ {
+ unsigned char temp = tga_pixel[0];
+ tga_pixel[0] = tga_pixel[2];
+ tga_pixel[2] = temp;
+ tga_pixel += tga_comp;
+ }
+ }
+
+ // convert to target component count
+ if (req_comp && req_comp != tga_comp)
+ tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
+
+ // the things I do to get rid of an error message, and yet keep
+ // Microsoft's C compilers happy... [8^(
+ tga_palette_start = tga_palette_len = tga_palette_bits =
+ tga_x_origin = tga_y_origin = 0;
+ STBI_NOTUSED(tga_palette_start);
+ // OK, done
+ return tga_data;
+}
+#endif
+
+// *************************************************************************************************
+// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_test(stbi__context *s)
+{
+ int r = (stbi__get32be(s) == 0x38425053);
+ stbi__rewind(s);
+ return r;
+}
+
+static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount)
+{
+ int count, nleft, len;
+
+ count = 0;
+ while ((nleft = pixelCount - count) > 0) {
+ len = stbi__get8(s);
+ if (len == 128) {
+ // No-op.
+ } else if (len < 128) {
+ // Copy next len+1 bytes literally.
+ len++;
+ if (len > nleft) return 0; // corrupt data
+ count += len;
+ while (len) {
+ *p = stbi__get8(s);
+ p += 4;
+ len--;
+ }
+ } else if (len > 128) {
+ stbi_uc val;
+ // Next -len+1 bytes in the dest are replicated from next source byte.
+ // (Interpret len as a negative 8-bit int.)
+ len = 257 - len;
+ if (len > nleft) return 0; // corrupt data
+ val = stbi__get8(s);
+ count += len;
+ while (len) {
+ *p = val;
+ p += 4;
+ len--;
+ }
+ }
+ }
+
+ return 1;
+}
+
+static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)
+{
+ int pixelCount;
+ int channelCount, compression;
+ int channel, i;
+ int bitdepth;
+ int w,h;
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ if (stbi__get32be(s) != 0x38425053) // "8BPS"
+ return stbi__errpuc("not PSD", "Corrupt PSD image");
+
+ // Check file type version.
+ if (stbi__get16be(s) != 1)
+ return stbi__errpuc("wrong version", "Unsupported version of PSD image");
+
+ // Skip 6 reserved bytes.
+ stbi__skip(s, 6 );
+
+ // Read the number of channels (R, G, B, A, etc).
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16)
+ return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
+
+ // Read the rows and columns of the image.
+ h = stbi__get32be(s);
+ w = stbi__get32be(s);
+
+ if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ // Make sure the depth is 8 bits.
+ bitdepth = stbi__get16be(s);
+ if (bitdepth != 8 && bitdepth != 16)
+ return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit");
+
+ // Make sure the color mode is RGB.
+ // Valid options are:
+ // 0: Bitmap
+ // 1: Grayscale
+ // 2: Indexed color
+ // 3: RGB color
+ // 4: CMYK color
+ // 7: Multichannel
+ // 8: Duotone
+ // 9: Lab color
+ if (stbi__get16be(s) != 3)
+ return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
+
+ // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
+ stbi__skip(s,stbi__get32be(s) );
+
+ // Skip the image resources. (resolution, pen tool paths, etc)
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Skip the reserved data.
+ stbi__skip(s, stbi__get32be(s) );
+
+ // Find out if the data is compressed.
+ // Known values:
+ // 0: no compression
+ // 1: RLE compressed
+ compression = stbi__get16be(s);
+ if (compression > 1)
+ return stbi__errpuc("bad compression", "PSD has an unknown compression format");
+
+ // Check size
+ if (!stbi__mad3sizes_valid(4, w, h, 0))
+ return stbi__errpuc("too large", "Corrupt PSD");
+
+ // Create the destination image.
+
+ if (!compression && bitdepth == 16 && bpc == 16) {
+ out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0);
+ ri->bits_per_channel = 16;
+ } else
+ out = (stbi_uc *) stbi__malloc(4 * w*h);
+
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ pixelCount = w*h;
+
+ // Initialize the data to zero.
+ //memset( out, 0, pixelCount * 4 );
+
+ // Finally, the image data.
+ if (compression) {
+ // RLE as used by .PSD and .TIFF
+ // Loop until you get the number of unpacked bytes you are expecting:
+ // Read the next source byte into n.
+ // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
+ // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
+ // Else if n is 128, noop.
+ // Endloop
+
+ // The RLE-compressed data is preceded by a 2-byte data count for each row in the data,
+ // which we're going to just skip.
+ stbi__skip(s, h * channelCount * 2 );
+
+ // Read the RLE data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ stbi_uc *p;
+
+ p = out+channel;
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (channel == 3 ? 255 : 0);
+ } else {
+ // Read the RLE data.
+ if (!stbi__psd_decode_rle(s, p, pixelCount)) {
+ STBI_FREE(out);
+ return stbi__errpuc("corrupt", "bad RLE data");
+ }
+ }
+ }
+
+ } else {
+ // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
+ // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.
+
+ // Read the data by channel.
+ for (channel = 0; channel < 4; channel++) {
+ if (channel >= channelCount) {
+ // Fill this channel with default data.
+ if (bitdepth == 16 && bpc == 16) {
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ stbi__uint16 val = channel == 3 ? 65535 : 0;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = val;
+ } else {
+ stbi_uc *p = out+channel;
+ stbi_uc val = channel == 3 ? 255 : 0;
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = val;
+ }
+ } else {
+ if (ri->bits_per_channel == 16) { // output bpc
+ stbi__uint16 *q = ((stbi__uint16 *) out) + channel;
+ for (i = 0; i < pixelCount; i++, q += 4)
+ *q = (stbi__uint16) stbi__get16be(s);
+ } else {
+ stbi_uc *p = out+channel;
+ if (bitdepth == 16) { // input bpc
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = (stbi_uc) (stbi__get16be(s) >> 8);
+ } else {
+ for (i = 0; i < pixelCount; i++, p += 4)
+ *p = stbi__get8(s);
+ }
+ }
+ }
+ }
+ }
+
+ // remove weird white matte from PSD
+ if (channelCount >= 4) {
+ if (ri->bits_per_channel == 16) {
+ for (i=0; i < w*h; ++i) {
+ stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 65535) {
+ float a = pixel[3] / 65535.0f;
+ float ra = 1.0f / a;
+ float inv_a = 65535.0f * (1 - ra);
+ pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a);
+ pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a);
+ pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a);
+ }
+ }
+ } else {
+ for (i=0; i < w*h; ++i) {
+ unsigned char *pixel = out + 4*i;
+ if (pixel[3] != 0 && pixel[3] != 255) {
+ float a = pixel[3] / 255.0f;
+ float ra = 1.0f / a;
+ float inv_a = 255.0f * (1 - ra);
+ pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);
+ pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);
+ pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);
+ }
+ }
+ }
+ }
+
+ // convert to desired output format
+ if (req_comp && req_comp != 4) {
+ if (ri->bits_per_channel == 16)
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);
+ else
+ out = stbi__convert_format(out, 4, req_comp, w, h);
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+
+ if (comp) *comp = 4;
+ *y = h;
+ *x = w;
+
+ return out;
+}
+#endif
+
+// *************************************************************************************************
+// Softimage PIC loader
+// by Tom Seddon
+//
+// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
+// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_is4(stbi__context *s,const char *str)
+{
+ int i;
+ for (i=0; i<4; ++i)
+ if (stbi__get8(s) != (stbi_uc)str[i])
+ return 0;
+
+ return 1;
+}
+
+static int stbi__pic_test_core(stbi__context *s)
+{
+ int i;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
+ return 0;
+
+ for(i=0;i<84;++i)
+ stbi__get8(s);
+
+ if (!stbi__pic_is4(s,"PICT"))
+ return 0;
+
+ return 1;
+}
+
+typedef struct
+{
+ stbi_uc size,type,channel;
+} stbi__pic_packet;
+
+static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
+{
+ int mask=0x80, i;
+
+ for (i=0; i<4; ++i, mask>>=1) {
+ if (channel & mask) {
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
+ dest[i]=stbi__get8(s);
+ }
+ }
+
+ return dest;
+}
+
+static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
+{
+ int mask=0x80,i;
+
+ for (i=0;i<4; ++i, mask>>=1)
+ if (channel&mask)
+ dest[i]=src[i];
+}
+
+static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
+{
+ int act_comp=0,num_packets=0,y,chained;
+ stbi__pic_packet packets[10];
+
+ // this will (should...) cater for even some bizarre stuff like having data
+ // for the same channel in multiple packets.
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return stbi__errpuc("bad format","too many packets");
+
+ packet = &packets[num_packets++];
+
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
+ if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
+
+ for(y=0; y<height; ++y) {
+ int packet_idx;
+
+ for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
+ stbi__pic_packet *packet = &packets[packet_idx];
+ stbi_uc *dest = result+y*width*4;
+
+ switch (packet->type) {
+ default:
+ return stbi__errpuc("bad format","packet has bad compression type");
+
+ case 0: {//uncompressed
+ int x;
+
+ for(x=0;x<width;++x, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ break;
+ }
+
+ case 1://Pure RLE
+ {
+ int left=width, i;
+
+ while (left>0) {
+ stbi_uc count,value[4];
+
+ count=stbi__get8(s);
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
+
+ if (count > left)
+ count = (stbi_uc) left;
+
+ if (!stbi__readval(s,packet->channel,value)) return 0;
+
+ for(i=0; i<count; ++i,dest+=4)
+ stbi__copyval(packet->channel,dest,value);
+ left -= count;
+ }
+ }
+ break;
+
+ case 2: {//Mixed RLE
+ int left=width;
+ while (left>0) {
+ int count = stbi__get8(s), i;
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
+
+ if (count >= 128) { // Repeated
+ stbi_uc value[4];
+
+ if (count==128)
+ count = stbi__get16be(s);
+ else
+ count -= 127;
+ if (count > left)
+ return stbi__errpuc("bad file","scanline overrun");
+
+ if (!stbi__readval(s,packet->channel,value))
+ return 0;
+
+ for(i=0;i<count;++i, dest += 4)
+ stbi__copyval(packet->channel,dest,value);
+ } else { // Raw
+ ++count;
+ if (count>left) return stbi__errpuc("bad file","scanline overrun");
+
+ for(i=0;i<count;++i, dest+=4)
+ if (!stbi__readval(s,packet->channel,dest))
+ return 0;
+ }
+ left-=count;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *result;
+ int i, x,y, internal_comp;
+ STBI_NOTUSED(ri);
+
+ if (!comp) comp = &internal_comp;
+
+ for (i=0; i<92; ++i)
+ stbi__get8(s);
+
+ x = stbi__get16be(s);
+ y = stbi__get16be(s);
+
+ if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
+ if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode");
+
+ stbi__get32be(s); //skip `ratio'
+ stbi__get16be(s); //skip `fields'
+ stbi__get16be(s); //skip `pad'
+
+ // intermediate buffer is RGBA
+ result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);
+ if (!result) return stbi__errpuc("outofmem", "Out of memory");
+ memset(result, 0xff, x*y*4);
+
+ if (!stbi__pic_load_core(s,x,y,comp, result)) {
+ STBI_FREE(result);
+ result=0;
+ }
+ *px = x;
+ *py = y;
+ if (req_comp == 0) req_comp = *comp;
+ result=stbi__convert_format(result,4,req_comp,x,y);
+
+ return result;
+}
+
+static int stbi__pic_test(stbi__context *s)
+{
+ int r = stbi__pic_test_core(s);
+ stbi__rewind(s);
+ return r;
+}
+#endif
+
+// *************************************************************************************************
+// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
+
+#ifndef STBI_NO_GIF
+typedef struct
+{
+ stbi__int16 prefix;
+ stbi_uc first;
+ stbi_uc suffix;
+} stbi__gif_lzw;
+
+typedef struct
+{
+ int w,h;
+ stbi_uc *out; // output buffer (always 4 components)
+ stbi_uc *background; // The current "background" as far as a gif is concerned
+ stbi_uc *history;
+ int flags, bgindex, ratio, transparent, eflags;
+ stbi_uc pal[256][4];
+ stbi_uc lpal[256][4];
+ stbi__gif_lzw codes[8192];
+ stbi_uc *color_table;
+ int parse, step;
+ int lflags;
+ int start_x, start_y;
+ int max_x, max_y;
+ int cur_x, cur_y;
+ int line_size;
+ int delay;
+} stbi__gif;
+
+static int stbi__gif_test_raw(stbi__context *s)
+{
+ int sz;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
+ sz = stbi__get8(s);
+ if (sz != '9' && sz != '7') return 0;
+ if (stbi__get8(s) != 'a') return 0;
+ return 1;
+}
+
+static int stbi__gif_test(stbi__context *s)
+{
+ int r = stbi__gif_test_raw(s);
+ stbi__rewind(s);
+ return r;
+}
+
+static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
+{
+ int i;
+ for (i=0; i < num_entries; ++i) {
+ pal[i][2] = stbi__get8(s);
+ pal[i][1] = stbi__get8(s);
+ pal[i][0] = stbi__get8(s);
+ pal[i][3] = transp == i ? 0 : 255;
+ }
+}
+
+static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
+{
+ stbi_uc version;
+ if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
+ return stbi__err("not GIF", "Corrupt GIF");
+
+ version = stbi__get8(s);
+ if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
+ if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
+
+ stbi__g_failure_reason = "";
+ g->w = stbi__get16le(s);
+ g->h = stbi__get16le(s);
+ g->flags = stbi__get8(s);
+ g->bgindex = stbi__get8(s);
+ g->ratio = stbi__get8(s);
+ g->transparent = -1;
+
+ if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+ if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)");
+
+ if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
+
+ if (is_info) return 1;
+
+ if (g->flags & 0x80)
+ stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
+
+ return 1;
+}
+
+static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
+{
+ stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));
+ if (!g) return stbi__err("outofmem", "Out of memory");
+ if (!stbi__gif_header(s, g, comp, 1)) {
+ STBI_FREE(g);
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = g->w;
+ if (y) *y = g->h;
+ STBI_FREE(g);
+ return 1;
+}
+
+static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
+{
+ stbi_uc *p, *c;
+ int idx;
+
+ // recurse to decode the prefixes, since the linked-list is backwards,
+ // and working backwards through an interleaved image would be nasty
+ if (g->codes[code].prefix >= 0)
+ stbi__out_gif_code(g, g->codes[code].prefix);
+
+ if (g->cur_y >= g->max_y) return;
+
+ idx = g->cur_x + g->cur_y;
+ p = &g->out[idx];
+ g->history[idx / 4] = 1;
+
+ c = &g->color_table[g->codes[code].suffix * 4];
+ if (c[3] > 128) { // don't render transparent pixels;
+ p[0] = c[2];
+ p[1] = c[1];
+ p[2] = c[0];
+ p[3] = c[3];
+ }
+ g->cur_x += 4;
+
+ if (g->cur_x >= g->max_x) {
+ g->cur_x = g->start_x;
+ g->cur_y += g->step;
+
+ while (g->cur_y >= g->max_y && g->parse > 0) {
+ g->step = (1 << g->parse) * g->line_size;
+ g->cur_y = g->start_y + (g->step >> 1);
+ --g->parse;
+ }
+ }
+}
+
+static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
+{
+ stbi_uc lzw_cs;
+ stbi__int32 len, init_code;
+ stbi__uint32 first;
+ stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
+ stbi__gif_lzw *p;
+
+ lzw_cs = stbi__get8(s);
+ if (lzw_cs > 12) return NULL;
+ clear = 1 << lzw_cs;
+ first = 1;
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ bits = 0;
+ valid_bits = 0;
+ for (init_code = 0; init_code < clear; init_code++) {
+ g->codes[init_code].prefix = -1;
+ g->codes[init_code].first = (stbi_uc) init_code;
+ g->codes[init_code].suffix = (stbi_uc) init_code;
+ }
+
+ // support no starting clear code
+ avail = clear+2;
+ oldcode = -1;
+
+ len = 0;
+ for(;;) {
+ if (valid_bits < codesize) {
+ if (len == 0) {
+ len = stbi__get8(s); // start new block
+ if (len == 0)
+ return g->out;
+ }
+ --len;
+ bits |= (stbi__int32) stbi__get8(s) << valid_bits;
+ valid_bits += 8;
+ } else {
+ stbi__int32 code = bits & codemask;
+ bits >>= codesize;
+ valid_bits -= codesize;
+ // @OPTIMIZE: is there some way we can accelerate the non-clear path?
+ if (code == clear) { // clear code
+ codesize = lzw_cs + 1;
+ codemask = (1 << codesize) - 1;
+ avail = clear + 2;
+ oldcode = -1;
+ first = 0;
+ } else if (code == clear + 1) { // end of stream code
+ stbi__skip(s, len);
+ while ((len = stbi__get8(s)) > 0)
+ stbi__skip(s,len);
+ return g->out;
+ } else if (code <= avail) {
+ if (first) {
+ return stbi__errpuc("no clear code", "Corrupt GIF");
+ }
+
+ if (oldcode >= 0) {
+ p = &g->codes[avail++];
+ if (avail > 8192) {
+ return stbi__errpuc("too many codes", "Corrupt GIF");
+ }
+
+ p->prefix = (stbi__int16) oldcode;
+ p->first = g->codes[oldcode].first;
+ p->suffix = (code == avail) ? p->first : g->codes[code].first;
+ } else if (code == avail)
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+
+ stbi__out_gif_code(g, (stbi__uint16) code);
+
+ if ((avail & codemask) == 0 && avail <= 0x0FFF) {
+ codesize++;
+ codemask = (1 << codesize) - 1;
+ }
+
+ oldcode = code;
+ } else {
+ return stbi__errpuc("illegal code in raster", "Corrupt GIF");
+ }
+ }
+ }
+}
+
+// this function is designed to support animated gifs, although stb_image doesn't support it
+// two back is the image from two frames ago, used for a very specific disposal format
+static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back)
+{
+ int dispose;
+ int first_frame;
+ int pi;
+ int pcount;
+ STBI_NOTUSED(req_comp);
+
+ // on first frame, any non-written pixels get the background colour (non-transparent)
+ first_frame = 0;
+ if (g->out == 0) {
+ if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
+ if (!stbi__mad3sizes_valid(4, g->w, g->h, 0))
+ return stbi__errpuc("too large", "GIF image is too large");
+ pcount = g->w * g->h;
+ g->out = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->background = (stbi_uc *) stbi__malloc(4 * pcount);
+ g->history = (stbi_uc *) stbi__malloc(pcount);
+ if (!g->out || !g->background || !g->history)
+ return stbi__errpuc("outofmem", "Out of memory");
+
+ // image is treated as "transparent" at the start - ie, nothing overwrites the current background;
+ // background colour is only used for pixels that are not rendered first frame, after that "background"
+ // color refers to the color that was there the previous frame.
+ memset(g->out, 0x00, 4 * pcount);
+ memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent)
+ memset(g->history, 0x00, pcount); // pixels that were affected previous frame
+ first_frame = 1;
+ } else {
+ // second frame - how do we dispose of the previous one?
+ dispose = (g->eflags & 0x1C) >> 2;
+ pcount = g->w * g->h;
+
+ if ((dispose == 3) && (two_back == 0)) {
+ dispose = 2; // if I don't have an image to revert back to, default to the old background
+ }
+
+ if (dispose == 3) { // use previous graphic
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 );
+ }
+ }
+ } else if (dispose == 2) {
+ // restore what was changed last frame to background before that frame;
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi]) {
+ memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 );
+ }
+ }
+ } else {
+ // This is a non-disposal case eithe way, so just
+ // leave the pixels as is, and they will become the new background
+ // 1: do not dispose
+ // 0: not specified.
+ }
+
+ // background is what out is after the undoing of the previou frame;
+ memcpy( g->background, g->out, 4 * g->w * g->h );
+ }
+
+ // clear my history;
+ memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame
+
+ for (;;) {
+ int tag = stbi__get8(s);
+ switch (tag) {
+ case 0x2C: /* Image Descriptor */
+ {
+ stbi__int32 x, y, w, h;
+ stbi_uc *o;
+
+ x = stbi__get16le(s);
+ y = stbi__get16le(s);
+ w = stbi__get16le(s);
+ h = stbi__get16le(s);
+ if (((x + w) > (g->w)) || ((y + h) > (g->h)))
+ return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
+
+ g->line_size = g->w * 4;
+ g->start_x = x * 4;
+ g->start_y = y * g->line_size;
+ g->max_x = g->start_x + w * 4;
+ g->max_y = g->start_y + h * g->line_size;
+ g->cur_x = g->start_x;
+ g->cur_y = g->start_y;
+
+ // if the width of the specified rectangle is 0, that means
+ // we may not see *any* pixels or the image is malformed;
+ // to make sure this is caught, move the current y down to
+ // max_y (which is what out_gif_code checks).
+ if (w == 0)
+ g->cur_y = g->max_y;
+
+ g->lflags = stbi__get8(s);
+
+ if (g->lflags & 0x40) {
+ g->step = 8 * g->line_size; // first interlaced spacing
+ g->parse = 3;
+ } else {
+ g->step = g->line_size;
+ g->parse = 0;
+ }
+
+ if (g->lflags & 0x80) {
+ stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
+ g->color_table = (stbi_uc *) g->lpal;
+ } else if (g->flags & 0x80) {
+ g->color_table = (stbi_uc *) g->pal;
+ } else
+ return stbi__errpuc("missing color table", "Corrupt GIF");
+
+ o = stbi__process_gif_raster(s, g);
+ if (!o) return NULL;
+
+ // if this was the first frame,
+ pcount = g->w * g->h;
+ if (first_frame && (g->bgindex > 0)) {
+ // if first frame, any pixel not drawn to gets the background color
+ for (pi = 0; pi < pcount; ++pi) {
+ if (g->history[pi] == 0) {
+ g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be;
+ memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 );
+ }
+ }
+ }
+
+ return o;
+ }
+
+ case 0x21: // Comment Extension.
+ {
+ int len;
+ int ext = stbi__get8(s);
+ if (ext == 0xF9) { // Graphic Control Extension.
+ len = stbi__get8(s);
+ if (len == 4) {
+ g->eflags = stbi__get8(s);
+ g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths.
+
+ // unset old transparent
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 255;
+ }
+ if (g->eflags & 0x01) {
+ g->transparent = stbi__get8(s);
+ if (g->transparent >= 0) {
+ g->pal[g->transparent][3] = 0;
+ }
+ } else {
+ // don't need transparent
+ stbi__skip(s, 1);
+ g->transparent = -1;
+ }
+ } else {
+ stbi__skip(s, len);
+ break;
+ }
+ }
+ while ((len = stbi__get8(s)) != 0) {
+ stbi__skip(s, len);
+ }
+ break;
+ }
+
+ case 0x3B: // gif stream termination code
+ return (stbi_uc *) s; // using '1' causes warning on some compilers
+
+ default:
+ return stbi__errpuc("unknown code", "Corrupt GIF");
+ }
+ }
+}
+
+static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)
+{
+ STBI_FREE(g->out);
+ STBI_FREE(g->history);
+ STBI_FREE(g->background);
+
+ if (out) STBI_FREE(out);
+ if (delays && *delays) STBI_FREE(*delays);
+ return stbi__errpuc("outofmem", "Out of memory");
+}
+
+static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)
+{
+ if (stbi__gif_test(s)) {
+ int layers = 0;
+ stbi_uc *u = 0;
+ stbi_uc *out = 0;
+ stbi_uc *two_back = 0;
+ stbi__gif g;
+ int stride;
+ int out_size = 0;
+ int delays_size = 0;
+
+ STBI_NOTUSED(out_size);
+ STBI_NOTUSED(delays_size);
+
+ memset(&g, 0, sizeof(g));
+ if (delays) {
+ *delays = 0;
+ }
+
+ do {
+ u = stbi__gif_load_next(s, &g, comp, req_comp, two_back);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+ ++layers;
+ stride = g.w * g.h * 4;
+
+ if (out) {
+ void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );
+ if (!tmp)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ else {
+ out = (stbi_uc*) tmp;
+ out_size = layers * stride;
+ }
+
+ if (delays) {
+ int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );
+ if (!new_delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ *delays = new_delays;
+ delays_size = layers * sizeof(int);
+ }
+ } else {
+ out = (stbi_uc*)stbi__malloc( layers * stride );
+ if (!out)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ out_size = layers * stride;
+ if (delays) {
+ *delays = (int*) stbi__malloc( layers * sizeof(int) );
+ if (!*delays)
+ return stbi__load_gif_main_outofmem(&g, out, delays);
+ delays_size = layers * sizeof(int);
+ }
+ }
+ memcpy( out + ((layers - 1) * stride), u, stride );
+ if (layers >= 2) {
+ two_back = out - 2 * stride;
+ }
+
+ if (delays) {
+ (*delays)[layers - 1U] = g.delay;
+ }
+ }
+ } while (u != 0);
+
+ // free temp buffer;
+ STBI_FREE(g.out);
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ // do the final conversion after loading everything;
+ if (req_comp && req_comp != 4)
+ out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h);
+
+ *z = layers;
+ return out;
+ } else {
+ return stbi__errpuc("not GIF", "Image was not as a gif type.");
+ }
+}
+
+static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *u = 0;
+ stbi__gif g;
+ memset(&g, 0, sizeof(g));
+ STBI_NOTUSED(ri);
+
+ u = stbi__gif_load_next(s, &g, comp, req_comp, 0);
+ if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
+ if (u) {
+ *x = g.w;
+ *y = g.h;
+
+ // moved conversion to after successful load so that the same
+ // can be done for multiple frames.
+ if (req_comp && req_comp != 4)
+ u = stbi__convert_format(u, 4, req_comp, g.w, g.h);
+ } else if (g.out) {
+ // if there was an error and we allocated an image buffer, free it!
+ STBI_FREE(g.out);
+ }
+
+ // free buffers needed for multiple frame loading;
+ STBI_FREE(g.history);
+ STBI_FREE(g.background);
+
+ return u;
+}
+
+static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ return stbi__gif_info_raw(s,x,y,comp);
+}
+#endif
+
+// *************************************************************************************************
+// Radiance RGBE HDR loader
+// originally by Nicolas Schulz
+#ifndef STBI_NO_HDR
+static int stbi__hdr_test_core(stbi__context *s, const char *signature)
+{
+ int i;
+ for (i=0; signature[i]; ++i)
+ if (stbi__get8(s) != signature[i])
+ return 0;
+ stbi__rewind(s);
+ return 1;
+}
+
+static int stbi__hdr_test(stbi__context* s)
+{
+ int r = stbi__hdr_test_core(s, "#?RADIANCE\n");
+ stbi__rewind(s);
+ if(!r) {
+ r = stbi__hdr_test_core(s, "#?RGBE\n");
+ stbi__rewind(s);
+ }
+ return r;
+}
+
+#define STBI__HDR_BUFLEN 1024
+static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
+{
+ int len=0;
+ char c = '\0';
+
+ c = (char) stbi__get8(z);
+
+ while (!stbi__at_eof(z) && c != '\n') {
+ buffer[len++] = c;
+ if (len == STBI__HDR_BUFLEN-1) {
+ // flush to end of line
+ while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
+ ;
+ break;
+ }
+ c = (char) stbi__get8(z);
+ }
+
+ buffer[len] = 0;
+ return buffer;
+}
+
+static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
+{
+ if ( input[3] != 0 ) {
+ float f1;
+ // Exponent
+ f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
+ if (req_comp <= 2)
+ output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
+ else {
+ output[0] = input[0] * f1;
+ output[1] = input[1] * f1;
+ output[2] = input[2] * f1;
+ }
+ if (req_comp == 2) output[1] = 1;
+ if (req_comp == 4) output[3] = 1;
+ } else {
+ switch (req_comp) {
+ case 4: output[3] = 1; /* fallthrough */
+ case 3: output[0] = output[1] = output[2] = 0;
+ break;
+ case 2: output[1] = 1; /* fallthrough */
+ case 1: output[0] = 0;
+ break;
+ }
+ }
+}
+
+static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int width, height;
+ stbi_uc *scanline;
+ float *hdr_data;
+ int len;
+ unsigned char count, value;
+ int i, j, k, c1,c2, z;
+ const char *headerToken;
+ STBI_NOTUSED(ri);
+
+ // Check identifier
+ headerToken = stbi__hdr_gettoken(s,buffer);
+ if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)
+ return stbi__errpf("not HDR", "Corrupt HDR image");
+
+ // Parse header
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
+
+ // Parse width and height
+ // can't use sscanf() if we're not using stdio!
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ height = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
+ token += 3;
+ width = (int) strtol(token, NULL, 10);
+
+ if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+ if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)");
+
+ *x = width;
+ *y = height;
+
+ if (comp) *comp = 3;
+ if (req_comp == 0) req_comp = 3;
+
+ if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))
+ return stbi__errpf("too large", "HDR image is too large");
+
+ // Read data
+ hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);
+ if (!hdr_data)
+ return stbi__errpf("outofmem", "Out of memory");
+
+ // Load image data
+ // image data is stored as some number of sca
+ if ( width < 8 || width >= 32768) {
+ // Read flat data
+ for (j=0; j < height; ++j) {
+ for (i=0; i < width; ++i) {
+ stbi_uc rgbe[4];
+ main_decode_loop:
+ stbi__getn(s, rgbe, 4);
+ stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
+ }
+ }
+ } else {
+ // Read RLE-encoded data
+ scanline = NULL;
+
+ for (j = 0; j < height; ++j) {
+ c1 = stbi__get8(s);
+ c2 = stbi__get8(s);
+ len = stbi__get8(s);
+ if (c1 != 2 || c2 != 2 || (len & 0x80)) {
+ // not run-length encoded, so we have to actually use THIS data as a decoded
+ // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
+ stbi_uc rgbe[4];
+ rgbe[0] = (stbi_uc) c1;
+ rgbe[1] = (stbi_uc) c2;
+ rgbe[2] = (stbi_uc) len;
+ rgbe[3] = (stbi_uc) stbi__get8(s);
+ stbi__hdr_convert(hdr_data, rgbe, req_comp);
+ i = 1;
+ j = 0;
+ STBI_FREE(scanline);
+ goto main_decode_loop; // yes, this makes no sense
+ }
+ len <<= 8;
+ len |= stbi__get8(s);
+ if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
+ if (scanline == NULL) {
+ scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);
+ if (!scanline) {
+ STBI_FREE(hdr_data);
+ return stbi__errpf("outofmem", "Out of memory");
+ }
+ }
+
+ for (k = 0; k < 4; ++k) {
+ int nleft;
+ i = 0;
+ while ((nleft = width - i) > 0) {
+ count = stbi__get8(s);
+ if (count > 128) {
+ // Run
+ value = stbi__get8(s);
+ count -= 128;
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = value;
+ } else {
+ // Dump
+ if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }
+ for (z = 0; z < count; ++z)
+ scanline[i++ * 4 + k] = stbi__get8(s);
+ }
+ }
+ }
+ for (i=0; i < width; ++i)
+ stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
+ }
+ if (scanline)
+ STBI_FREE(scanline);
+ }
+
+ return hdr_data;
+}
+
+static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ char buffer[STBI__HDR_BUFLEN];
+ char *token;
+ int valid = 0;
+ int dummy;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (stbi__hdr_test(s) == 0) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ for(;;) {
+ token = stbi__hdr_gettoken(s,buffer);
+ if (token[0] == 0) break;
+ if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
+ }
+
+ if (!valid) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token = stbi__hdr_gettoken(s,buffer);
+ if (strncmp(token, "-Y ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *y = (int) strtol(token, &token, 10);
+ while (*token == ' ') ++token;
+ if (strncmp(token, "+X ", 3)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ token += 3;
+ *x = (int) strtol(token, NULL, 10);
+ *comp = 3;
+ return 1;
+}
+#endif // STBI_NO_HDR
+
+#ifndef STBI_NO_BMP
+static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ void *p;
+ stbi__bmp_data info;
+
+ info.all_a = 255;
+ p = stbi__bmp_parse_header(s, &info);
+ if (p == NULL) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (x) *x = s->img_x;
+ if (y) *y = s->img_y;
+ if (comp) {
+ if (info.bpp == 24 && info.ma == 0xff000000)
+ *comp = 3;
+ else
+ *comp = info.ma ? 4 : 3;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PSD
+static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int channelCount, dummy, depth;
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *y = stbi__get32be(s);
+ *x = stbi__get32be(s);
+ depth = stbi__get16be(s);
+ if (depth != 8 && depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 3) {
+ stbi__rewind( s );
+ return 0;
+ }
+ *comp = 4;
+ return 1;
+}
+
+static int stbi__psd_is16(stbi__context *s)
+{
+ int channelCount, depth;
+ if (stbi__get32be(s) != 0x38425053) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (stbi__get16be(s) != 1) {
+ stbi__rewind( s );
+ return 0;
+ }
+ stbi__skip(s, 6);
+ channelCount = stbi__get16be(s);
+ if (channelCount < 0 || channelCount > 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ STBI_NOTUSED(stbi__get32be(s));
+ STBI_NOTUSED(stbi__get32be(s));
+ depth = stbi__get16be(s);
+ if (depth != 16) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+#endif
+
+#ifndef STBI_NO_PIC
+static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int act_comp=0,num_packets=0,chained,dummy;
+ stbi__pic_packet packets[10];
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ stbi__skip(s, 88);
+
+ *x = stbi__get16be(s);
+ *y = stbi__get16be(s);
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s);
+ return 0;
+ }
+ if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
+ stbi__rewind( s );
+ return 0;
+ }
+
+ stbi__skip(s, 8);
+
+ do {
+ stbi__pic_packet *packet;
+
+ if (num_packets==sizeof(packets)/sizeof(packets[0]))
+ return 0;
+
+ packet = &packets[num_packets++];
+ chained = stbi__get8(s);
+ packet->size = stbi__get8(s);
+ packet->type = stbi__get8(s);
+ packet->channel = stbi__get8(s);
+ act_comp |= packet->channel;
+
+ if (stbi__at_eof(s)) {
+ stbi__rewind( s );
+ return 0;
+ }
+ if (packet->size != 8) {
+ stbi__rewind( s );
+ return 0;
+ }
+ } while (chained);
+
+ *comp = (act_comp & 0x10 ? 4 : 3);
+
+ return 1;
+}
+#endif
+
+// *************************************************************************************************
+// Portable Gray Map and Portable Pixel Map loader
+// by Ken Miller
+//
+// PGM: http://netpbm.sourceforge.net/doc/pgm.html
+// PPM: http://netpbm.sourceforge.net/doc/ppm.html
+//
+// Known limitations:
+// Does not support comments in the header section
+// Does not support ASCII image data (formats P2 and P3)
+
+#ifndef STBI_NO_PNM
+
+static int stbi__pnm_test(stbi__context *s)
+{
+ char p, t;
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind( s );
+ return 0;
+ }
+ return 1;
+}
+
+static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)
+{
+ stbi_uc *out;
+ STBI_NOTUSED(ri);
+
+ ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);
+ if (ri->bits_per_channel == 0)
+ return 0;
+
+ if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+ if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");
+
+ *x = s->img_x;
+ *y = s->img_y;
+ if (comp) *comp = s->img_n;
+
+ if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))
+ return stbi__errpuc("too large", "PNM too large");
+
+ out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);
+ if (!out) return stbi__errpuc("outofmem", "Out of memory");
+ if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) {
+ STBI_FREE(out);
+ return stbi__errpuc("bad PNM", "PNM file truncated");
+ }
+
+ if (req_comp && req_comp != s->img_n) {
+ if (ri->bits_per_channel == 16) {
+ out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y);
+ } else {
+ out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
+ }
+ if (out == NULL) return out; // stbi__convert_format frees input on failure
+ }
+ return out;
+}
+
+static int stbi__pnm_isspace(char c)
+{
+ return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
+}
+
+static void stbi__pnm_skip_whitespace(stbi__context *s, char *c)
+{
+ for (;;) {
+ while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
+ *c = (char) stbi__get8(s);
+
+ if (stbi__at_eof(s) || *c != '#')
+ break;
+
+ while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' )
+ *c = (char) stbi__get8(s);
+ }
+}
+
+static int stbi__pnm_isdigit(char c)
+{
+ return c >= '0' && c <= '9';
+}
+
+static int stbi__pnm_getinteger(stbi__context *s, char *c)
+{
+ int value = 0;
+
+ while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
+ value = value*10 + (*c - '0');
+ *c = (char) stbi__get8(s);
+ if((value > 214748364) || (value == 214748364 && *c > '7'))
+ return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int");
+ }
+
+ return value;
+}
+
+static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
+{
+ int maxv, dummy;
+ char c, p, t;
+
+ if (!x) x = &dummy;
+ if (!y) y = &dummy;
+ if (!comp) comp = &dummy;
+
+ stbi__rewind(s);
+
+ // Get identifier
+ p = (char) stbi__get8(s);
+ t = (char) stbi__get8(s);
+ if (p != 'P' || (t != '5' && t != '6')) {
+ stbi__rewind(s);
+ return 0;
+ }
+
+ *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
+
+ c = (char) stbi__get8(s);
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *x = stbi__pnm_getinteger(s, &c); // read width
+ if(*x == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ *y = stbi__pnm_getinteger(s, &c); // read height
+ if (*y == 0)
+ return stbi__err("invalid width", "PPM image header had zero or overflowing width");
+ stbi__pnm_skip_whitespace(s, &c);
+
+ maxv = stbi__pnm_getinteger(s, &c); // read max value
+ if (maxv > 65535)
+ return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");
+ else if (maxv > 255)
+ return 16;
+ else
+ return 8;
+}
+
+static int stbi__pnm_is16(stbi__context *s)
+{
+ if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)
+ return 1;
+ return 0;
+}
+#endif
+
+static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
+{
+ #ifndef STBI_NO_JPEG
+ if (stbi__jpeg_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNG
+ if (stbi__png_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_GIF
+ if (stbi__gif_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_BMP
+ if (stbi__bmp_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PIC
+ if (stbi__pic_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_info(s, x, y, comp)) return 1;
+ #endif
+
+ #ifndef STBI_NO_HDR
+ if (stbi__hdr_info(s, x, y, comp)) return 1;
+ #endif
+
+ // test tga last because it's a crappy test!
+ #ifndef STBI_NO_TGA
+ if (stbi__tga_info(s, x, y, comp))
+ return 1;
+ #endif
+ return stbi__err("unknown image type", "Image not of any known type, or corrupt");
+}
+
+static int stbi__is_16_main(stbi__context *s)
+{
+ #ifndef STBI_NO_PNG
+ if (stbi__png_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PSD
+ if (stbi__psd_is16(s)) return 1;
+ #endif
+
+ #ifndef STBI_NO_PNM
+ if (stbi__pnm_is16(s)) return 1;
+ #endif
+ return 0;
+}
+
+#ifndef STBI_NO_STDIO
+STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_info_from_file(f, x, y, comp);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__info_main(&s,x,y,comp);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+
+STBIDEF int stbi_is_16_bit(char const *filename)
+{
+ FILE *f = stbi__fopen(filename, "rb");
+ int result;
+ if (!f) return stbi__err("can't fopen", "Unable to open file");
+ result = stbi_is_16_bit_from_file(f);
+ fclose(f);
+ return result;
+}
+
+STBIDEF int stbi_is_16_bit_from_file(FILE *f)
+{
+ int r;
+ stbi__context s;
+ long pos = ftell(f);
+ stbi__start_file(&s, f);
+ r = stbi__is_16_main(&s);
+ fseek(f,pos,SEEK_SET);
+ return r;
+}
+#endif // !STBI_NO_STDIO
+
+STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__info_main(&s,x,y,comp);
+}
+
+STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len)
+{
+ stbi__context s;
+ stbi__start_mem(&s,buffer,len);
+ return stbi__is_16_main(&s);
+}
+
+STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user)
+{
+ stbi__context s;
+ stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
+ return stbi__is_16_main(&s);
+}
+
+#endif // STB_IMAGE_IMPLEMENTATION
+
+/*
+ revision history:
+ 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs
+ 2.19 (2018-02-11) fix warning
+ 2.18 (2018-01-30) fix warnings
+ 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug
+ 1-bit BMP
+ *_is_16_bit api
+ avoid warnings
+ 2.16 (2017-07-23) all functions have 16-bit variants;
+ STBI_NO_STDIO works again;
+ compilation fixes;
+ fix rounding in unpremultiply;
+ optimize vertical flip;
+ disable raw_len validation;
+ documentation fixes
+ 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode;
+ warning fixes; disable run-time SSE detection on gcc;
+ uniform handling of optional "return" values;
+ thread-safe initialization of zlib tables
+ 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs
+ 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now
+ 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes
+ 2.11 (2016-04-02) allocate large structures on the stack
+ remove white matting for transparent PSD
+ fix reported channel count for PNG & BMP
+ re-enable SSE2 in non-gcc 64-bit
+ support RGB-formatted JPEG
+ read 16-bit PNGs (only as 8-bit)
+ 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED
+ 2.09 (2016-01-16) allow comments in PNM files
+ 16-bit-per-pixel TGA (not bit-per-component)
+ info() for TGA could break due to .hdr handling
+ info() for BMP to shares code instead of sloppy parse
+ can use STBI_REALLOC_SIZED if allocator doesn't support realloc
+ code cleanup
+ 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA
+ 2.07 (2015-09-13) fix compiler warnings
+ partial animated GIF support
+ limited 16-bpc PSD support
+ #ifdef unused functions
+ bug with < 92 byte PIC,PNM,HDR,TGA
+ 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value
+ 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
+ 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
+ 2.03 (2015-04-12) extra corruption checking (mmozeiko)
+ stbi_set_flip_vertically_on_load (nguillemot)
+ fix NEON support; fix mingw support
+ 2.02 (2015-01-19) fix incorrect assert, fix warning
+ 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
+ 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
+ 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
+ progressive JPEG (stb)
+ PGM/PPM support (Ken Miller)
+ STBI_MALLOC,STBI_REALLOC,STBI_FREE
+ GIF bugfix -- seemingly never worked
+ STBI_NO_*, STBI_ONLY_*
+ 1.48 (2014-12-14) fix incorrectly-named assert()
+ 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
+ optimize PNG (ryg)
+ fix bug in interlaced PNG with user-specified channel count (stb)
+ 1.46 (2014-08-26)
+ fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
+ 1.45 (2014-08-16)
+ fix MSVC-ARM internal compiler error by wrapping malloc
+ 1.44 (2014-08-07)
+ various warning fixes from Ronny Chevalier
+ 1.43 (2014-07-15)
+ fix MSVC-only compiler problem in code changed in 1.42
+ 1.42 (2014-07-09)
+ don't define _CRT_SECURE_NO_WARNINGS (affects user code)
+ fixes to stbi__cleanup_jpeg path
+ added STBI_ASSERT to avoid requiring assert.h
+ 1.41 (2014-06-25)
+ fix search&replace from 1.36 that messed up comments/error messages
+ 1.40 (2014-06-22)
+ fix gcc struct-initialization warning
+ 1.39 (2014-06-15)
+ fix to TGA optimization when req_comp != number of components in TGA;
+ fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
+ add support for BMP version 5 (more ignored fields)
+ 1.38 (2014-06-06)
+ suppress MSVC warnings on integer casts truncating values
+ fix accidental rename of 'skip' field of I/O
+ 1.37 (2014-06-04)
+ remove duplicate typedef
+ 1.36 (2014-06-03)
+ convert to header file single-file library
+ if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
+ 1.35 (2014-05-27)
+ various warnings
+ fix broken STBI_SIMD path
+ fix bug where stbi_load_from_file no longer left file pointer in correct place
+ fix broken non-easy path for 32-bit BMP (possibly never used)
+ TGA optimization by Arseny Kapoulkine
+ 1.34 (unknown)
+ use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
+ 1.33 (2011-07-14)
+ make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
+ 1.32 (2011-07-13)
+ support for "info" function for all supported filetypes (SpartanJ)
+ 1.31 (2011-06-20)
+ a few more leak fixes, bug in PNG handling (SpartanJ)
+ 1.30 (2011-06-11)
+ added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
+ removed deprecated format-specific test/load functions
+ removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
+ error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
+ fix inefficiency in decoding 32-bit BMP (David Woo)
+ 1.29 (2010-08-16)
+ various warning fixes from Aurelien Pocheville
+ 1.28 (2010-08-01)
+ fix bug in GIF palette transparency (SpartanJ)
+ 1.27 (2010-08-01)
+ cast-to-stbi_uc to fix warnings
+ 1.26 (2010-07-24)
+ fix bug in file buffering for PNG reported by SpartanJ
+ 1.25 (2010-07-17)
+ refix trans_data warning (Won Chun)
+ 1.24 (2010-07-12)
+ perf improvements reading from files on platforms with lock-heavy fgetc()
+ minor perf improvements for jpeg
+ deprecated type-specific functions so we'll get feedback if they're needed
+ attempt to fix trans_data warning (Won Chun)
+ 1.23 fixed bug in iPhone support
+ 1.22 (2010-07-10)
+ removed image *writing* support
+ stbi_info support from Jetro Lauha
+ GIF support from Jean-Marc Lienher
+ iPhone PNG-extensions from James Brown
+ warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
+ 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
+ 1.20 added support for Softimage PIC, by Tom Seddon
+ 1.19 bug in interlaced PNG corruption check (found by ryg)
+ 1.18 (2008-08-02)
+ fix a threading bug (local mutable static)
+ 1.17 support interlaced PNG
+ 1.16 major bugfix - stbi__convert_format converted one too many pixels
+ 1.15 initialize some fields for thread safety
+ 1.14 fix threadsafe conversion bug
+ header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
+ 1.13 threadsafe
+ 1.12 const qualifiers in the API
+ 1.11 Support installable IDCT, colorspace conversion routines
+ 1.10 Fixes for 64-bit (don't use "unsigned long")
+ optimized upsampling by Fabian "ryg" Giesen
+ 1.09 Fix format-conversion for PSD code (bad global variables!)
+ 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
+ 1.07 attempt to fix C++ warning/errors again
+ 1.06 attempt to fix C++ warning/errors again
+ 1.05 fix TGA loading to return correct *comp and use good luminance calc
+ 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
+ 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
+ 1.02 support for (subset of) HDR files, float interface for preferred access to them
+ 1.01 fix bug: possible bug in handling right-side up bmps... not sure
+ fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
+ 1.00 interface to zlib that skips zlib header
+ 0.99 correct handling of alpha in palette
+ 0.98 TGA loader by lonesock; dynamically add loaders (untested)
+ 0.97 jpeg errors on too large a file; also catch another malloc failure
+ 0.96 fix detection of invalid v value - particleman@mollyrocket forum
+ 0.95 during header scan, seek to markers in case of padding
+ 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
+ 0.93 handle jpegtran output; verbose errors
+ 0.92 read 4,8,16,24,32-bit BMP files of several formats
+ 0.91 output 24-bit Windows 3.0 BMP files
+ 0.90 fix a few more warnings; bump version number to approach 1.0
+ 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
+ 0.60 fix compiling as c++
+ 0.59 fix warnings: merge Dave Moore's -Wall fixes
+ 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
+ 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
+ 0.56 fix bug: zlib uncompressed mode len vs. nlen
+ 0.55 fix bug: restart_interval not initialized to 0
+ 0.54 allow NULL for 'int *comp'
+ 0.53 fix bug in png 3->4; speedup png decoding
+ 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
+ 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
+ on 'test' only check type, not whether we support this variant
+ 0.50 (2006-11-19)
+ first released version
+*/
+
+
+/*
+------------------------------------------------------------------------------
+This software is available under 2 licenses -- choose whichever you prefer.
+------------------------------------------------------------------------------
+ALTERNATIVE A - MIT License
+Copyright (c) 2017 Sean Barrett
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+------------------------------------------------------------------------------
+ALTERNATIVE B - Public Domain (www.unlicense.org)
+This is free and unencumbered software released into the public domain.
+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
+software, either in source code form or as a compiled binary, for any purpose,
+commercial or non-commercial, and by any means.
+In jurisdictions that recognize copyright laws, the author or authors of this
+software dedicate any and all copyright interest in the software to the public
+domain. We make this dedication for the benefit of the public at large and to
+the detriment of our heirs and successors. We intend this dedication to be an
+overt act of relinquishment in perpetuity of all present and future rights to
+this software under copyright law.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+------------------------------------------------------------------------------
+*/
diff --git a/src/sxbar.c b/src/sxbar.c
index 69b2fe4..d747710 100644
--- a/src/sxbar.c
+++ b/src/sxbar.c
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <err.h>
+#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -16,6 +17,13 @@
#include "defs.h"
#include "parser.h"
+/* vendored, public domain (see src/stb_image.h) -- decodes popup_image
+ * rows (e.g. album art) without pulling in a full image-loading library
+ * (Imlib2 et al.) as a runtime dependency; the decoder compiles straight
+ * into this binary instead */
+#define STB_IMAGE_IMPLEMENTATION
+#include "stb_image.h"
+
void cleanup_modules(void);
void cleanup_resources(void);
@@ -98,6 +106,45 @@ static int text_width(const char *str)
return ext.xOff;
}
+/* a workspace's displayed label: its configured workspace_icon override
+ * (e.g. a Nerd Font glyph) if one matches its _NET_DESKTOP_NAMES string,
+ * else that string unchanged */
+static const char *workspace_display_name(const char *name)
+{
+ for (int i = 0; i < config.workspace_icon_count; i++) {
+ if (!strcmp(config.workspace_icons[i].name, name))
+ return config.workspace_icons[i].icon;
+ }
+ return name;
+}
+
+/* x to actually draw a " %s "-wrapped workspace label at (instead of
+ * plain origin_x) so `inner`'s visual ink sits centered within the
+ * padded string's full advance width `box_w`, given `lead_w` (the
+ * advance of the one literal leading space). Several Nerd Font icon
+ * glyphs -- especially outside the "Mono" variant of a given font --
+ * report a narrow advance (e.g. one monospace cell) while their ink is
+ * considerably wider and shifted, which throws off centering inside a
+ * fixed box like the workspace switcher's highlight pill.
+ *
+ * Measuring the *padded* string's own extents directly doesn't work: at
+ * least for JetBrainsMono Nerd Font, XftTextExtentsUtf8() reports the
+ * padded string's bounding box as if it always spans its full advance
+ * width (x=0, width=xOff) regardless of where the inner glyph's ink
+ * actually sits, silently producing a zero shift for exactly the glyphs
+ * that most need one. Measuring `inner` alone instead (correctly
+ * asymmetric) and offsetting by the known leading space width sidesteps
+ * that. This leaves box_w itself (and therefore layout/box sizing
+ * elsewhere) untouched -- only where within it we draw shifts. */
+static int ink_centered_x(int origin_x, int box_w, int lead_w, const char *inner)
+{
+ XGlyphInfo in;
+ XftTextExtentsUtf8(dpy, font, (const FcChar8 *)inner, strlen(inner), &in);
+ int ink_center = lead_w + in.x + in.width / 2;
+ int box_center = box_w / 2;
+ return origin_x + (box_center - ink_center);
+}
+
/* module's cached output with its configured prefix (static text, or the
* live output of a prefix_cmd script) prepended */
static const char *module_text(Module *m, char *buf, size_t bufsz)
@@ -114,12 +161,75 @@ static const char *module_text(Module *m, char *buf, size_t bufsz)
/* space a module reserves in the layout: its text width, or its configured
* minimum, whichever is larger -- keeps everything else on the bar from
- * shifting when the text width changes (e.g. cpu going from one digit to two) */
+ * shifting when the text width changes (e.g. cpu going from one digit to
+ * two). Capped at max_width instead, if set and the text overflows it --
+ * that text scrolls (marquee) within the fixed slot rather than growing it. */
static int module_slot_width(Module *m, int text_w)
{
+ if (m->max_width > 0 && text_w > m->max_width)
+ return m->max_width;
return text_w > m->min_width ? text_w : m->min_width;
}
+#define MARQUEE_GAP " " /* separates the wrap point in a scrolling ticker */
+
+/* draws `text` at (x, text_y); if it's narrower than max_w (or max_w <= 0,
+ * meaning "no cap") this is just XftDrawStringUtf8, same as always. If it's
+ * wider, the text is clipped to max_w and drawn twice back to back
+ * (text+gap, text+gap) offset by *offset, so it reads as one continuously-
+ * wrapping ticker rather than jumping at the seam. Shared by the bar's own
+ * module text (driven by a Module's max_width/scroll_offset) and a popup's
+ * text/button rows (driven by a PopupItem's own scroll_offset, capped to
+ * the popup's actual width) -- callers own advancing *offset over time. */
+static void draw_ticker(XftDraw *d, XftColor *col, int x, int text_y, int max_w, const char *text, int tw, int offset)
+{
+ if (max_w <= 0 || tw <= max_w) {
+ XftDrawStringUtf8(d, col, font, x, text_y, (const FcChar8 *)text, strlen(text));
+ return;
+ }
+
+ char rep[512];
+ snprintf(rep, sizeof rep, "%s%s", text, MARQUEE_GAP);
+ int rep_w = text_width(rep);
+ int off = rep_w > 0 ? offset % rep_w : 0;
+
+ XRectangle clip = {.x = (short)x, .y = (short)(text_y - font->ascent),
+ .width = (unsigned short)max_w,
+ .height = (unsigned short)(font->ascent + font->descent)};
+ XftDrawSetClipRectangles(d, 0, 0, &clip, 1);
+ XftDrawStringUtf8(d, col, font, x - off, text_y, (const FcChar8 *)rep, strlen(rep));
+ XftDrawStringUtf8(d, col, font, x - off + rep_w, text_y, (const FcChar8 *)rep, strlen(rep));
+ XftDrawSetClip(d, NULL);
+}
+
+static void draw_module_text(XftDraw *d, XftColor *col, int x, int text_y, Module *m, const char *out, int tw)
+{
+ draw_ticker(d, col, x, text_y, m->max_width, out, tw, m->scroll_offset);
+}
+
+#define MARQUEE_STEP_PX 2 /* pixels advanced per redraw tick while scrolling */
+
+/* advance scroll_offset for every enabled module whose text currently
+ * overflows its max_width, and report (via return value) whether any of
+ * them did -- run() uses that to decide how often to redraw: fast while
+ * something's actually animating, the normal cadence otherwise */
+static int advance_marquees(void)
+{
+ int any = 0;
+ char mbuf[256];
+ for (int i = 0; i < config.module_count; i++) {
+ Module *m = &config.modules[i];
+ if (!m->enabled || !m->cached_output || m->max_width <= 0)
+ continue;
+ int tw = text_width(module_text(m, mbuf, sizeof mbuf));
+ if (tw <= m->max_width)
+ continue;
+ any = 1;
+ m->scroll_offset += MARQUEE_STEP_PX;
+ }
+ return any;
+}
+
static void pixel_to_xftcolor(unsigned long pixel, XftColor *out)
{
XColor xc = {0};
@@ -150,6 +260,152 @@ static void resolve_module_colours(void)
}
}
+/* release an IMAGE row's loaded XImage (if any), so popup_open() can
+ * safely reload it on every popup open without leaking the previous one */
+static void free_popup_image(PopupItem *it)
+{
+ if (!it->image)
+ return;
+ XDestroyImage((XImage *)it->image);
+ it->image = NULL;
+ it->image_w = it->image_h = 0;
+}
+
+/* box-filter downscale of an RGBA8 buffer (4 bytes/pixel, no row padding)
+ * from sw x sh to dw x dh -- averages every source pixel that falls under
+ * each destination pixel, rather than nearest-neighbour/point sampling,
+ * so shrinking a photo-sized album art down to popup size doesn't alias.
+ * Caller frees the returned buffer with free(). NULL on OOM. */
+static unsigned char *scale_image_rgba(const unsigned char *src, int sw, int sh, int dw, int dh)
+{
+ unsigned char *dst = malloc((size_t)dw * dh * 4);
+ if (!dst)
+ return NULL;
+
+ for (int y = 0; y < dh; y++) {
+ int sy0 = y * sh / dh;
+ int sy1 = (y + 1) * sh / dh;
+ if (sy1 <= sy0) sy1 = sy0 + 1;
+ if (sy1 > sh) sy1 = sh;
+
+ for (int x = 0; x < dw; x++) {
+ int sx0 = x * sw / dw;
+ int sx1 = (x + 1) * sw / dw;
+ if (sx1 <= sx0) sx1 = sx0 + 1;
+ if (sx1 > sw) sx1 = sw;
+
+ long r = 0, g = 0, b = 0, a = 0, n = 0;
+ for (int yy = sy0; yy < sy1; yy++) {
+ const unsigned char *row = src + ((size_t)yy * sw + sx0) * 4;
+ for (int xx = sx0; xx < sx1; xx++, row += 4) {
+ r += row[0]; g += row[1]; b += row[2]; a += row[3];
+ n++;
+ }
+ }
+ unsigned char *out = dst + ((size_t)y * dw + x) * 4;
+ out[0] = (unsigned char)(r / n);
+ out[1] = (unsigned char)(g / n);
+ out[2] = (unsigned char)(b / n);
+ out[3] = (unsigned char)(a / n);
+ }
+ }
+ return dst;
+}
+
+/* number of trailing zero bits in a visual channel mask (e.g. 0x00ff00 -> 8) */
+static int mask_shift(unsigned long mask)
+{
+ int shift = 0;
+ while (mask && !(mask & 1)) { mask >>= 1; shift++; }
+ return shift;
+}
+
+/* number of set bits in a visual channel mask (e.g. 0x00ff00 -> 8) */
+static int mask_bits(unsigned long mask)
+{
+ int bits = 0;
+ while (mask) { bits += (int)(mask & 1); mask >>= 1; }
+ if (bits > 8) bits = 8; /* no real visual exceeds 8 bits/channel */
+ return bits;
+}
+
+/* pack an RGBA8 buffer into a freshly allocated XImage matching the
+ * default visual's actual channel masks/depth (not just assumed 24-bit
+ * TrueColor), so this renders correctly on any visual. Returns NULL on
+ * failure; caller owns the result (free with XDestroyImage()). */
+static XImage *rgba_to_ximage(const unsigned char *rgba, int w, int h)
+{
+ Visual *vis = DefaultVisual(dpy, scr);
+ int depth = DefaultDepth(dpy, scr);
+
+ int red_shift = mask_shift(vis->red_mask), red_bits = mask_bits(vis->red_mask);
+ int green_shift = mask_shift(vis->green_mask), green_bits = mask_bits(vis->green_mask);
+ int blue_shift = mask_shift(vis->blue_mask), blue_bits = mask_bits(vis->blue_mask);
+
+ XImage *img = XCreateImage(dpy, vis, depth, ZPixmap, 0, NULL, w, h, 32, 0);
+ if (!img)
+ return NULL;
+ img->data = malloc((size_t)img->bytes_per_line * h);
+ if (!img->data) {
+ XFree(img);
+ return NULL;
+ }
+
+ for (int y = 0; y < h; y++) {
+ for (int x = 0; x < w; x++) {
+ const unsigned char *px = rgba + ((size_t)y * w + x) * 4;
+ unsigned long rv = px[0] >> (8 - red_bits);
+ unsigned long gv = px[1] >> (8 - green_bits);
+ unsigned long bv = px[2] >> (8 - blue_bits);
+ unsigned long pixel = (rv << red_shift) | (gv << green_shift) | (bv << blue_shift);
+ XPutPixel(img, x, y, pixel);
+ }
+ }
+ return img;
+}
+
+/* decode `path` (any format stb_image supports -- JPEG/PNG/GIF/BMP/...),
+ * scale it down (preserving aspect ratio) to fit within a `box`-pixel
+ * square if larger, and return it as an XImage ready for XPutImage().
+ * NULL on any failure (missing/corrupt/unreadable file). */
+static void *load_scaled_image(const char *path, int box, int *out_w, int *out_h)
+{
+ int iw, ih, comp;
+ unsigned char *pixels = stbi_load(path, &iw, &ih, &comp, 4);
+ if (!pixels)
+ return NULL;
+
+ int dw = iw, dh = ih;
+ if (iw > box || ih > box) {
+ double scale = iw > ih ? (double)box / iw : (double)box / ih;
+ dw = (int)(iw * scale); if (dw < 1) dw = 1;
+ dh = (int)(ih * scale); if (dh < 1) dh = 1;
+ }
+
+ unsigned char *final = pixels;
+ int scaled_ourselves = 0;
+ if (dw != iw || dh != ih) {
+ final = scale_image_rgba(pixels, iw, ih, dw, dh);
+ stbi_image_free(pixels);
+ if (!final)
+ return NULL;
+ scaled_ourselves = 1;
+ }
+
+ XImage *img = rgba_to_ximage(final, dw, dh);
+
+ if (scaled_ourselves)
+ free(final);
+ else
+ stbi_image_free(final);
+
+ if (!img)
+ return NULL;
+ *out_w = dw;
+ *out_h = dh;
+ return img;
+}
+
void cleanup_modules(void)
{
Visual *vis = DefaultVisual(dpy, scr);
@@ -169,8 +425,20 @@ void cleanup_modules(void)
free(config.modules[i].popup_items[j].command);
free(config.modules[i].popup_items[j].label_command);
free(config.modules[i].popup_items[j].set_command);
+ free(config.modules[i].popup_items[j].image_command);
+ free_popup_image(&config.modules[i].popup_items[j]);
+ for (int b = 0; b < config.modules[i].popup_items[j].button_count; b++) {
+ free(config.modules[i].popup_items[j].buttons[b].label);
+ free(config.modules[i].popup_items[j].buttons[b].command);
+ }
+ free(config.modules[i].popup_items[j].buttons);
}
free(config.modules[i].popup_items);
+ for (int j = 0; j < config.modules[i].taskbar_entry_count; j++) {
+ free(config.modules[i].taskbar_entries[j].label);
+ free(config.modules[i].taskbar_entries[j].command);
+ }
+ free(config.modules[i].taskbar_entries);
if (config.modules[i].has_colour)
XftColorFree(dpy, vis, cmap, &config.modules[i].xft_colour);
free(config.modules[i].cached_output);
@@ -330,24 +598,27 @@ static void draw_bar_into(int bar_idx)
int *wd = malloc(name_count * sizeof *wd);
for (int i = 0; i < name_count; i++) {
char tmp[64];
- snprintf(tmp, sizeof tmp, " %s ", names[i]);
+ snprintf(tmp, sizeof tmp, " %s ", workspace_display_name(names[i]));
wd[i] = text_width(tmp);
pos[i] = cur_x;
cur_x += wd[i] + ws_sp;
}
+ int lead_w = text_width(" ");
for (int i = 0; i < name_count; i++) {
char tmp[64];
- snprintf(tmp, sizeof tmp, " %s ", names[i]);
+ const char *inner = workspace_display_name(names[i]);
+ snprintf(tmp, sizeof tmp, " %s ", inner);
+ int draw_x = ink_centered_x(pos[i], wd[i], lead_w, inner);
if (i == current_ws) {
XSetForeground(dpy, gc, config.foreground_colour);
XFillRectangle(dpy, draw, gc, pos[i] - pad,
text_y - font->ascent - pad,
wd[i] + 2 * pad,
font->ascent + font->descent + 2 * pad);
- XftDrawStringUtf8(d, &xft_bg, font, pos[i], text_y,
+ XftDrawStringUtf8(d, &xft_bg, font, draw_x, text_y,
(const FcChar8 *)tmp, strlen(tmp));
} else {
- XftDrawStringUtf8(d, &xft_fg, font, pos[i], text_y,
+ XftDrawStringUtf8(d, &xft_fg, font, draw_x, text_y,
(const FcChar8 *)tmp, strlen(tmp));
}
@@ -423,7 +694,7 @@ static void draw_bar_into(int bar_idx)
const char *out = module_text(m, mbuf, sizeof mbuf);
int tw = text_width(out);
XftColor *col = m->has_colour ? &m->xft_colour : &xft_fg;
- XftDrawStringUtf8(d, col, font, lx, text_y, (const FcChar8 *)out, strlen(out));
+ draw_module_text(d, col, lx, text_y, m, out, tw);
lx += module_slot_width(m, tw) + mod_sp;
}
@@ -436,7 +707,7 @@ static void draw_bar_into(int bar_idx)
const char *out = module_text(m, mbuf, sizeof mbuf);
int tw = text_width(out);
XftColor *col = m->has_colour ? &m->xft_colour : &xft_fg;
- XftDrawStringUtf8(d, col, font, cx, text_y, (const FcChar8 *)out, strlen(out));
+ draw_module_text(d, col, cx, text_y, m, out, tw);
cx += module_slot_width(m, tw) + mod_sp;
}
@@ -449,10 +720,65 @@ static void draw_bar_into(int bar_idx)
const char *out = module_text(m, mbuf, sizeof mbuf);
int tw = text_width(out);
XftColor *col = m->has_colour ? &m->xft_colour : &xft_fg;
- XftDrawStringUtf8(d, col, font, rx, text_y, (const FcChar8 *)out, strlen(out));
+ draw_module_text(d, col, rx, text_y, m, out, tw);
rx += module_slot_width(m, tw) + mod_sp;
}
+ /* taskbar: one clickable, equal-width segment per current-workspace
+ * window, filling whatever's left between the left and right groups
+ * above. Its own cached_output is deliberately left NULL by
+ * update_taskbar() (src/sxbar.c), so it's automatically excluded from
+ * every loop above (all of them skip modules with no cached_output)
+ * -- this is its only rendering path. Ignores its own `align` (a fill
+ * module has no single anchor side); at most one taskbar module can
+ * ever exist (it's a fixed built-in name), hence the early exit once
+ * found. */
+ for (int i = 0; i < config.module_count; i++) {
+ Module *m = &config.modules[i];
+ if (strcmp(m->name, "taskbar") || !m->enabled || m->on_secondary != is_secondary)
+ continue;
+
+ int tb_x = cur_x + total_left;
+ int tb_end = w - total_right - ver_w - 2 * config.text_padding - 2 * pad;
+ int tb_w = tb_end - tb_x;
+ int n = m->taskbar_entry_count;
+ if (tb_w <= 0 || n <= 0)
+ break;
+
+ Window active = None;
+ {
+ Atom at = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
+ Atom ret_type;
+ int fmt;
+ unsigned long nitems, after;
+ unsigned char *adata = NULL;
+ if (XGetWindowProperty(dpy, root, at, 0, 1, False, XA_WINDOW,
+ &ret_type, &fmt, &nitems, &after, &adata) == Success && adata) {
+ active = *(Window *)adata;
+ XFree(adata);
+ }
+ }
+
+ int seg_w = tb_w / n;
+ for (int e = 0; e < n; e++) {
+ TaskbarEntry *ent = &m->taskbar_entries[e];
+ int seg_x = tb_x + e * seg_w;
+ int this_w = (e == n - 1) ? (tb_x + tb_w - seg_x) : seg_w;
+ const char *label = ent->label ? ent->label : "";
+ int lw = text_width(label);
+ int avail = this_w - 2 * pad;
+ if (ent->id == active) {
+ XSetForeground(dpy, gc, config.foreground_colour);
+ XFillRectangle(dpy, draw, gc, seg_x, text_y - font->ascent - pad,
+ this_w, font->ascent + font->descent + 2 * pad);
+ draw_ticker(d, &xft_bg, seg_x + pad, text_y, avail, label, lw, 0);
+ } else {
+ draw_ticker(d, &xft_fg, seg_x + pad, text_y, avail, label, lw, 0);
+ }
+ }
+ break;
+ }
+
/* version (primary bar only) */
if (!is_secondary && config.show_version) {
int vx = w - ver_w - config.text_padding - pad;
@@ -531,7 +857,7 @@ static int workspace_end_x(int is_secondary, int pad, int ws_sp)
for (int i = 0; i < name_count; i++) {
char tmp[64];
- snprintf(tmp, sizeof tmp, " %s ", names[i]);
+ snprintf(tmp, sizeof tmp, " %s ", workspace_display_name(names[i]));
cur_x += text_width(tmp) + ws_sp;
free(names[i]);
}
@@ -604,6 +930,52 @@ static Module *module_at_x(int bar_idx, int x_click, int *out_mx)
return NULL;
}
+/* find which taskbar entry (if any) x_click lands on, mirroring the
+ * bounds computed in draw_bar_into()'s dedicated taskbar block without
+ * doing any of that block's drawing work -- same pattern as
+ * module_at_x()/workspace_end_x() above */
+static TaskbarEntry *taskbar_entry_at_x(int bar_idx, int x_click)
+{
+ Bar *bar = &bars[bar_idx];
+ int is_secondary = bar->is_secondary;
+ int w = monitors[bar->monitor].width - 2 * config.horizontal_padding;
+ const int pad = 5, ws_sp = 10, mod_sp = 20;
+
+ Module *tb = NULL;
+ for (int i = 0; i < config.module_count; i++) {
+ if (!strcmp(config.modules[i].name, "taskbar")) {
+ tb = &config.modules[i];
+ break;
+ }
+ }
+ if (!tb || !tb->enabled || tb->on_secondary != is_secondary || tb->taskbar_entry_count <= 0)
+ return NULL;
+
+ char mbuf[256];
+ int total_left = 0, total_right = 0;
+ for (int i = 0; i < config.module_count; i++) {
+ Module *m = &config.modules[i];
+ if (!m->enabled || !m->cached_output || m->on_secondary != is_secondary)
+ continue;
+ int tw = text_width(module_text(m, mbuf, sizeof mbuf));
+ int slot = module_slot_width(m, tw) + mod_sp;
+ if (m->align == ALIGN_LEFT) total_left += slot;
+ else if (m->align != ALIGN_CENTER) total_right += slot;
+ }
+ int ver_w = (!is_secondary && config.show_version) ? text_width(config.version_text) : 0;
+ int tb_x = workspace_end_x(is_secondary, pad, ws_sp) + total_left;
+ int tb_end = w - total_right - ver_w - 2 * config.text_padding - 2 * pad;
+ if (x_click < tb_x || x_click >= tb_end)
+ return NULL;
+
+ int n = tb->taskbar_entry_count;
+ int seg_w = (tb_end - tb_x) / n;
+ int e = (x_click - tb_x) / (seg_w > 0 ? seg_w : 1);
+ if (e >= n)
+ e = n - 1;
+ return &tb->taskbar_entries[e];
+}
+
/* root-space geometry of a bar window, replicating create_bars()'s formula.
* Kept in sync by hand -- there is no shared helper with create_bars(). */
static void bar_root_geometry(int bar_idx, int *ox, int *oy, int *ow, int *oh)
@@ -628,6 +1000,7 @@ static void bar_root_geometry(int bar_idx, int *ox, int *oy, int *ow, int *oh)
#define POPUP_SLIDER_W 170
#define POPUP_TRACK_H 10
#define POPUP_GAP 4
+#define POPUP_IMAGE_SIZE 160 /* IMAGE rows scale to fit within this square box */
static int popup_row_height(void)
{
@@ -636,9 +1009,11 @@ static int popup_row_height(void)
static int popup_item_height(PopupItem *it)
{
- return it->type == POPUP_ROW_SLIDER
- ? popup_row_height() + POPUP_ROW_PAD + POPUP_TRACK_H + POPUP_ROW_PAD
- : popup_row_height();
+ if (it->type == POPUP_ROW_SLIDER)
+ return popup_row_height() + POPUP_ROW_PAD + POPUP_TRACK_H + POPUP_ROW_PAD;
+ if (it->type == POPUP_ROW_IMAGE)
+ return (it->image_h > 0 ? it->image_h : POPUP_IMAGE_SIZE) + 2 * POPUP_ROW_PAD;
+ return popup_row_height();
}
/* total popup content height across all of a module's rows (text, button
@@ -731,22 +1106,80 @@ static void popup_draw(void)
continue;
}
+ if (it->type == POPUP_ROW_IMAGE) {
+ if (it->image) {
+ int img_x = (popup.w - it->image_w) / 2;
+ int img_y = ry + POPUP_ROW_PAD;
+ XPutImage(dpy, popup.buffer, gc, (XImage *)it->image, 0, 0,
+ img_x, img_y, it->image_w, it->image_h);
+ }
+ continue;
+ }
+
+ if (it->type == POPUP_ROW_BUTTONS) {
+ int n = it->button_count > 0 ? it->button_count : 1;
+ int seg_w = popup.w / n;
+ for (int b = 0; b < it->button_count; b++) {
+ int seg_x = b * seg_w;
+ int this_w = (b == n - 1) ? (popup.w - seg_x) : seg_w;
+ const char *blabel = it->buttons[b].label ? it->buttons[b].label : "";
+ int lw = text_width(blabel);
+ int lx = seg_x + (this_w - lw) / 2;
+ if (i == popup.hover_row && b == popup.hover_col) {
+ XSetForeground(dpy, gc, config.foreground_colour);
+ XFillRectangle(dpy, popup.buffer, gc, seg_x, ry, this_w, popup_row_height());
+ XftDrawStringUtf8(popup.xft_draw, &xft_bg, font, lx, text_y,
+ (const FcChar8 *)blabel, strlen(blabel));
+ } else {
+ XftDrawStringUtf8(popup.xft_draw, &xft_fg, font, lx, text_y,
+ (const FcChar8 *)blabel, strlen(blabel));
+ }
+ }
+ continue;
+ }
+
const char *label = it->label ? it->label : "";
+ int avail = popup.w - 2 * POPUP_PAD;
+ int lw = text_width(label);
if (it->type == POPUP_ROW_BUTTON && i == popup.hover_row) {
int row_h = popup_item_height(it);
XSetForeground(dpy, gc, config.foreground_colour);
XFillRectangle(dpy, popup.buffer, gc, 0, ry, popup.w, row_h);
- XftDrawStringUtf8(popup.xft_draw, &xft_bg, font, POPUP_PAD, text_y,
- (const FcChar8 *)label, strlen(label));
+ draw_ticker(popup.xft_draw, &xft_bg, POPUP_PAD, text_y, avail, label, lw, it->scroll_offset);
} else {
- XftDrawStringUtf8(popup.xft_draw, &xft_fg, font, POPUP_PAD, text_y,
- (const FcChar8 *)label, strlen(label));
+ draw_ticker(popup.xft_draw, &xft_fg, POPUP_PAD, text_y, avail, label, lw, it->scroll_offset);
}
}
XCopyArea(dpy, popup.buffer, popup.win, gc, 0, 0, popup.w, popup.h, 0, 0);
}
+/* advance scroll_offset for every row in the *currently open* popup whose
+ * label overflows the popup's actual width, redraw if any did, and report
+ * that back -- same idea as advance_marquees(), just scoped to whichever
+ * one popup is open right now instead of every bar module */
+static int advance_popup_marquee(void)
+{
+ if (!popup.open)
+ return 0;
+
+ Module *m = popup.module;
+ int avail = popup.w - 2 * POPUP_PAD;
+ int any = 0;
+ for (int i = 0; i < m->popup_item_count; i++) {
+ PopupItem *it = &m->popup_items[i];
+ if (it->type != POPUP_ROW_TEXT && it->type != POPUP_ROW_BUTTON)
+ continue;
+ if (text_width(it->label ? it->label : "") <= avail)
+ continue;
+ any = 1;
+ it->scroll_offset += MARQUEE_STEP_PX;
+ }
+ if (any)
+ popup_draw();
+ return any;
+}
+
/* recompute a slider row's value from a pointer x (popup-window-relative)
* and, if it changed, spawn its set_command with the new value (as "NN%") */
static void popup_slider_set_from_x(int row, int x)
@@ -784,6 +1217,22 @@ static void popup_open(int bar_idx, Module *m, int anchor_x)
int is_secondary = bars[bar_idx].is_secondary;
int bottom_bar = is_secondary ? !config.bottom_bar : config.bottom_bar;
+ /* an IMAGE/SLIDER/BUTTONS row "anchors" the popup's width -- when one
+ * is present, plain TEXT/BUTTON rows (e.g. a track title) no longer
+ * get to stretch the popup wider than that; instead their text is
+ * capped to whatever width the anchor established and scrolls
+ * (marquee) if it doesn't fit -- see popup_draw(). With no such row
+ * present, behaviour is unchanged: the widest row's text sets the
+ * popup's width, same as always. */
+ int has_anchor = 0;
+ for (int i = 0; i < m->popup_item_count; i++) {
+ int t = m->popup_items[i].type;
+ if (t == POPUP_ROW_IMAGE || t == POPUP_ROW_SLIDER || t == POPUP_ROW_BUTTONS) {
+ has_anchor = 1;
+ break;
+ }
+ }
+
int w = POPUP_MIN_W;
for (int i = 0; i < m->popup_item_count; i++) {
PopupItem *it = &m->popup_items[i];
@@ -793,12 +1242,37 @@ static void popup_open(int bar_idx, Module *m, int anchor_x)
if (POPUP_SLIDER_W > w) w = POPUP_SLIDER_W;
continue;
}
+ if (it->type == POPUP_ROW_IMAGE) {
+ free_popup_image(it);
+ char *path = it->image_command ? run_command(it->image_command) : NULL;
+ if (path && *path) {
+ int iw, ih;
+ it->image = load_scaled_image(path, POPUP_IMAGE_SIZE, &iw, &ih);
+ if (it->image) {
+ it->image_w = iw;
+ it->image_h = ih;
+ }
+ }
+ free(path);
+ if (it->image_w + 2 * POPUP_PAD > w) w = it->image_w + 2 * POPUP_PAD;
+ continue;
+ }
+ if (it->type == POPUP_ROW_BUTTONS) {
+ int total = 0;
+ for (int b = 0; b < it->button_count; b++)
+ total += text_width(it->buttons[b].label ? it->buttons[b].label : "") + 2 * POPUP_PAD;
+ if (total > w) w = total;
+ continue;
+ }
if (it->label_command) {
free(it->label);
it->label = run_command(it->label_command);
}
- int tw = text_width(it->label ? it->label : "") + 2 * POPUP_PAD;
- if (tw > w) w = tw;
+ it->scroll_offset = 0; /* restart any marquee fresh on each open */
+ if (!has_anchor) {
+ int tw = text_width(it->label ? it->label : "") + 2 * POPUP_PAD;
+ if (tw > w) w = tw;
+ }
}
int h = popup_total_height(m);
@@ -838,6 +1312,7 @@ static void popup_open(int bar_idx, Module *m, int anchor_x)
popup.trigger = m->popup_trigger;
popup.x = x; popup.y = y; popup.w = w; popup.h = h;
popup.hover_row = -1;
+ popup.hover_col = -1;
popup.dragging_row = -1;
XMapRaised(dpy, win);
@@ -878,6 +1353,16 @@ static void popup_handle_button(XEvent *xev)
popup.dragging_row = row;
popup_slider_set_from_x(row, x);
break;
+ case POPUP_ROW_BUTTONS: {
+ int n = it->button_count > 0 ? it->button_count : 1;
+ int seg = x / (popup.w / n);
+ if (seg >= it->button_count)
+ seg = it->button_count - 1;
+ if (seg >= 0 && it->buttons[seg].command && *it->buttons[seg].command)
+ spawn(it->buttons[seg].command);
+ popup_close();
+ break;
+ }
default:
/* POPUP_ROW_TEXT: purely informational, not clickable at all --
* the popup stays open, nothing happens */
@@ -911,8 +1396,14 @@ void hdl_button(XEvent *xev)
int mx;
Module *m = module_at_x(bar_idx, xev->xbutton.x, &mx);
- if (!m)
+ if (!m) {
+ if (btn == Button1) {
+ TaskbarEntry *ent = taskbar_entry_at_x(bar_idx, xev->xbutton.x);
+ if (ent && ent->command && *ent->command)
+ spawn(ent->command);
+ }
return;
+ }
if (btn == Button1 && m->popup_type != POPUP_NONE && m->popup_trigger == POPUP_TRIGGER_CLICK) {
popup_open(bar_idx, m, mx);
@@ -950,10 +1441,22 @@ void hdl_motion(XEvent *xev)
}
int row = (x >= 0 && y >= 0 && x < popup.w && y < popup.h) ? popup_row_at_y(m, y) : -1;
- if (row >= 0 && m->popup_items[row].type != POPUP_ROW_BUTTON)
- row = -1; /* only BUTTON rows get a hover highlight */
- if (row != popup.hover_row) {
+ int col = -1;
+ if (row >= 0) {
+ int type = m->popup_items[row].type;
+ if (type == POPUP_ROW_BUTTONS) {
+ PopupItem *it = &m->popup_items[row];
+ int n = it->button_count > 0 ? it->button_count : 1;
+ col = x / (popup.w / n);
+ if (col >= it->button_count)
+ col = it->button_count - 1;
+ } else if (type != POPUP_ROW_BUTTON) {
+ row = -1; /* only BUTTON/BUTTONS rows get a hover highlight */
+ }
+ }
+ if (row != popup.hover_row || col != popup.hover_col) {
popup.hover_row = row;
+ popup.hover_col = col;
popup_draw();
}
return;
@@ -1050,230 +1553,78 @@ int find_bar(Window win)
return 0;
}
-static void grow_popup_items_or_die(Module *m)
+/* resolve a built-in module's shell command to a script, checked in this
+ * order: the user's own edited copy under ~/.config/sxbar/scripts/, then
+ * the system-installed reference copy `make install` puts under
+ * /usr/local/share/sxbar/scripts/ (same fallback-path convention as the
+ * config file lookup in parser.c), or a harmless shell no-op if neither
+ * exists yet -- e.g. running straight from a freshly built, not-yet-
+ * installed checkout without having copied any scripts over */
+static char *resolve_script(const char *name)
{
- if (m->popup_item_count < m->popup_item_max)
- return;
- int newmax = m->popup_item_max ? m->popup_item_max * 2 : 4;
- m->popup_items = realloc(m->popup_items, newmax * sizeof *m->popup_items);
- m->popup_item_max = newmax;
+ char path[PATH_MAX];
+ const char *home = getenv("HOME");
+ if (home) {
+ snprintf(path, sizeof path, "%s/.config/sxbar/scripts/%s.sh", home, name);
+ if (access(path, X_OK) == 0)
+ return strdup(path);
+ }
+ snprintf(path, sizeof path, "/usr/local/share/sxbar/scripts/%s.sh", name);
+ if (access(path, X_OK) == 0)
+ return strdup(path);
+ return strdup(":");
}
-/* append a built-in default BUTTON row -- mirrors the parser's popup_item
- * handling but for compile-time defaults */
-static void add_popup_item(Module *m, const char *label, const char *cmd)
-{
- grow_popup_items_or_die(m);
- PopupItem *it = &m->popup_items[m->popup_item_count];
- it->type = POPUP_ROW_BUTTON;
- it->label = strdup(label);
- it->command = strdup(cmd);
- it->label_command = NULL;
- it->set_command = NULL;
- m->popup_item_count++;
-}
-
-/* append a built-in default TEXT row: purely informational, its label is
- * re-run fresh (via label_command) every time the popup opens, and it's
- * not clickable at all -- clicking it does nothing, the popup stays open */
-static void add_popup_info_item(Module *m, const char *label_cmd)
+/* add one built-in module: resolve its script, then let the script itself
+ * declare its popup content (if any) by running `<script> menu` -- see
+ * load_popup_from_script() in parser.c. This is what makes a built-in
+ * module self-contained: sxbarc only ever turns it on/off and tunes its
+ * refresh interval; everything about *how it behaves* (bar text, and now
+ * its popup menu) lives in the module's own script. */
+static void add_builtin_module(const char *name, int enabled, int refresh_interval)
{
- grow_popup_items_or_die(m);
- PopupItem *it = &m->popup_items[m->popup_item_count];
- it->type = POPUP_ROW_TEXT;
- it->label = NULL;
- it->command = NULL;
- it->label_command = strdup(label_cmd);
- it->set_command = NULL;
- m->popup_item_count++;
-}
-
-/* append a built-in default SLIDER row; mirrors the parser's popup_set
- * handling but for compile-time defaults (module has no pre-existing
- * slider row yet, so this always appends rather than updating in place) */
-static void add_popup_slider_item(Module *m, const char *set_cmd)
-{
- grow_popup_items_or_die(m);
- PopupItem *it = &m->popup_items[m->popup_item_count];
- it->type = POPUP_ROW_SLIDER;
- it->label = NULL;
- it->command = NULL;
- it->label_command = NULL;
- it->set_command = strdup(set_cmd);
- it->value = 0;
- it->last_spawned = 0;
- m->slider_item_idx = m->popup_item_count;
- m->popup_item_count++;
- m->popup_type = POPUP_BUTTONS;
+ Module *m = &config.modules[config.module_count++];
+ *m = (Module){.name = strdup(name),
+ .command = resolve_script(name),
+ .enabled = enabled,
+ .refresh_interval = refresh_interval,
+ .last_update = 0,
+ .cached_output = NULL,
+ .slider_item_idx = -1};
+ load_popup_from_script(m, m->command);
}
void init_modules(void)
{
- config.max_modules = 10;
+ config.max_modules = 16; /* headroom beyond the built-ins added below --
+ * grow_modules() (parser.c) takes over for any
+ * further custom modules from sxbarc */
config.modules = malloc(config.max_modules * sizeof(Module));
config.module_count = 0;
- /* clock */
- config.modules[config.module_count++] = (Module){.name = strdup("clock"),
- .command = "date '+%H:%M:%S'",
- .enabled = True,
- .refresh_interval = 1,
- .last_update = 0,
- .cached_output = NULL,
- .slider_item_idx = -1};
- /* date */
- config.modules[config.module_count++] = (Module){.name = strdup("date"),
- .command = "date '+%Y-%m-%d'",
- .enabled = True,
- .refresh_interval = 60,
- .last_update = 0,
- .cached_output = NULL,
- .slider_item_idx = -1};
- /* battery */
- config.modules[config.module_count++] =
- (Module){.name = strdup("battery"),
- /* BAT0 on some machines, BAT1 on others -- glob for whichever exists */
- .command = "cat /sys/class/power_supply/BAT*/capacity 2>/dev/null | "
- "head -n1 | sed 's/$/%/'",
- .enabled = False,
- .refresh_interval = 30,
- .last_update = 0,
- .cached_output = NULL,
- .slider_item_idx = -1};
- /* volume -- hovering reveals a slider; dragging it runs its set_command */
- config.modules[config.module_count++] =
- (Module){.name = strdup("volume"),
- /* awk does the arithmetic itself; no bc/bash/xargs needed */
- .command = "LC_ALL=C wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null | "
- "LC_ALL=C awk '/Volume:/ {printf \"%d%%\\n\", $2 * 100}'",
- .enabled = True,
- .refresh_interval = 5,
- .last_update = 0,
- .cached_output = NULL,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- add_popup_slider_item(&config.modules[config.module_count - 1],
- "wpctl set-volume @DEFAULT_AUDIO_SINK@");
- /* cpu -- hovering reveals more system info (cpu + memory + per-core load) */
- config.modules[config.module_count++] =
- (Module){.name = strdup("cpu"),
- /* two /proc/stat samples -- top(1)'s output is localised and unparseable */
- .command = "{ grep -m1 '^cpu ' /proc/stat; sleep 0.2; "
- "grep -m1 '^cpu ' /proc/stat; } | LC_ALL=C awk "
- "'NR==1{for(i=2;i<=8;i++)t1+=$i; d1=$5+$6} "
- "NR==2{for(i=2;i<=8;i++)t2+=$i; d2=$5+$6; d=t2-t1; "
- "printf \"%d%%\\n\", (d>0 ? (1-(d2-d1)/d)*100 : 0)}'",
- .enabled = False,
- .refresh_interval = 3,
- .last_update = 0,
- .cached_output = NULL,
- .popup_type = POPUP_BUTTONS,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- {
- Module *cpu = &config.modules[config.module_count - 1];
- add_popup_info_item(cpu,
- "{ grep -m1 '^cpu ' /proc/stat; sleep 0.2; grep -m1 '^cpu ' /proc/stat; } | "
- "LC_ALL=C awk 'NR==1{for(i=2;i<=8;i++)t1+=$i; d1=$5+$6} "
- "NR==2{for(i=2;i<=8;i++)t2+=$i; d2=$5+$6; d=t2-t1; "
- "printf \"CPU: %d%%\\n\", (d>0 ? (1-(d2-d1)/d)*100 : 0)}'");
- add_popup_info_item(cpu, "LC_ALL=C free -h | awk '/^Mem:/{print \"Mem: \" $3\"/\"$2}'");
- /* per-core load: two /proc/stat samples paired up by position via
- * awk arrays (no process substitution -- /bin/sh may be dash) */
- add_popup_info_item(cpu,
- "a=$(grep '^cpu[0-9]' /proc/stat); n=$(printf '%s\\n' \"$a\" | wc -l); "
- "sleep 0.2; b=$(grep '^cpu[0-9]' /proc/stat); "
- "printf '%s\\n%s\\n' \"$a\" \"$b\" | LC_ALL=C awk -v n=\"$n\" "
- "'NR<=n{t1[NR]=0; for(i=2;i<=8;i++)t1[NR]+=$i; d1[NR]=$5+$6; name[NR]=$1} "
- "NR>n{j=NR-n; t2=0; for(i=2;i<=8;i++)t2+=$i; d2=$5+$6; d=t2-t1[j]; "
- "pct=(d>0)?(1-(d2-d1[j])/d)*100:0; gsub(/cpu/,\"\",name[j]); "
- "printf \"%s:%d%% \", name[j], pct} "
- "BEGIN{printf \"Cores: \"} END{print \"\"}'");
- }
- /* brightness -- hovering reveals a slider; dragging it runs its set_command */
- config.modules[config.module_count++] =
- (Module){.name = strdup("brightness"),
- .command = "brightnessctl -m 2>/dev/null | awk -F, '{print $4}'",
- .enabled = False,
- .refresh_interval = 5,
- .last_update = 0,
- .cached_output = NULL,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- add_popup_slider_item(&config.modules[config.module_count - 1], "brightnessctl set");
- /* bluetooth -- hovering reveals a floating menu: power on/off, scan, pair */
- config.modules[config.module_count++] =
- (Module){.name = strdup("bluetooth"),
- .command = "bluetoothctl show 2>/dev/null | grep -q 'Powered: yes' && "
- "echo 'On' || echo 'Off'",
- .enabled = False,
- .refresh_interval = 10,
- .last_update = 0,
- .cached_output = NULL,
- .popup_type = POPUP_BUTTONS,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- {
- Module *bt = &config.modules[config.module_count - 1];
- add_popup_item(bt, "Turn on", "bluetoothctl power on");
- add_popup_item(bt, "Turn off", "bluetoothctl power off");
- add_popup_item(bt, "Search for devices", "bluetoothctl --timeout 10 scan on");
- add_popup_item(bt, "Pair last found device",
- "m=$(bluetoothctl devices | tail -n1 | awk '{print $2}'); "
- "[ -n \"$m\" ] && bluetoothctl pair \"$m\" && bluetoothctl trust \"$m\" "
- "&& bluetoothctl connect \"$m\"");
- }
- /* usermenu -- hovering reveals a floating menu: sleep, log out, shut down */
- config.modules[config.module_count++] =
- (Module){.name = strdup("usermenu"),
- .command = "whoami",
- .enabled = True,
- .refresh_interval = 300,
- .last_update = 0,
- .cached_output = NULL,
- .popup_type = POPUP_BUTTONS,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- {
- Module *um = &config.modules[config.module_count - 1];
- add_popup_item(um, "Sleep", "systemctl suspend");
- /* sxwm (https://github.com/uint23/sxwm) has no session manager or
- * external IPC to trigger its own `quit` keybind, so logging out
- * means ending the X session by killing the WM -- adjust for your
- * own WM/session via popup_item in sxbarc if this doesn't fit */
- add_popup_item(um, "Log out", "pkill sxwm");
- add_popup_item(um, "Shut down", "systemctl poweroff");
- }
- /* network -- hovering reveals a floating menu showing WiFi/Ethernet + IPs */
- config.modules[config.module_count++] =
- (Module){.name = strdup("network"),
- .command = "ip route show default 2>/dev/null | grep -q . && echo Online || echo Offline",
- .enabled = False,
- .refresh_interval = 10,
- .last_update = 0,
- .cached_output = NULL,
- .popup_type = POPUP_BUTTONS,
- .popup_trigger = POPUP_TRIGGER_HOVER,
- .slider_item_idx = -1};
- {
- Module *net = &config.modules[config.module_count - 1];
- /* wifi: first interface with a /sys/class/net/<if>/wireless dir */
- add_popup_info_item(net,
- "i=$(for d in /sys/class/net/*/wireless; do [ -d \"$d\" ] && "
- "basename \"$(dirname \"$d\")\" && break; done); "
- "if [ -z \"$i\" ]; then echo 'WiFi: none'; else "
- "ip=$(ip -4 -o addr show \"$i\" 2>/dev/null | awk '{print $4}' | cut -d/ -f1); "
- "[ -n \"$ip\" ] && echo \"WiFi ($i): $ip\" || echo \"WiFi ($i): disconnected\"; fi");
- /* ethernet: first non-virtual, non-wireless interface of ARPHRD_ETHER type */
- add_popup_info_item(net,
- "i=$(for d in /sys/class/net/*; do n=$(basename \"$d\"); "
- "case \"$n\" in lo|docker*|veth*|br-*|virbr*|tun*|tap*) continue;; esac; "
- "[ -d \"$d/wireless\" ] && continue; "
- "[ \"$(cat \"$d/type\" 2>/dev/null)\" = \"1\" ] && echo \"$n\" && break; done); "
- "if [ -z \"$i\" ]; then echo 'Ethernet: none'; else "
- "ip=$(ip -4 -o addr show \"$i\" 2>/dev/null | awk '{print $4}' | cut -d/ -f1); "
- "[ -n \"$ip\" ] && echo \"Ethernet ($i): $ip\" || echo \"Ethernet ($i): disconnected\"; fi");
- }
+ add_builtin_module("clock", True, 1);
+ add_builtin_module("date", True, 60);
+ add_builtin_module("battery", False, 30);
+ add_builtin_module("volume", True, 5);
+ add_builtin_module("cpu", False, 3);
+ add_builtin_module("brightness", False, 5);
+ add_builtin_module("bluetooth", False, 10);
+ /* usermenu -- sxwm (https://github.com/uint23/sxwm) has no session
+ * manager or external IPC to trigger its own `quit` keybind, so the
+ * default "Log out" row (in scripts/usermenu.sh) ends the X session by
+ * killing the WM -- edit your own copy under ~/.config/sxbar/scripts/
+ * if this doesn't fit your WM/session, or add more rows of your own. */
+ add_builtin_module("usermenu", True, 300);
+ add_builtin_module("network", False, 10);
+ /* media -- MPRIS controls via playerctl; popup shows album art (needs
+ * curl for remote art URLs) plus Previous/Play-Pause/Next buttons */
+ add_builtin_module("media", False, 2);
+ /* taskbar -- one clickable entry per window on the current workspace,
+ * rendered directly in the bar rather than a popup (see the dedicated
+ * block in draw_bar_into()); needs wmctrl, and a window manager that
+ * acts on _NET_ACTIVE_WINDOW client messages to actually focus what
+ * you click (see scripts/taskbar.sh) */
+ add_builtin_module("taskbar", False, 1);
}
unsigned long parse_col(const char *hex)
@@ -1298,13 +1649,27 @@ void run(void)
evtable[xev.type](&xev);
}
time_t now = time(NULL);
- if (now - last >= 1) {
+ int due = now - last >= 1;
+ if (due)
update_modules();
+
+ /* redraw every ~100ms tick while any module's text is actively
+ * scrolling (marquee), so it animates smoothly; otherwise just
+ * once a second like before -- advance_marquees() only ever
+ * reports true for modules with max_width set and overflowing, so
+ * this changes nothing for a config that doesn't use it */
+ int scrolling = advance_marquees();
+ if (due || scrolling) {
for (int i = 0; i < nbars; i++) {
redraw_bar(i);
}
- last = now;
}
+ /* same idea for whichever popup is currently open, if any -- it
+ * redraws itself directly (it's a separate window from the bars) */
+ advance_popup_marquee();
+ if (due)
+ last = now;
+
struct timespec ts = {0, 100000000};
nanosleep(&ts, NULL);
}
@@ -1361,6 +1726,104 @@ static char *shell_quote(const char *s)
return out;
}
+static void free_taskbar_entries(Module *m)
+{
+ for (int i = 0; i < m->taskbar_entry_count; i++) {
+ free(m->taskbar_entries[i].label);
+ free(m->taskbar_entries[i].command);
+ }
+ free(m->taskbar_entries);
+ m->taskbar_entries = NULL;
+ m->taskbar_entry_count = 0;
+}
+
+/* parses one "A" : "B" : "C" line -- the internal wire format
+ * scripts/taskbar.sh's listing uses, not a user-facing sxbarc directive,
+ * so this doesn't reuse parser.c's quote-parsing (scoped to config-file
+ * directives). Outputs a/b/c are malloc'd (strdup) on success (0); returns -1
+ * without allocating anything if the line doesn't match, so the caller
+ * can just skip it. */
+static int parse_three_quoted(char *line, char **a, char **b, char **c)
+{
+ char *p = line;
+ char *fields[3];
+ for (int i = 0; i < 3; i++) {
+ while (*p == ' ' || *p == '\t')
+ p++;
+ if (*p != '"')
+ return -1;
+ p++;
+ char *start = p;
+ char *end = strchr(p, '"');
+ if (!end)
+ return -1;
+ *end = '\0';
+ fields[i] = start;
+ p = end + 1;
+ while (*p == ' ' || *p == '\t')
+ p++;
+ if (i < 2) {
+ if (*p != ':')
+ return -1;
+ p++;
+ }
+ }
+ *a = strdup(fields[0]);
+ *b = strdup(fields[1]);
+ *c = strdup(fields[2]);
+ return 0;
+}
+
+/* refreshes the built-in `taskbar` module's window-entry list by running
+ * its script with "list" appended and parsing each line as "Title" :
+ * "0xWindowID" : "command" -- see scripts/taskbar.sh. Unlike every other
+ * module, m->cached_output is deliberately left NULL: every generic
+ * per-module code path (draw_bar_into()'s layout/rendering loops,
+ * module_at_x(), advance_marquees()) already skips modules with no
+ * cached_output, which is exactly what we want here, since taskbar
+ * renders itself in its own dedicated block/click-handling instead. */
+static void update_taskbar(Module *m)
+{
+ char cmd[PATH_MAX + 8];
+ snprintf(cmd, sizeof cmd, "%s list", m->command);
+
+ FILE *fp = popen(cmd, "r");
+ if (!fp)
+ return;
+
+ free_taskbar_entries(m);
+ int max = 0;
+ char line[1024];
+ while (fgets(line, sizeof line, fp)) {
+ char *nl = strchr(line, '\n');
+ if (nl)
+ *nl = '\0';
+
+ char *title, *idstr, *action;
+ if (parse_three_quoted(line, &title, &idstr, &action) < 0)
+ continue;
+
+ if (m->taskbar_entry_count >= max) {
+ int newmax = max ? max * 2 : 4;
+ TaskbarEntry *tmp = realloc(m->taskbar_entries, newmax * sizeof *tmp);
+ if (!tmp) {
+ free(title);
+ free(idstr);
+ free(action);
+ break;
+ }
+ m->taskbar_entries = tmp;
+ max = newmax;
+ }
+ TaskbarEntry *e = &m->taskbar_entries[m->taskbar_entry_count++];
+ e->label = title;
+ e->command = action;
+ e->id = (Window)strtoul(idstr, NULL, 0); /* base 0: "0x..." parses as hex */
+ free(idstr);
+ }
+ pclose(fp);
+}
+
void update_modules(void)
{
time_t now = time(NULL);
@@ -1370,6 +1833,12 @@ void update_modules(void)
continue;
}
if (now - m->last_update >= m->refresh_interval) {
+ if (!strcmp(m->name, "taskbar")) {
+ update_taskbar(m);
+ m->last_update = now;
+ continue;
+ }
+
free(m->cached_output);
m->cached_output = run_command(m->command);
diff --git a/sxbar.1 b/sxbar.1
index e69de29..7d4355d 100644
--- a/sxbar.1
+++ b/sxbar.1
@@ -0,0 +1,491 @@
+.TH SXBAR 1 "2026-07-29" "sxbar 1.1" "User Commands"
+.SH NAME
+sxbar \- a small, fast EWMH status bar for Xorg
+.SH SYNOPSIS
+.B sxbar
+.br
+.B sxbar
+.RB { \-v | \-\-version }
+.SH DESCRIPTION
+.B sxbar
+is a single C99 binary that draws an EWMH workspace switcher plus a row of
+modules \(en clock, battery, volume, custom shell commands, anything you
+configure \(en on one bar per monitor (detected via Xinerama). Modules can
+open a small floating popup window on hover or click, containing text rows,
+button rows, a draggable slider row, or an image row (e.g. album art).
+.PP
+Everything is controlled by a single plain-text configuration file; there is
+nothing to recompile to add or remove a module, change colours/icons, wire
+up click actions, or define a popup menu.
+.B sxbar
+re-reads its configuration once, at startup \(en it is not live-reloaded.
+.SH OPTIONS
+.TP
+.BR \-v ", " \-\-version
+Print the version, author and licence line, then exit.
+.SH CONFIGURATION FILE
+The config file is searched for, in this order, and the first one found is
+used:
+.RS
+.IP \(bu 2
+.I $XDG_CONFIG_HOME/sxbarc
+.IP \(bu 2
+.I $XDG_CONFIG_HOME/sxbar/sxbarc
+.IP \(bu 2
+.I ~/.config/sxbarc
+.IP \(bu 2
+.I ~/.config/sxbar/sxbarc
+.IP \(bu 2
+.I /usr/local/share/sxbarc
+(the system-wide fallback \fBmake install\fP places; see \fBFILES\fP)
+.RE
+.PP
+Syntax is line-oriented,
+.IR "key : value" ,
+with extra
+.I : name
+fields for directives that target one module. A
+.B #
+starts a trailing comment, except as the very first character of a value
+(so hex colours like
+.I #50fa7b
+are not treated as comments). Blank lines are ignored. A leading
+.B ~/
+in any command or path value is expanded to
+.IR $HOME/ .
+.SH GLOBAL OPTIONS
+Set once, apply to every bar unless noted.
+.TP
+.B height : pixels
+Bar height. Default 19.
+.TP
+.B bottom_bar : true|false
+Dock at the screen bottom instead of the top. Default false.
+.TP
+.B vertical_padding : pixels
+Gap between the bar and the screen edge it's docked to. Default 0.
+.TP
+.B horizontal_padding : pixels
+Gap on both sides of the bar. Default 0.
+.TP
+.B text_padding : pixels
+Inner padding before the first workspace/module. Default 0.
+.TP
+.B border : true|false
+.TQ
+.B border_width : pixels
+Draw a border around the bar window. Default false / 0.
+.TP
+.BR background_colour " (or " background_color ") : " #rrggbb|X-colour-name
+.TQ
+.BR foreground_colour " (or " foreground_color ") : " #rrggbb|X-colour-name
+.TQ
+.BR border_colour " (or " border_color ") : " #rrggbb|X-colour-name
+Bar colours. Defaults #000000, #7abccd, #005577. Unlike most other keys,
+these three do not support a trailing
+.I "# comment"
+on the same line \(en put comments on their own line instead.
+.TP
+.B font : "Family:size=N[:style=Bold]"
+Xft font name. Use a Nerd Font family here to render icon glyphs used by
+.B prefix / prefix_cmd
+below. Default monospace:size=10.
+.TP
+.B show_version : true|false
+.TQ
+.B version_text : "text"
+Optional version string shown at the primary bar's right edge. Default
+true / "sxbar ver. 1.1".
+.TP
+.B secondary_bar : true|false
+Adds a second, modules-only bar on the edge opposite
+.BR bottom_bar ,
+with no workspace switcher and no version text \(en only modules tagged
+.B "bar : name : secondary"
+are drawn on it, everything else stays on the primary bar. Default false.
+.SH WORKSPACES & MONITORS
+The workspace switcher reads standard EWMH properties
+.RI ( _NET_DESKTOP_NAMES ", " _NET_CURRENT_DESKTOP ", " _NET_CLIENT_LIST ", "
+.IR _NET_WM_DESKTOP ),
+so it works with any EWMH-compliant window manager with no sxbar-specific
+setup. One bar opens per monitor automatically via Xinerama; each workspace
+pill shows up to 4 small boxes for windows on that workspace, counted only
+for windows actually on that bar's own monitor.
+.TP
+.BR "workspace_icon : name : \(dqicon text\(dq"
+Replaces a workspace's displayed label \(en its
+.I _NET_DESKTOP_NAMES
+string, typically a plain number like
+.IR \(dq1\(dq " -- with different text instead, e.g. a Nerd Font glyph."
+Purely cosmetic: switching still targets the same underlying desktop,
+only what's drawn changes. Needs a Nerd Font set via
+.B font
+to render glyphs. Repeatable, one line per workspace; any workspace
+without a matching line just shows its plain name.
+.SH BUILT-IN MODULES
+Enabled with
+.BR "module : name : true|false : refresh_interval_seconds" .
+Available names:
+.BR clock ", " date ", " battery ", " volume ", " cpu ", " brightness ", "
+.BR bluetooth ", " usermenu ", " network ", " media .
+.PP
+Each resolves its bar-text command, and its popup content (see
+.B POPUPS
+below), to a script rather than code built into the binary \(en checked in
+this order: your own copy at
+.IR ~/.config/sxbar/scripts/ name .sh ,
+then the system copy at
+.IR /usr/local/share/sxbar/scripts/ name .sh ,
+or a harmless no-op if neither exists. Copy any of them over and edit; no
+config line or recompile is needed, sxbar picks up your copy on the next
+restart.
+.TP
+.B clock
+Bar text: current time (HH:MM:SS). Popup: "Open calendar" (needs
+.BR gsimplecal ).
+.TP
+.B date
+Bar text: current date (YYYY-MM-DD). Popup: "Open calendar" (needs
+.BR gsimplecal ).
+.TP
+.B battery
+Bar text: charge percentage, from
+.IR /sys/class/power_supply .
+Popup: detailed status line and a "Toggle power saver" button (needs
+.B upower
+and
+.BR power-profiles-daemon ).
+.TP
+.B volume
+Bar text: volume percentage (needs
+.BR wpctl ).
+Popup: a draggable slider.
+.TP
+.B cpu
+Bar text: overall CPU usage percentage, sampled from
+.IR /proc/stat .
+Popup: usage, memory (used/total), and a per-core breakdown.
+.TP
+.B brightness
+Bar text: screen brightness percentage (needs
+.BR brightnessctl ).
+Popup: a draggable slider.
+.TP
+.B bluetooth
+Bar text: adapter power state, On/Off (needs
+.BR bluetoothctl ).
+Popup: Turn on, Turn off, Search for devices, and Pair last found device
+(the most recently seen device \(en no interactive device list).
+.TP
+.B usermenu
+Bar text: current username. Popup: Sleep
+.RI ( "systemctl suspend" ),
+Log out
+.RI ( "pkill <your WM>" ", " sxwm " by default), and Shut down ("
+.IR "systemctl poweroff" ).
+Add, remove or reorder rows by editing your own copy of
+.I usermenu.sh
+directly \(en see
+.B POPUPS
+below.
+.TP
+.B network
+Bar text: Online/Offline, based on whether a default route exists (needs
+.BR ip ).
+Popup: first WiFi interface + its IPv4, and first wired Ethernet interface
++ its IPv4 (or "none"/"disconnected").
+.TP
+.B media
+Bar text: a play/pause glyph plus "Artist - Title" (needs
+.BR playerctl ,
+controlling whichever player it considers active). Popup: album art (a
+.B popup_image
+row; remote art URLs need
+.B curl
+to download and cache), track info, and Previous/Play-Pause/Next buttons.
+.TP
+.B taskbar
+Not like the other modules: renders one clickable segment per window on
+the current workspace directly in the bar, instead of one line of text.
+See
+.B TASKBAR
+below.
+.SH TASKBAR
+.B taskbar
+shows one clickable segment per window on the current workspace, so you
+can switch focus between them \(en the motivating case being a window
+manager's monocle mode, where only one window is visible at a time.
+Typical setup is its own row on the secondary bar:
+.RS
+.nf
+secondary_bar : true
+module : taskbar : true : 1
+bar : taskbar : secondary
+.fi
+.RE
+.PP
+Needs
+.BR wmctrl ,
+for both listing windows and requesting focus, and a window manager that
+actually acts on a
+.I _NET_ACTIVE_WINDOW
+client message (what
+.B "wmctrl -i -a"
+sends to request focus). sxwm, as of this writing, does not out of the
+box \(en see
+.I patches/net-active-window-mrjensk.patch
+in the sxwm repo, which adds that handling by reusing sxwm's own
+.IR set_input_focus() ,
+the same function
+.IR focus_next / focus_prev
+already use. Other window managers may already support this; check
+yours.
+.PP
+Ignores its own
+.B align
+\(en as a fill module, it always occupies whatever space is left between
+the left- and right-aligned modules on its bar, split into equal-width
+segments, rather than anchoring to one side. The currently-focused
+window's segment is highlighted the same way the active workspace pill
+is.
+.SH CUSTOM MODULES
+.B custom : name : "command" : refresh_interval_seconds
+runs an arbitrary shell command on its own interval; its stdout (trailing
+newline stripped) is the bar text. Every other directive on this page
+.RB ( prefix ", " colour ", " click ", " popup ", etc.) works on a custom"
+module by the name given here, exactly as on a built-in one.
+.SH ICONS, COLOUR, LAYOUT, CLICKS
+These apply to any module, built-in or custom, by name.
+.TP
+.BR "prefix : name : \(dqtext\(dq" " (or " icon )
+Static text prepended to the module's output. Needs a Nerd Font set via
+.B font
+to render glyphs.
+.TP
+.BR "prefix_cmd : name : \(dqcommand\(dq" " (or " icon_cmd )
+Like
+.B prefix
+but the icon comes from a script instead of fixed text, so it can change
+with module state (e.g. battery charging, volume muted). Re-run on the
+module's own refresh interval; the module's current bar-text output is
+passed in as
+.IR $1 .
+Its stdout (no trailing newline) becomes the prefix verbatim, so include
+your own trailing separator if you want one.
+.TP
+.BR "colour : name : #rrggbb" " (or " color )
+Overrides
+.B foreground_colour
+for one module.
+.TP
+.B width : name : min_pixels
+Reserves a minimum pixel width for the module's slot so neighbours don't
+shift as its text width changes. Text itself is never truncated.
+.TP
+.B max_width : name : max_pixels
+The opposite of
+.BR width :
+caps the module's slot at this many pixels. Text that fits draws as
+normal; text wider than the cap scrolls left (a marquee/ticker) within
+that fixed width instead of stretching the bar. sxbar only redraws faster
+than its usual once-a-second cadence while something is actually
+scrolling, so this costs nothing when nothing overflows.
+.TP
+.B bar : name : primary|secondary
+Which bar the module is drawn on when
+.B secondary_bar
+is enabled. Default primary.
+.TP
+.B align : name : left|center|right
+Which side of the bar the module is anchored to; each group is laid out
+independently. Default right.
+.TP
+.B icon_only : name : true|false
+Shows only the prefix/icon, hiding the module's own rendered text. The
+underlying command, refresh interval and popup still run as normal. Needs
+a
+.B prefix
+or
+.B prefix_cmd
+set, or there is nothing left to show.
+.TP
+.BR "click : name : \(dqcommand\(dq"
+Runs a command, detached, on left-click. Ignored for a module whose popup
+trigger is
+.BR click ,
+since the popup takes over left-click there.
+.TP
+.BR "scroll_up : name : \(dqcommand\(dq"
+.TQ
+.BR "scroll_down : name : \(dqcommand\(dq"
+Run a command on scrolling up/down over the module; work independently of
+any popup.
+.SH POPUPS
+A module can open a small floating window instead of, or as well as,
+running a plain
+.B click
+command. Only one popup is open at a time.
+.TP
+.B popup : name : hover|click : buttons|slider
+.B hover
+opens the popup while the pointer is over the module, closing it when the
+pointer leaves both the module and the popup;
+.B click
+opens it on left-click and closes it again on a second click, on clicking a
+button row, or on clicking elsewhere. The third field only decides whether
+the module has a popup at all \(en
+.BR popup_item / popup_info / popup_set
+below decide what is actually in it, in any combination, so either word
+works there.
+.TP
+.BR "popup_item : name : \(dqLabel\(dq : \(dqcommand\(dq"
+A button row: runs
+.I command
+(detached) and closes the popup, on click. Repeatable.
+.TP
+.BR "popup_info : name : \(dqcommand\(dq"
+A purely informational text row: its label is
+.IR command 's
+output, re-run fresh every time the popup opens. Not clickable at all.
+Repeatable.
+.TP
+.BR "popup_image : name : \(dqcommand\(dq"
+An image row (e.g. album art):
+.IR command 's
+stdout is a path to a local image file, re-run fresh every time the popup
+opens; scaled down, preserving aspect ratio, to fit within a 160-pixel
+square box if larger. Empty or failed output just means no image that
+time \(en the row stays, it renders blank. Not clickable. Needs no extra
+library: image decoding is vendored and compiled into
+.BR sxbar .
+An image row (like a slider or
+.B popup_buttons
+row) anchors the popup's width \(en any
+.B popup_info
+or
+.B popup_item
+text in the same popup is then capped to that width and scrolls instead
+of stretching the popup past it.
+.TP
+.BI "popup_buttons : name : \(dqLabel1\(dq : \(dqcommand1\(dq : \(dqLabel2\(dq : \(dqcommand2\(dq " ...
+One row split into N equal-width button segments side by side, e.g. media
+transport controls, instead of N stacked full-width
+.B popup_item
+rows. Needs an even number of quoted label/command pairs; each segment
+runs its own command and closes the popup on click, same as
+.BR popup_item .
+Glyphs work well as segment labels here.
+.TP
+.BR "popup_set : name : \(dqcommand\(dq"
+Adds (or updates) one draggable 0\(en100% slider row.
+.I command
+is run when the value changes, receiving the new value as
+.I $1
+(e.g.
+.IR 45% ,
+same convention as
+.BR prefix_cmd ).
+The slider's starting position comes from the module's own bar-text
+command output, so no separate "get" command is needed.
+.PP
+Text, button, slider, image and segmented-button rows can be mixed freely
+in the same popup. The first
+.BR popup_item ,
+.BR popup_info ,
+.B popup_image
+or
+.B popup_buttons
+line for a given module replaces its current default rows (including any
+.B popup_set
+slider row); later lines for that module append instead. Add
+.B popup_set
+again afterwards if you cleared a slider row this way and still want one.
+.SS Module-declared menus
+A built-in module's default popup content is not compiled into the binary:
+it comes from that module's own script, run once at startup as
+.IR "<script> menu" .
+That subcommand prints the exact same
+.BR popup / popup_item / popup_info / popup_image / popup_buttons / popup_set
+directives described above, just without the
+.I name
+field, since a script only ever describes itself. For example,
+.I usermenu.sh menu
+prints:
+.RS
+.nf
+popup : hover : buttons
+popup_item : "Sleep" : "systemctl suspend"
+popup_item : "Log out" : "pkill sxwm"
+popup_item : "Shut down" : "systemctl poweroff"
+.fi
+.RE
+.PP
+To add your own entry to the user menu, edit the
+.B menu)
+case in your own copy of
+.I ~/.config/sxbar/scripts/usermenu.sh
+and add another
+.B popup_item
+line \(en no sxbarc editing needed. The sxbarc directives above still work
+exactly as documented and can still override a script's menu wholesale, if
+you would rather keep everything in one config file. A
+.B custom
+module has no script to load a menu from, so give it a popup via the
+sxbarc directives instead.
+.SH FILES
+.TP
+.I ~/.config/sxbarc, ~/.config/sxbar/sxbarc
+User configuration file (see search order above).
+.TP
+.I ~/.config/sxbar/scripts/<name>.sh
+Your own edited copy of a built-in module's script, or of a
+.B prefix_cmd
+icon script; checked before the installed system copy.
+.TP
+.I $PREFIX/bin/sxbar
+The installed binary.
+.TP
+.I $PREFIX/share/man/man1/sxbar.1
+This man page.
+.TP
+.I $PREFIX/share/sxbarc
+System-wide fallback default configuration.
+.TP
+.I $PREFIX/share/sxbar/scripts/
+Reference copies of every built-in module's script, plus the
+.IR battery_icon.sh / volume_icon.sh
+prefix_cmd examples and the
+.I demo_popup.sh
+try-it-yourself popup script. Copy any of these to
+.I ~/.config/sxbar/scripts/
+and edit freely.
+.TP
+.I $XDG_CACHE_HOME/sxbar-media-art/ (or ~/.cache/sxbar-media-art/)
+Downloaded album art cache, populated by
+.IR "media.sh art" ,
+one file per remote artwork URL.
+.PP
+.I $PREFIX
+defaults to
+.IR /usr/local .
+.SH EXAMPLE
+.nf
+module : clock : true : 1
+module : battery : true : 30
+module : volume : true : 5
+
+prefix : clock : " "
+colour : clock : #50fa7b
+
+scroll_up : volume : "wpctl set-volume --limit 1.0 @DEFAULT_AUDIO_SINK@ 5%+"
+scroll_down : volume : "wpctl set-volume @DEFAULT_AUDIO_SINK@ 5%-"
+
+custom : mem : "free -h | awk '/^Mem:/{print $3\\"/\\"$2}'" : 10
+.fi
+.SH AUTHOR
+Abhinav Prasai
+.SH SEE ALSO
+Full directive reference and worked examples ship in this repository's
+.I README.md
+and
+.IR docs/wiki.html .