diff --git a/.gitignore b/.gitignore index b60ec17..806b78e 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ node_modules/ .mooncakes/ *.log host-native/target/ +.pixi/ diff --git a/assets/fonts/AdwaitaMono-Bold.ttf b/assets/fonts/AdwaitaMono-Bold.ttf new file mode 100644 index 0000000..8ee6428 Binary files /dev/null and b/assets/fonts/AdwaitaMono-Bold.ttf differ diff --git a/assets/fonts/AdwaitaMono-Regular.ttf b/assets/fonts/AdwaitaMono-Regular.ttf new file mode 100644 index 0000000..89363f2 Binary files /dev/null and b/assets/fonts/AdwaitaMono-Regular.ttf differ diff --git a/assets/fonts/AdwaitaSans-Regular.ttf b/assets/fonts/AdwaitaSans-Regular.ttf new file mode 100644 index 0000000..6fcafd9 Binary files /dev/null and b/assets/fonts/AdwaitaSans-Regular.ttf differ diff --git a/assets/fonts/AlloVariable.ttf b/assets/fonts/AlloVariable.ttf new file mode 100644 index 0000000..c3f8b4d Binary files /dev/null and b/assets/fonts/AlloVariable.ttf differ diff --git a/assets/fonts/LICENSE b/assets/fonts/LICENSE new file mode 100644 index 0000000..6dc188d --- /dev/null +++ b/assets/fonts/LICENSE @@ -0,0 +1,96 @@ +Copyright (c) 2016, The Inter Project Authors (https://github.com/rsms/inter) +Copyright (c) 2015-2025, Renzhi Li (aka. Belleve Invis, belleve@typeof.net) +Copyright (c) 2025, Jamie Gravendeel (https://jamie.garden) +Copyright (c) 2025, Florian Müllner + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/compositor/bin/main.mbt b/compositor/bin/main.mbt index d762e7e..c8ad670 100644 --- a/compositor/bin/main.mbt +++ b/compositor/bin/main.mbt @@ -6,6 +6,7 @@ fn main { let mut socket_path = "/tmp/wayland-moon-0" let mut theme_path = "config/themes/moon-night.json" let mut gfx_out = "" + let widgets : Array[String] = [] let mut windowed = false let mut drm = false let mut width = 1280 @@ -26,6 +27,9 @@ fn main { } else if a == "--drm" { drm = true i = i + 1 + } else if a == "--widget" && i + 1 < args.length() { + widgets.push(args[i + 1]) + i = i + 2 } else if a == "--gfx-out" && i + 1 < args.length() { gfx_out = args[i + 1] i = i + 2 @@ -71,6 +75,14 @@ fn main { match @host.MoonPlasmaCompositor::new(socket_path, theme, width, height) { Some(comp) => { + comp.shell.persist = true // remember which modules are loaded in the panel + comp.shell.screen_w = width // the panel can't place widgets before it knows its width + if widgets.length() > 0 { + ignore(comp.compose_frame()) // boots the panel and sets the theme tokens modules are loaded with + for path in widgets { + ignore(comp.shell.load_path(path)) + } + } if gfx_out.length() > 0 { let pixmap = comp.present_to_gfx(gfx_ctx) let png = @renderer.encode_png(pixmap) diff --git a/compositor/bin/moon.pkg b/compositor/bin/moon.pkg index 86d6e86..5381c90 100644 --- a/compositor/bin/moon.pkg +++ b/compositor/bin/moon.pkg @@ -18,7 +18,7 @@ pkgtype(kind: "executable") options( link: { "native": { - "cc-link-flags": "-ldrm -linput -lseat -lxkbcommon -ludev", + "cc-link-flags": "-ldrm -linput -lseat -lxkbcommon -ludev -lwasmer", }, }, ) diff --git a/compositor/font/font.mbt b/compositor/font/font.mbt new file mode 100644 index 0000000..504fc75 --- /dev/null +++ b/compositor/font/font.mbt @@ -0,0 +1,142 @@ +///| Real text rendering for the native compositor: Adwaita Mono rasterised with +/// stb_truetype, plugged into the renderer's glyph hook. The pure-MoonBit +/// renderer (also built for wasm) keeps its bitmap font when no hook is set. + +///| +#borrow(path) +extern "C" fn c_font_load(slot : Int, path : Bytes) -> Int = "mp_font_load" + +///| +extern "C" fn c_font_metrics( + slot : Int, + cp : Int, + size : Int, + info : FixedArray[Int], +) = "mp_font_metrics" + +///| +#borrow(buf) +extern "C" fn c_font_bitmap( + slot : Int, + cp : Int, + size : Int, + w : Int, + h : Int, + buf : Bytes, +) = "mp_font_bitmap" + +///| +fn utf8(s : String) -> Bytes { + let out : Array[Byte] = [] + for ch in s { + let c = ch.to_int() + if c < 0x80 { + out.push(c.to_byte()) + } else if c < 0x800 { + out.push((0xC0 | (c >> 6)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } else if c < 0x10000 { + out.push((0xE0 | (c >> 12)).to_byte()) + out.push((0x80 | ((c >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } else { + out.push((0xF0 | (c >> 18)).to_byte()) + out.push((0x80 | ((c >> 12) & 0x3F)).to_byte()) + out.push((0x80 | ((c >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } + } + Bytes::from_array(out) +} + +///| Where to look for each face: bundled copy first, then the system one. +let regular_paths : Array[String] = [ + "assets/fonts/AdwaitaMono-Regular.ttf", + "/usr/share/fonts/Adwaita/AdwaitaMono-Regular.ttf", +] + +///| +let sans_paths : Array[String] = [ + "assets/fonts/AlloVariable.ttf", + "/usr/local/share/fonts/a/AlloVariable.ttf", + "assets/fonts/AdwaitaSans-Regular.ttf", + "/usr/share/fonts/Adwaita/AdwaitaSans-Regular.ttf", +] + +///| +let bold_paths : Array[String] = [ + "assets/fonts/AdwaitaMono-Bold.ttf", + "/usr/share/fonts/Adwaita/AdwaitaMono-Bold.ttf", +] + +///| +fn load_first(slot : Int, paths : Array[String]) -> Bool { + for p in paths { + if c_font_load(slot, utf8(p)) == 0 { + return true + } + } + false +} + +///| +let cache : Map[Int, @renderer.Glyph] = {} + +///| +fn rasterise(slot : Int, cp : Int, size : Int, embolden : Bool) -> @renderer.Glyph { + let key = cp + 0x110000 * (size + 256 * (slot * 2 + (if embolden { 1 } else { 0 }))) + match cache.get(key) { + Some(g) => g + None => { + let info : FixedArray[Int] = FixedArray::make(5, 0) + c_font_metrics(slot, cp, size, info) + let w = info[0] + let h = info[1] + let buf = if w > 0 && h > 0 { + let b = Bytes::make(w * h, b'\x00') + c_font_bitmap(slot, cp, size, w, h, b) + b + } else { + Bytes::make(0, b'\x00') + } + let g : @renderer.Glyph = { + w, + h, + xoff: info[2], + yoff: info[3], + advance: info[4], + coverage: buf, + embolden, + } + cache.set(key, g) + g + } + } +} + +///| Install Allo Variable (UI text, falling back to Adwaita Sans) and Adwaita Mono (code) as the renderer's +/// faces. Returns false (keeping the bitmap font) when no face can be found. +/// Slots: 0 mono, 1 mono bold, 2 sans. Sans is a variable font whose bold +/// instance stb_truetype can't select, so bold sans is emboldened. +pub fn install() -> Bool { + let has_mono = load_first(0, regular_paths) + let has_sans = load_first(2, sans_paths) + if !has_mono && !has_sans { + return false + } + let has_bold = has_mono && load_first(1, bold_paths) + @renderer.set_glyph_source(fn(cp, size, bold, mono) { + if mono && has_mono { + if bold && has_bold { + rasterise(1, cp, size, false) + } else { + rasterise(0, cp, size, bold) + } + } else if has_sans { + rasterise(2, cp, size, bold) + } else { + rasterise(0, cp, size, bold) + } + }) + true +} diff --git a/compositor/font/font_stub.c b/compositor/font/font_stub.c new file mode 100644 index 0000000..bccbd59 --- /dev/null +++ b/compositor/font/font_stub.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include + +#include "moonbit.h" + +#define STB_TRUETYPE_IMPLEMENTATION +#define STBTT_STATIC +#include "stb_truetype.h" + +#define MAX_SLOTS 4 +static stbtt_fontinfo fonts[MAX_SLOTS]; +static unsigned char *font_data[MAX_SLOTS]; + +/* Load a TTF file into `slot`. Returns 0 on success. */ +MOONBIT_FFI_EXPORT +int32_t mp_font_load(int32_t slot, moonbit_bytes_t path_bytes) { + char path[512]; + int32_t len = Moonbit_array_length(path_bytes); + size_t n = (size_t)len < sizeof(path) - 1 ? (size_t)len : sizeof(path) - 1; + memcpy(path, path_bytes, n); + path[n] = '\0'; + if (slot < 0 || slot >= MAX_SLOTS) return -1; + FILE *f = fopen(path, "rb"); + if (!f) return -1; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + if (sz <= 0) { fclose(f); return -1; } + unsigned char *buf = (unsigned char *)malloc((size_t)sz); + if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -1; } + fclose(f); + if (!stbtt_InitFont(&fonts[slot], buf, stbtt_GetFontOffsetForIndex(buf, 0))) { free(buf); return -1; } + free(font_data[slot]); + font_data[slot] = buf; + return 0; +} + +/* info = [w, h, xoff, yoff (top-left of bitmap relative to pen/baseline), advance] in pixels. */ +MOONBIT_FFI_EXPORT +void mp_font_metrics(int32_t slot, int32_t cp, int32_t size, int32_t *info) { + stbtt_fontinfo *fi = &fonts[slot]; + float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size); + int adv, lsb, x0, y0, x1, y1; + int g = stbtt_FindGlyphIndex(fi, cp); + stbtt_GetGlyphHMetrics(fi, g, &adv, &lsb); + stbtt_GetGlyphBitmapBox(fi, g, scale, scale, &x0, &y0, &x1, &y1); + info[0] = x1 - x0; + info[1] = y1 - y0; + info[2] = x0; + info[3] = y0; + info[4] = (int32_t)(adv * scale + 0.5f); +} + +/* Render the 8-bit coverage bitmap (w*h bytes, w/h from mp_font_metrics) into buf. */ +MOONBIT_FFI_EXPORT +void mp_font_bitmap(int32_t slot, int32_t cp, int32_t size, int32_t w, int32_t h, moonbit_bytes_t buf) { + stbtt_fontinfo *fi = &fonts[slot]; + float scale = stbtt_ScaleForMappingEmToPixels(fi, (float)size); + if (w <= 0 || h <= 0 || Moonbit_array_length(buf) < w * h) return; + stbtt_MakeGlyphBitmap(fi, (unsigned char *)buf, w, h, w, scale, scale, stbtt_FindGlyphIndex(fi, cp)); +} diff --git a/compositor/font/moon.pkg b/compositor/font/moon.pkg new file mode 100644 index 0000000..7199de4 --- /dev/null +++ b/compositor/font/moon.pkg @@ -0,0 +1,10 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/compositor/renderer" @renderer, +} + +supported_targets = "-all+native" + +options( + "native-stub": [ "font_stub.c" ], +) diff --git a/compositor/font/stb_truetype.h b/compositor/font/stb_truetype.h new file mode 100644 index 0000000..ff5d70c --- /dev/null +++ b/compositor/font/stb_truetype.h @@ -0,0 +1,5321 @@ +// stb_truetype.h - v1.28 - public domain +// authored from 2009-2021 by Sean Barrett / RAD Game Tools +// +// ======================================================================= +// +// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +// +// This library does no range checking of the offsets found in the file, +// meaning an attacker can use it to read arbitrary memory. +// +// ======================================================================= +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +// Cass Everitt Martins Mozeiko github:aloucks +// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +// Brian Hook Omar Cornut github:vassvik +// Walter van Niftrik Ryan Griege github:Cerallin +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. Brian Costabile +// Ken Voskuil (kaesve) Yakov Galka +// Neil Bickford Matthias Dorfelt +// Isaac "Atridas" Serrano +// +// VERSION HISTORY +// +// 1.28 (2026-11-12) several fixes +// 1.27 (2026-11-08) many fixes, support vertical layout, underlines, font name +// 1.26 (2021-08-28) fix broken rasterizer +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places need to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*y1 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*y1. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Call a function to compute the bounding box of the character. It will contain +// signed values relative to . I.e. if it returns x0,y0, +// x1,y1, then the character should be displayed in the rectangle from +// to . +// +// Advancing for the next character: +// Call GlyphHMetrics, and compute 'current_point += SF * advance'. +// +// +// ADVANCED USAGE +// +// Quality: +// +// - Use the functions with Subpixel at the end to allow your characters +// to have subpixel positioning. Since the font is anti-aliased, not +// hinted, this is very important for quality. (This is not possible with +// baked fonts.) +// +// - Kerning is supported, and if you're supporting subpixel rendering +// then kerning is worth using to give your text a polished look. +// +// Performance: +// +// - Convert Unicode codepoints to glyph indexes and operate on the glyphs; +// if you don't do this, stb_truetype is forced to do the conversion on +// every call. +// +// - There are a lot of memory allocations. We should modify it to take +// a temp buffer and allocate from the temp buffer (without freeing), +// should help performance a lot. +// +// NOTES +// +// The system uses the raw data found in the .ttf file without changing it +// and without building auxiliary data structures. This is a bit inefficient +// on little-endian systems (the data is big-endian), but assuming you're +// caching the bitmaps or glyph shapes this shouldn't be a big deal. +// +// It appears to be very hard to programmatically determine what font a +// given file is in a general way. I provide an API for this, but I don't +// recommend it. +// +// +// PERFORMANCE MEASUREMENTS FOR 1.06: +// +// 32-bit 64-bit +// Previous release: 8.83 s 7.68 s +// Pool allocations: 7.72 s 6.34 s +// Inline sort : 6.54 s 5.65 s +// New rasterizer : 5.63 s 5.00 s + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// SAMPLE PROGRAMS +//// +// +// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless. +// See "tests/truetype_demo_win32.c" for a complete version. +#if 0 +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +unsigned char ttf_buffer[1<<20]; +unsigned char temp_bitmap[512*512]; + +stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs +GLuint ftex; + +void my_stbtt_initfont(void) +{ + fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); + stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! + // can free ttf_buffer at this point + glGenTextures(1, &ftex); + glBindTexture(GL_TEXTURE_2D, ftex); + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap); + // can free temp_bitmap at this point + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +} + +void my_stbtt_print(float x, float y, char *text) +{ + // assume orthographic projection with units = screen pixels, origin at top left + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, ftex); + glBegin(GL_QUADS); + while (*text) { + if (*text >= 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Compilable program (does no cleanup): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); // fclose() omitted for clarity + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); // stbtt_FreeBitmap() omitted for clarity + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs & no cleanup +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + #ifndef STBTT_assert + #include + #define STBTT_assert(x) assert(x) + #endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + const int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph received the font's "missing character" glyph, +// typically an empty box by convention. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + int skip_missing; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publicly so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,vhea,vmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSION + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose width is 'pixels' wide. +// Width is measured as the distance from the left-side-bearing to the right-side-bearing + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap); + + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness); +// the underline position and thickness as defined in the "post" table +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + +typedef struct stbtt_kerningentry +{ + int glyph1; // use stbtt_FindGlyphIndex + int glyph2; + int advance; +} stbtt_kerningentry; + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); +// Retrieves a complete list of all of the kerning pairs provided by the font +// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. +// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of contours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); +// fills svg with the character's SVG data. +// returns data size or 0 if SVG not found. + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *output_buffer, size_t output_buffer_len); +// return the default english full name of the font as utf-8 + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + int v, b0 = stbtt__buf_peek8(b); + STBTT_assert(b0 >= 28); + if (b0 == 30) { + stbtt__buf_skip(b, 1); + while (b->cursor < b->size) { + v = stbtt__buf_get8(b); + if ((v & 0xF) == 0xF || (v >> 4) == 0xF) + break; + } + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) +{ + stbtt__buf_seek(b, 0); + while (b->cursor < b->size) { + int start = b->cursor, end, op; + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + end = b->cursor; + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end-start); + } + return stbtt__buf_range(b, 0, 0); +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) +{ + int i; + stbtt__buf operands = stbtt__dict_get(b, key); + for (i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + STBTT_assert(i >= 0 && i < count); + STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + for (i=0; i < num_tables; ++i) { + stbtt_uint32 loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +// since most people won't use this, find this table the first time it's needed +static int stbtt__get_svg(stbtt_fontinfo *info) +{ + stbtt_uint32 t; + if (info->svg < 0) { + t = stbtt__find_table(info->data, info->fontstart, "SVG "); + if (t) { + stbtt_uint32 offset = ttULONG(info->data + t + 2); + info->svg = t + offset; + } else { + info->svg = 0; + } + } + return info->svg; +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + stbtt_uint32 symbol_map=0; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->vhea = stbtt__find_table(data, fontstart, "vhea"); // not required + info->vmtx = stbtt__find_table(data, fontstart, "vmtx"); // not required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + info->svg = -1; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + for (i=0; i < numTables; ++i) { + stbtt_uint32 encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + case STBTT_MS_EID_SYMBOL: + symbol_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + info->index_map = symbol_map; + + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + stbtt_uint8 *data = info->data; + stbtt_uint32 index_map = info->index_map; + + stbtt_uint16 format = ttUSHORT(data + index_map + 0); + + if (format == 0) { // apple byte encoding + stbtt_int32 bytes = ttUSHORT(data + index_map + 2); + if (unicode_codepoint < bytes-6) + return ttBYTE(data + index_map + 6 + unicode_codepoint); + return 0; + } else if (format == 6) { + stbtt_uint32 first = ttUSHORT(data + index_map + 6); + stbtt_uint32 count = ttUSHORT(data + index_map + 8); + if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count) + return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2); + return 0; + } else if (format == 2) { + STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean + return 0; + } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges + stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1; + stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; + stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); + stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; + + // do a binary search of the segments + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (unicode_codepoint > 0xffff) + return 0; + + // they lie from endCount .. endCount + segCount + // but searchRange is the nearest power of two, so... + if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2)) + search += rangeShift*2; + + // now decrement to bias correctly to find smallest + search -= 2; + while (entrySelector) { + stbtt_uint16 end; + searchRange >>= 1; + end = ttUSHORT(data + search + searchRange*2); + if (unicode_codepoint > end) + search += searchRange*2; + --entrySelector; + } + search += 2; + + { + stbtt_uint16 offset, start, last, index; + stbtt_int16 delta; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); + + // get the actual range for this segment + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + last = ttUSHORT(data + endCount + 2*item); + if (unicode_codepoint < start || unicode_codepoint > last) + return 0; + + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + delta = ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item); + + // "if idRangeOffset is 0, the idDelta value is added directly to the character code" + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + delta); + + // "If the idRangeOffset value for the segment is not 0, ..." + // "glyphIndexAddress = idRangeOffset[i] + 2 * (c - startCode[i]) + (Ptr) &idRangeOffset[i]" + index = ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + + // "Once the glyph indexing operation is complete, the glyph ID at the indicated address + // is checked. If it's not 0 (that is, if it's not the missing glyph), the value is added + // to idDelta[i] to get the actual glyph ID to use." + if (index != 0) { + index = (stbtt_uint16) (index + delta); + } + + return index; + } + } else if (format == 12 || format == 13) { + stbtt_uint32 ngroups = ttULONG(data+index_map+12); + stbtt_int32 low,high; + low = 0; high = (stbtt_int32)ngroups; + // Binary search the right group. + while (low < high) { + stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high + stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12); + stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4); + if ((stbtt_uint32) unicode_codepoint < start_char) + high = mid; + else if ((stbtt_uint32) unicode_codepoint > end_char) + low = mid+1; + else { + stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8); + if (format == 12) + return start_glyph + unicode_codepoint-start_char; + else // format == 13 + return start_glyph; + } + } + return 0; // not found + } + // @TODO + STBTT_assert(0); + return 0; +} + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + return stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + stbtt_int16 dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + stbtt_int16 dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one... avoid looking ahead if we're at the end of a contour + start_off = !(flags & 1) && i < ttUSHORT(endPtsOfContours+j*2); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours < 0) { + // Compound shapes. + int more = 1; + stbtt_uint8 *comp = data + g + 10; + num_vertices = 0; + vertices = 0; + while (more) { + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. Per TrueType spec, these are used + // ONLY to rescale the offsets (mtx[4], mtx[5]) when + // SCALED_COMPONENT_OFFSET (flag bit 11, 0x800) is set. They must + // NOT scale the linear part of the transform — doing so squares + // the scale factor and is the cause of composite sub-components + // rendering at wrong sizes in COLR emoji fonts (OpenMoji, Noto + // Color Emoji, Microsoft Fluent Emoji). + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + // Default: UNSCALED offsets (Microsoft convention; matches modern + // font tooling). Only SCALED_COMPONENT_OFFSET (bit 11) set without + // UNSCALED_COMPONENT_OFFSET (bit 12) triggers the offset rescale. + if ((flags & (1<<11)) && !(flags & (1<<12))) { + mtx[4] *= m; mtx[5] *= n; + } + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices: v' = M·v + t. No double-scaling. + for (i = 0; i < comp_num_verts; ++i) { + stbtt_vertex* v = &comp_verts[i]; + stbtt_vertex_type x,y; + x=v->x; y=v->y; + v->x = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); + v->y = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + x=v->cx; y=v->cy; + v->cx = (stbtt_vertex_type)(mtx[0]*x + mtx[2]*y + mtx[4]); + v->cy = (stbtt_vertex_type)(mtx[1]*x + mtx[3]*y + mtx[5]); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) return stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // FALLTHROUGH + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && b0 < 32) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +STBTT_DEF void stbtt_GetGlyphVMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceHeight, int *topSideBearing) +{ + if (advanceHeight) *advanceHeight = ttSHORT(info->data + info->vmtx + 4*glyph_index); + if (topSideBearing) *topSideBearing = ttSHORT(info->data + info->vmtx + 4*glyph_index + 2); +} + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) +{ + stbtt_uint8 *data = info->data + info->kern; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + return ttUSHORT(data+10); +} + +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) +{ + stbtt_uint8 *data = info->data + info->kern; + int k, length; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + length = ttUSHORT(data+10); + if (table_length < length) + length = table_length; + + for (k = 0; k < length; k++) + { + table[k].glyph1 = ttUSHORT(data+18+(k*6)); + table[k].glyph2 = ttUSHORT(data+20+(k*6)); + table[k].advance = ttSHORT(data+22+(k*6)); + } + + return length; +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch (coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + break; + } + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + break; + } + + default: return -1; // unsupported + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch (classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + break; + } + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + break; + } + + default: + return -1; // Unsupported definition type, return an error. + } + + // "All glyphs not assigned to a class fall into class 0". (OpenType spec) + return 0; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i, sti; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) > 1) return 0; // Minor version 0, or 1 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i= pairSetCount) return 0; + + needle=glyph2; + r=pairValueCount-1; + l=0; + + // Binary search. + while (l <= r) { + stbtt_uint16 secondGlyph; + stbtt_uint8 *pairValue; + m = (l + r) >> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + stbtt_int16 xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } else + return 0; + break; + } + + case 2: { + stbtt_uint16 valueFormat1 = ttUSHORT(table + 4); + stbtt_uint16 valueFormat2 = ttUSHORT(table + 6); + if ((valueFormat1 == 4 || + valueFormat1 == 68) && + valueFormat2 == 0) { // Support more formats? + stbtt_uint16 classDef1Offset = ttUSHORT(table + 8); + stbtt_uint16 classDef2Offset = ttUSHORT(table + 10); + int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + stbtt_uint16 class1Count = ttUSHORT(table + 12); + stbtt_uint16 class2Count = ttUSHORT(table + 14); + stbtt_uint8 *class1Records, *class2Records; + stbtt_int16 xAdvance; + stbtt_int32 valueRecordPairSizeInBytes; + + if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed + if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed + + valueRecordPairSizeInBytes = valueFormat1 == 68 ? 4 : 2; + + class1Records = table + 16; + class2Records = class1Records + valueRecordPairSizeInBytes * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + valueRecordPairSizeInBytes * glyph2class); + return xAdvance; + } else + return 0; + break; + } + + default: + return 0; // Unsupported position format + } + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance = stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + + if (info->kern && xAdvance == 0) + xAdvance = stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetCodepointVMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceHeight, int *topSideBearing) +{ + stbtt_GetGlyphVMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceHeight, topSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF void stbtt_GetFontHMetrics(const stbtt_fontinfo *info, int *vertTypoAscender, int *vertTypoDescender, int *vertTypoLineGap) +{ + if (vertTypoAscender ) *vertTypoAscender = ttSHORT(info->data+info->vhea + 4); + if (vertTypoDescender) *vertTypoDescender = ttSHORT(info->data+info->vhea + 6); + if (vertTypoLineGap) *vertTypoLineGap = ttSHORT(info->data+info->vhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF int stbtt_GetFontUnderlineMetrics(const stbtt_fontinfo *info, int *position, int *thickness) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "post"); + if (!tab) + return 0; + *position = ttSHORT(info->data + tab + 8); + *thickness = ttSHORT(info->data + tab + 10); + return 1; +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForPixelWidth(const stbtt_fontinfo *info, float width) +{ + int fwidth = ttSHORT(info->data + info->hhea + 10) - ttSHORT(info->data + info->hhea + 12); + return (float) width / fwidth; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) +{ + int i; + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); + + int numEntries = ttUSHORT(svg_doc_list); + stbtt_uint8 *svg_docs = svg_doc_list + 2; + + for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) + return svg_doc; + } + return 0; +} + +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) +{ + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc; + + if (info->svg == 0) + return 0; + + svg_doc = stbtt_FindSVGDoc(info, gl); + if (svg_doc != NULL) { + *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); + return ttULONG(svg_doc + 8); + } else { + return 0; + } +} + +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) +{ + return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + int x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + float scan_y = y + 0.5f; + stbtt__active_edge **step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + int changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + stbtt__active_edge *t = *step; + stbtt__active_edge *q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) +{ + STBTT_assert(top_width >= 0); + STBTT_assert(bottom_width >= 0); + return (top_width + bottom_width) / 2.0f * height; +} + +static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) +{ + return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); +} + +static float stbtt__sized_triangle_area(float height, float width) +{ + return height * width / 2; +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = (sy1 - sy0) * e->direction; + STBTT_assert(x >= 0 && x < len); + scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); + scanline_fill[x] += height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, y_final, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + STBTT_assert(dy >= 0); + STBTT_assert(dx >= 0); + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = y_top + dy * (x1+1 - x0); + + // compute intersection with y axis at x2 + y_final = y_top + dy * (x2 - x0); + + // x1 x_top x2 x_bottom + // y_top +------|-----+------------+------------+--------|---+------------+ + // | | | | | | + // | | | | | | + // sy0 | Txxxxx|............|............|............|............| + // y_crossing | *xxxxx.......|............|............|............| + // | | xxxxx..|............|............|............| + // | | /- xx*xxxx........|............|............| + // | | dy < | xxxxxx..|............|............| + // y_final | | \- | xx*xxx.........|............| + // sy1 | | | | xxxxxB...|............| + // | | | | | | + // | | | | | | + // y_bottom +------------+------------+------------+------------+------------+ + // + // goal is to measure the area covered by '.' in each pixel + + // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 + // @TODO: maybe test against sy1 rather than y_bottom? + if (y_crossing > y_bottom) + y_crossing = y_bottom; + + sign = e->direction; + + // area of the rectangle covered from sy0..y_crossing + area = sign * (y_crossing-sy0); + + // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) + scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); + + // check if final y_crossing is blown up; no test case for this + if (y_final > y_bottom) { + int denom = (x2 - (x1+1)); + y_final = y_bottom; + if (denom != 0) + dy = (y_final - y_crossing ) / denom; // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } + + // in second pixel, area covered by line segment found in first pixel + // is always a rectangle 1 wide * the height of that line segment; this + // is exactly what the variable 'area' stores. it also gets a contribution + // from the line segment within it. the THIRD pixel will get the first + // pixel's rectangle contribution, the second pixel's rectangle contribution, + // and its own contribution. the 'own contribution' is the same in every pixel except + // the leftmost and rightmost, a trapezoid that slides down in each pixel. + // the second pixel's contribution to the third pixel will be the + // rectangle 1 wide times the height change in the second pixel, which is dy. + + step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, + // which multiplied by 1-pixel-width is how much pixel area changes for each step in x + // so the area advances by 'step' every time + + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; // area of trapezoid is 1*step/2 + area += step; + } + STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down + STBTT_assert(sy1 > y_final-0.01f); + + // area covered in the last pixel is the rectangle from all the pixels to the left, + // plus the trapezoid filled by the line segment in this pixel all the way to the right edge + scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); + + // the rest of the line is filled based on the total height of the line segment in this pixel + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + // note though that this does happen some of the time because + // x_top and x_bottom can be extrapolated at the top & bottom of + // the shape and actually lie outside the bounding box + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + float y1 = (x - x0) / dx + y_top; + float y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + int a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + float x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + STBTT_assert(x+gw < pw); + STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + spc->skip_missing = 0; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + int i; + unsigned int total; + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k; + int missing_glyph_added = 0; + + k=0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + int x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + if (glyph == 0) + missing_glyph_added = 1; + } + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, missing_range = -1, missing_glyph = -1, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + + k = 0; + for (i=0; i < num_ranges; ++i) { + float fh = ranges[i].font_size; + float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed && r->w != 0 && r->h != 0) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + int advance, lsb, x0,y0,x1,y1; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + + if (glyph == 0) { + missing_range = i; + missing_glyph = j; + } + } else if (spc->skip_missing) { + return_value = 0; + } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { + ranges[i].chardata_for_range[j] = ranges[missing_range].chardata_for_range[missing_glyph]; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i, j, n, return_value; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int stbtt__equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + + orig[0] = x; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y; + int x1 = (int) verts[i ].x, y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ; + int x1 = (int) verts[i ].cx, y1 = (int) verts[i ].cy; + int x2 = (int) verts[i ].x , y2 = (int) verts[i ].y ; + int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2)); + int by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + float q0[2],q1[2],q2[2]; + float hits[2][2]; + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (stbtt__equal(q0,q1) || stbtt__equal(q1,q2)) { + x0 = (int)verts[i-1].x; + y0 = (int)verts[i-1].y; + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + a*x^2 + b*x + c = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + if (scale == 0) return NULL; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) { + if (width) *width = 0; + if (height) *height = 0; + if (xoff) *xoff = 0; + if (yoff) *yoff = 0; + return NULL; + } + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + // distance from singular values (in the same units as the pixel grid) + const float eps = 1./1024, eps2 = eps*eps; + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y; + float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y; + float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y; + float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float len2 = bx*bx + by*by; + if (len2 >= eps2) + precompute[i] = 1.0f / len2; + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + float val; + float min_dist = 999999.0f; + float sx = (float) x + 0.5f; + float sy = (float) y + 0.5f; + float x_gspace = (sx / scale_x); + float y_gspace = (sy / scale_y); + + int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y; + + if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { + float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y; + + float dist,dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + float dx = x1-x0, dy = y1-y0; + float px = x0-sx, py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + float t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y; + float x1 = verts[i ].cx*scale_x, y1 = verts[i ].cy*scale_y; + float box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + float box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + float box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + float box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + int num=0; + float ax = x1-x0, ay = y1-y0; + float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2; + float mx = x0 - sx, my = y0 - sy; + float res[3] = {0.f,0.f,0.f}; + float px,py,t,it,dist2; + float a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + float a = 3*(ax*bx + ay*by); + float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + float c = mx*ax+my*ay; + if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear + if (STBTT_fabs(b) >= eps2) { + res[num++] = -c/b; + } + } else { + float discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + float root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + float d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2], it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + stbtt_uint16 ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +// convert utf16 to utf8 and return the length required to output NUL-terminated; buffer_len of 0 means to just query length +// if you pass a buffer that's too small, it'll NULL terminate and return the actual length computed +STBTT_DEF int stbtt__ConvertUTF16BEtoUTF8(char *buffer, size_t buffer_len, unsigned char *src, size_t src_len_raw) +{ + int src_len = (int) src_len_raw; + int write_max = 0; + int i = 0, write, off = 0; + write = (buffer_len != 0); + write_max = (int) (buffer_len-1); + + if ((size_t) src_len != src_len_raw) + return -1; + + if (write) { + if (write_max < 0 || ((size_t) write_max+1 != buffer_len && write_max != 0)) + return -1; + } + + if (buffer_len == 1) { + buffer[0] = 0; + return 1; + } + + while (off < src_len) { + stbtt_uint16 ch = src[off+0]*256 + src[off+1]; + off += 2; + if (ch < 0x80) { + if (write) { + if (i >= write_max) { buffer[i] = 0; return i+1; } + buffer[i] = (char) ch; + } + ++i; + } else if (ch < 0x800) { + if (write) { + if (i+1 >= write_max) { buffer[i] = 0; return i+1; } + buffer[i+0] = (char) ( 0xc0 + (ch >> 6) ); + buffer[i+1] = (char) ( 0x80 + (ch & 0x3f) ); + } + i += 2; + } else if (ch >= 0xd800 && ch < 0xdc00) { + stbtt_uint32 c; + stbtt_uint16 ch2 = src[off+0]*256 + src[off+1]; + off += 2; + if (write) { + if (i+3 >= write_max) { buffer[i] = 0; return i+1; } + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + buffer[i+0] = (char) ( 0xf0 + (c >> 18) ); + buffer[i+1] = (char) ( 0x80 + ((c >> 12) & 0x3f) ); + buffer[i+2] = (char) ( 0x80 + ((c >> 6) & 0x3f) ); + buffer[i+3] = (char) ( 0x80 + ((c ) & 0x3f) ); + } + i += 4; + } else if (ch >= 0xdc00 && ch < 0xe000) { + if (write) + buffer[i] = 0; + return -1; + } else { + if (write) { + if (i+2 >= write_max) { buffer[i] = 0; return i+1; } + buffer[i+0] = (char) ( 0xe0 + (ch >> 12) ); + buffer[i+1] = (char) ( 0x80 + ((ch >> 6) & 0x3f) ); + buffer[i+2] = (char) ( 0x80 + ((ch ) & 0x3f) ); + } + i += 3; + } + } + if (write) { + STBTT_assert(i <= write_max); + buffer[i] = 0; + } + return i+1; +} + +// Returns the english full name of the font as UTF-8 +STBTT_DEF int stbtt_GetFontNameDefault(const stbtt_fontinfo *font, char *buffer, size_t buffer_len) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return -1; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + for (i=0; i < count; ++i) { + char* str; + stbtt_uint16 platformId; + stbtt_uint16 encodingId; + stbtt_uint16 languageId; + size_t length; + stbtt_uint32 loc = nm + 6 + 12 * i; + if (ttUSHORT(fc+loc+6) != 4) continue; + platformId = ttUSHORT(fc+loc+0); + encodingId = ttUSHORT(fc+loc+2); + languageId = ttUSHORT(fc+loc+4); + if (!(platformId == STBTT_PLATFORM_ID_MAC && languageId == STBTT_MAC_LANG_ENGLISH) && !(platformId == STBTT_PLATFORM_ID_MICROSOFT && languageId == STBTT_MS_LANG_ENGLISH)) + continue; + + length = ttUSHORT(fc+loc+8); + str = (char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + if (platformId == STBTT_PLATFORM_ID_UNICODE || (platformId == STBTT_PLATFORM_ID_MICROSOFT && (encodingId == 1 || encodingId == 10))) + return stbtt__ConvertUTF16BEtoUTF8(buffer, buffer_len, (unsigned char *) str, length); + else { + if (buffer == NULL) + return (int) length; + + if (length < buffer_len) { + memcpy(buffer, str, length); + buffer[length] = 0; + return (int) length; + } else { + memcpy(buffer, str, buffer_len-1); + buffer[buffer_len-1] = 0; + return (int) length; + } + } + } + return -1; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + for (i=0; i < count; ++i) { + stbtt_uint32 loc = nm + 6 + 12 * i; + stbtt_int32 id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4); + + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + stbtt_int32 slen = ttUSHORT(fc+loc+8); + stbtt_int32 off = ttUSHORT(fc+loc+10); + + // check if there's a prefix match + stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i; + for (i=0;;++i) { + stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/compositor/host/compositor.mbt b/compositor/host/compositor.mbt index f19992e..6977036 100644 --- a/compositor/host/compositor.mbt +++ b/compositor/host/compositor.mbt @@ -10,6 +10,8 @@ pub(all) struct HostWindow { mut maximized : Bool mut fullscreen : Bool mut surface : @scene.ShmBufferSnapshot? + /// A size change still to be sent to the client (coalesced while dragging a divider). + mut cfg_dirty : Bool } ///| @@ -32,6 +34,8 @@ pub(all) struct MoonPlasmaCompositor { mut press_fwd : Bool mut kbd_win : UInt64? mut mods : UInt + /// A Super key is down and nothing else was pressed since: releasing it opens the launcher. + mut super_solo : Bool mut layout_mode : @wm.LayoutMode } @@ -42,6 +46,7 @@ pub fn MoonPlasmaCompositor::new( output_w : Int, output_h : Int, ) -> MoonPlasmaCompositor? { + ignore(@font.install()) // Adwaita Mono; keeps the bitmap font if it's missing let server = match @wayland.WaylandServer::listen(socket_path, output_w, output_h) { Some(s) => s None => return None @@ -58,6 +63,8 @@ pub fn MoonPlasmaCompositor::new( excl_top=32, // room for the server-side title bar drawn above each client excl_bottom=theme.panel_height, ) + let shell = @shell.DesktopShell::new(socket_path) + shell.set_output(theme, output_w, output_h) Some({ server, wm, @@ -67,7 +74,7 @@ pub fn MoonPlasmaCompositor::new( work_area, windows: {}, damage: @scene.DamageTracker::new(), - shell: @shell.DesktopShell::new(socket_path), + shell, ptr_x: 0.0, ptr_y: 0.0, ptr_win: None, @@ -75,12 +82,14 @@ pub fn MoonPlasmaCompositor::new( press_fwd: false, kbd_win: None, mods: 0U, + super_solo: false, layout_mode: @wm.LayoutMode::Tiling, }) } ///| pub fn MoonPlasmaCompositor::close(self : MoonPlasmaCompositor) -> Unit { + self.shell.shutdown() self.server.close() } @@ -95,14 +104,20 @@ fn MoonPlasmaCompositor::apply_actions( match self.windows.get(wid) { Some(win) => { win.geometry = @scene.Rect::new(r.x, r.y, r.w, r.h) - self.server.send_toplevel_configure( - wid, - r.w, - r.h, - win.focused, - win.maximized, - win.fullscreen, - ) + if self.split_drag is Some(_) { + // Dragging: send one configure per frame, not one per mouse event. + win.cfg_dirty = true + } else { + win.cfg_dirty = false + self.server.send_toplevel_configure( + wid, + r.w, + r.h, + win.focused, + win.maximized, + win.fullscreen, + ) + } self.damage.mark_full() } None => () @@ -130,8 +145,26 @@ fn MoonPlasmaCompositor::apply_actions( } } +///| Send the size changes coalesced during a divider drag. +fn MoonPlasmaCompositor::flush_configures(self : MoonPlasmaCompositor) -> Unit { + for wid, win in self.windows { + if win.cfg_dirty { + win.cfg_dirty = false + self.server.send_toplevel_configure( + wid, + win.geometry.w, + win.geometry.h, + win.focused, + win.maximized, + win.fullscreen, + ) + } + } +} + ///| pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { + self.flush_configures() let events = self.server.poll_events() for ev in events { match ev { @@ -145,6 +178,7 @@ pub fn MoonPlasmaCompositor::step(self : MoonPlasmaCompositor) -> Unit { maximized: false, fullscreen: false, surface: None, + cfg_dirty: false, } self.windows.set(wid, win) let rec : @wm.WindowRecord = { @@ -250,15 +284,13 @@ pub fn MoonPlasmaCompositor::set_layout_mode( pub fn MoonPlasmaCompositor::compose_frame( self : MoonPlasmaCompositor, ) -> @renderer.Pixmap { + self.flush_configures() let scene = @scene.SceneGraph::new(self.output_w, self.output_h) let order = self.wm.stacking_order() - let titles : Array[String] = [] for wid in order { match self.windows.get(wid) { Some(win) => { - let label = if win.title.length() > 0 { win.title } else { win.app_id } - titles.push(label) let (insets, deco_ops) = @scene.build_breeze_decoration( win.title, win.app_id, @@ -284,18 +316,51 @@ pub fn MoonPlasmaCompositor::compose_frame( } } - let layout_label = match self.layout_mode { - @wm.LayoutMode::Tiling => "BSP Tiling" - @wm.LayoutMode::Floating => "Floating" - @wm.LayoutMode::Monocle => "Monocle" + self.shell.layout_sel = match self.layout_mode { + @wm.LayoutMode::Tiling => 0 + @wm.LayoutMode::Monocle => 1 + @wm.LayoutMode::Floating => 2 } - let (bg_ops, panel_ops) = self.shell.render( - self.output_w, - self.output_h, - self.theme, - layout_label, - titles, - ) + // The task list shows every window, minimized ones too (so they can be restored). + let wins : Array[@shell.WinInfo] = [] + for wid in order { + match self.windows.get(wid) { + Some(win) => + wins.push({ + id: win.id, + title: if win.title.length() > 0 { win.title } else { win.app_id }, + focused: win.focused, + minimized: false, + }) + None => () + } + } + for id, r in self.wm.windows { + if r.minimized { + match self.windows.get(id) { + Some(win) => + wins.push({ + id, + title: if win.title.length() > 0 { win.title } else { win.app_id }, + focused: false, + minimized: true, + }) + None => () + } + } + } + self.shell.windows = wins + // The window list the `windows` interface serves to wasm widgets (task-bar order). + let entries : Array[@wasm.WindowEntry] = [] + for w in wins { + match self.windows.get(w.id) { + Some(win) => entries.push({ id: w.id, title: w.title, app_id: win.app_id, focused: w.focused }) + None => () + } + } + self.shell.win_list = entries + let (bg_ops, panel_ops) = self.shell.render(self.output_w, self.output_h, self.theme) + self.run_shell_actions() scene.background_ops = bg_ops scene.panel_ops = panel_ops ignore(self.damage.take_damage(self.output_w, self.output_h)) @@ -390,6 +455,104 @@ fn MoonPlasmaCompositor::window_at(self : MoonPlasmaCompositor, x : Int, y : Int None } +///| Title-bar button under (x, y) for window `wid`: 1 minimize, 2 maximize, 3 close, 0 none. +/// Mirrors the layout in `build_breeze_decoration` (18px buttons, 8px apart, 10px from the right edge). +fn MoonPlasmaCompositor::title_button_at( + self : MoonPlasmaCompositor, + wid : UInt64, + x : Int, + y : Int, +) -> Int { + match self.windows.get(wid) { + None => 0 + Some(win) => { + let g = win.geometry + let outer_w = g.w + 4 + let lx = x - (g.x - 2) + let ly = y - (g.y - 32) + let size = 18 + let by = (32 - size) / 2 + if ly < by - 3 || ly >= by + size + 3 { + return 0 + } + let close_x = outer_w - 10 - size + let max_x = close_x - 8 - size + let min_x = max_x - 8 - size + if lx >= close_x - 3 && lx < close_x + size + 3 { + 3 + } else if lx >= max_x - 3 && lx < max_x + size + 3 { + 2 + } else if lx >= min_x - 3 && lx < min_x + size + 3 { + 1 + } else { + 0 + } + } + } +} + +///| Activate the title-bar button `btn` of window `wid`. +fn MoonPlasmaCompositor::press_title_button( + self : MoonPlasmaCompositor, + wid : UInt64, + btn : Int, +) -> Unit { + self.leave_pointer() + let req = match btn { + 1 => @wm.WindowRequest::Minimize(true) + 2 => { + let maxed = match self.wm.windows.get(wid) { + Some(r) => r.maximized + None => false + } + @wm.WindowRequest::Maximize(!maxed) + } + _ => @wm.WindowRequest::Close + } + self.apply_actions(self.wm.handle_request(wid, req, self.work_area)) + if btn == 1 { + // Hand focus to the top-most remaining window. + let order = self.wm.stacking_order() + if order.length() > 0 { + let top = order[order.length() - 1] + self.apply_actions([@wm.WmAction::Focus(top), @wm.WmAction::Raise(top)]) + } else { + self.set_kbd_focus(None) + } + } + self.damage.mark_full() +} + +///| Restore a minimized window (or focus a visible one) from its task-bar pill. +fn MoonPlasmaCompositor::activate_task(self : MoonPlasmaCompositor, wid : UInt64) -> Unit { + let minimized = match self.wm.windows.get(wid) { + Some(r) => r.minimized + None => return + } + if minimized { + self.apply_actions( + self.wm.handle_request(wid, @wm.WindowRequest::Minimize(false), self.work_area), + ) + } + self.apply_actions([@wm.WmAction::Focus(wid), @wm.WmAction::Raise(wid)]) +} + +///| Carry out what panel modules asked for: focus a window, switch layout. +fn MoonPlasmaCompositor::run_shell_actions(self : MoonPlasmaCompositor) -> Unit { + for a in self.shell.take_actions() { + match a { + @shell.ShellAction::FocusWindow(wid) => self.activate_task(wid) + @shell.ShellAction::SetLayout(m) => + match m { + 0 => self.set_layout_mode(@wm.LayoutMode::Tiling) + 1 => self.set_layout_mode(@wm.LayoutMode::Monocle) + 2 => self.set_layout_mode(@wm.LayoutMode::Floating) + _ => () + } + } + } +} + ///| Tiling divider under (x, y), with a few pixels of slack either side. fn MoonPlasmaCompositor::handle_at( self : MoonPlasmaCompositor, @@ -467,6 +630,20 @@ pub fn MoonPlasmaCompositor::handle_input( self.ptr_y = y let xi = x.to_int() let yi = y.to_int() + if self.shell.inspecting() { + self.leave_pointer() + let id = match self.shell.component_at(xi, yi) { + "" => + match self.window_at(xi, yi) { + Some((_, true)) => "window-surface" + Some((_, false)) => "window-decoration" + None => "desktop" + } + sid => sid + } + self.shell.set_hover(id, xi, yi) + return + } if self.shell.pointer_move(xi, yi) || self.shell.hit(xi, yi) { self.leave_pointer() return @@ -482,6 +659,17 @@ pub fn MoonPlasmaCompositor::handle_input( self.leave_pointer() return } + match self.split_drag { + Some(h) => { + self.apply_actions(self.wm.drag_split(h, xi, yi, self.work_area)) + return + } + None => () + } + if self.handle_at(xi, yi) is Some(_) { + self.leave_pointer() + return + } match self.window_at(xi, yi) { Some((wid, true)) => match self.windows.get(wid) { @@ -500,17 +688,50 @@ pub fn MoonPlasmaCompositor::handle_input( _ => self.leave_pointer() } } + Scroll(v) => { + // ~10 units per wheel notch -> 3 lines. + let lines = if v > 0.0 { (v / 10.0).to_int() + 1 } else { (v / 10.0).to_int() - 1 } + ignore(self.shell.scroll_inspector(lines)) + } PointerButton(button, pressed) => { let xi = self.ptr_x.to_int() let yi = self.ptr_y.to_int() + if !pressed && self.shell.pointer_up() { + self.run_shell_actions() + return + } if !pressed && self.split_drag is Some(_) { self.split_drag = None return } + // Right button over a swappable panel widget opens its alternatives menu. + if button == 273U && pressed && self.shell.right_click(xi, yi) { + return + } if pressed { - if self.shell.pointer_down(xi, yi) { + self.super_solo = false + if button != 273U && self.shell.pointer_down(xi, yi) { + self.run_shell_actions() return } + match self.window_at(xi, yi) { + Some((wid, false)) => { + let btn = self.title_button_at(wid, xi, yi) + if btn != 0 { + self.press_title_button(wid, btn) + return + } + } + _ => () + } + match self.handle_at(xi, yi) { + Some(h) => { + self.split_drag = Some(h) + self.leave_pointer() + return + } + None => () + } match self.handle_at(xi, yi) { Some(h) => { self.split_drag = Some(h) @@ -542,7 +763,24 @@ pub fn MoonPlasmaCompositor::handle_input( } } Key(code, pressed) => - if self.shell.popup_open() { + if code == 125U || code == 126U { + // Super (left/right): a bare tap toggles the launcher search; never reaches clients. + if pressed { + self.super_solo = true + } else if self.super_solo { + self.super_solo = false + if !self.shell.inspecting() { + self.shell.toggle_launcher() + } + } + } else if self.shell.inspecting() { + self.super_solo = false + // Escape leaves inspect mode; other keys are not forwarded while inspecting. + if code == 1U && pressed { + self.shell.set_inspecting(false) + } + } else if self.shell.popup_open() { + self.super_solo = false if pressed { let name = key_name(code, (self.mods & 1U) != 0U) if name.length() > 0 { @@ -550,6 +788,7 @@ pub fn MoonPlasmaCompositor::handle_input( } } } else { + self.super_solo = false match self.kbd_win { Some(w) => self.server.keyboard_key(w, time_ms, code, pressed) None => () @@ -580,6 +819,14 @@ pub fn MoonPlasmaCompositor::desired_cursor(self : MoonPlasmaCompositor) -> UInt Some(h) => return if h.horizontal { 26U } else { 27U } // ew-resize / ns-resize None => () } + let handle = match self.split_drag { + Some(h) => Some(h) + None => self.handle_at(self.ptr_x.to_int(), self.ptr_y.to_int()) + } + match handle { + Some(h) => return if h.horizontal { 26U } else { 27U } // ew-resize / ns-resize + None => () + } match self.ptr_win { Some(w) => self.server.client_cursor_shape(w) None => 1U diff --git a/compositor/host/input_test.mbt b/compositor/host/input_test.mbt index 8a7afbd..a927c93 100644 --- a/compositor/host/input_test.mbt +++ b/compositor/host/input_test.mbt @@ -1,5 +1,41 @@ -///| Input routing: host pointer/keyboard events reach the focused client window, -/// and the launcher button opens the shell's launcher popup. +///| Input routing: host pointer/keyboard events reach the focused client window, and the +/// panel (made entirely of wasm modules) responds to the mouse and keyboard. +/// Needs the modules: run scripts/build-modules.sh (just test does). + +///| Rectangle of the panel module `id` (file stem), as last drawn. +fn rect_of(comp : @host.MoonPlasmaCompositor, id : String) -> @scene.Rect { + comp.shell.slot_rect(comp.shell.slot_of(id)) +} + +///| Centre of the panel module `id`. +fn center_of(comp : @host.MoonPlasmaCompositor, id : String) -> (Double, Double) raise { + let r = rect_of(comp, id) + assert_true(r.w > 0) + ((r.x + r.w / 2).to_double(), (r.y + r.h / 2).to_double()) +} + +///| Move to (x, y), press and release `btn`, then draw a frame. +fn click_at(comp : @host.MoonPlasmaCompositor, x : Int, y : Int, t : UInt, btn? : UInt = 272U) -> Unit { + comp.handle_input(@nested.InputEvent::PointerMove(x.to_double(), y.to_double()), t) + comp.handle_input(@nested.InputEvent::PointerButton(btn, true), t + 1U) + comp.handle_input(@nested.InputEvent::PointerButton(btn, false), t + 2U) + ignore(comp.compose_frame()) +} + +///| Click the centre of panel module `id`. +fn click_module(comp : @host.MoonPlasmaCompositor, id : String, t : UInt) -> Unit raise { + let (x, y) = center_of(comp, id) + click_at(comp, x.to_int(), y.to_int(), t) +} + +///| A fresh compositor with the default panel and a first frame drawn. +fn new_comp(tag : String) -> @host.MoonPlasmaCompositor { + let socket_path = "/tmp/wayland-moon-" + tag + "-" + @sys.getpid().to_string() + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + ignore(comp.compose_frame()) + comp +} ///| Drain everything the compositor sent this client as (object, opcode) pairs. fn drain_msgs(c : TestWaylandClient) -> Array[(UInt, UInt)] { @@ -37,6 +73,7 @@ fn has_msg(msgs : Array[(UInt, UInt)], obj : UInt, op : UInt) -> Bool { msgs.iter().any(m => m.0 == obj && m.1 == op) } + ///| test "host input reaches the focused client and the launcher popup opens" { let socket_path = "/tmp/wayland-moon-input-" + @@ -95,22 +132,16 @@ test "host input reaches the focused client and the launcher popup opens" { } assert_eq(comp.desired_cursor(), 9U) - // Launcher: click the button -> popup opens and swallows keys. + // Launcher module: click the button -> its popup opens and swallows keys. ignore(comp.compose_frame()) // lays out the panel - comp.handle_input(@nested.InputEvent::PointerMove(60.0, 700.0), 20U) - assert_eq(comp.desired_cursor(), 4U) // ...but the launcher button always shows a hand - comp.handle_input(@nested.InputEvent::PointerButton(0x110U, true), 21U) - comp.handle_input(@nested.InputEvent::PointerButton(0x110U, false), 22U) + let (lx, ly) = center_of(comp, "launcher") + comp.handle_input(@nested.InputEvent::PointerMove(lx, ly), 20U) + assert_eq(comp.desired_cursor(), 4U) // ...but panel modules always show a hand + click_at(comp, lx.to_int(), ly.to_int(), 21U) assert_true(comp.shell.popup_open()) + assert_true(comp.shell.slot_popup_rect(comp.shell.slot_of("launcher")).w > 0) comp.handle_input(@nested.InputEvent::Key(30U, true), 23U) - let after = drain_msgs(c) - assert_false(has_msg(after, kbd_id, 3U)) // swallowed by the launcher - // Typing fills the search field: evdev 20 = t, 18 = e (key 30 = a was typed above). - comp.handle_input(@nested.InputEvent::Key(20U, true), 26U) - comp.handle_input(@nested.InputEvent::Key(18U, true), 27U) - assert_eq(comp.shell.launcher_state.query, "ate") - comp.handle_input(@nested.InputEvent::Key(14U, true), 28U) - assert_eq(comp.shell.launcher_state.query, "at") + assert_false(has_msg(drain_msgs(c), kbd_id, 3U)) // swallowed by the launcher // Off the shell and off any window: default arrow. comp.handle_input(@nested.InputEvent::PointerMove(1270.0, 5.0), 25U) assert_eq(comp.desired_cursor(), 1U) @@ -146,3 +177,357 @@ test "dragging the divider between two tiled windows resizes them" { assert_true(right2.w > right.w + 200) assert_true(right2.x > left2.x + left2.w) } + +///| +test "the layout module opens a popup to pick Tiling, Monocle or Floating" { + let socket_path = "/tmp/wayland-moon-layout-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + let _a = open_and_configure_client(comp, socket_path, "A", "a") + let _b = open_and_configure_client(comp, socket_path, "B", "b") + ignore(comp.compose_frame()) + let slot = comp.shell.slot_of("layout") + let (cx, cy) = center_of(comp, "layout") + comp.handle_input(@nested.InputEvent::PointerMove(cx, cy), 1U) + assert_eq(comp.desired_cursor(), 4U) // it is a button: hand cursor + // Pick row `i` from the popup the button opens. + let pick = fn(i : Int, t : UInt) raise { + click_at(comp, cx.to_int(), cy.to_int(), t) // open + let pr = comp.shell.slot_popup_rect(slot) + assert_true(pr.w > 0) + click_at(comp, pr.x + pr.w / 2, pr.y + 4 + i * 28 + 14, t + 3U) + assert_eq(comp.shell.slot_popup_rect(slot).w, 0) + } + assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling) + let tiled_w = comp.windows.get(1UL).unwrap().geometry.w + // Opening alone changes nothing. + click_at(comp, cx.to_int(), cy.to_int(), 2U) + assert_true(comp.shell.slot_popup_rect(slot).w > 0) + assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling) + // Escape closes without picking. + comp.handle_input(@nested.InputEvent::Key(1U, true), 3U) + assert_eq(comp.shell.slot_popup_rect(slot).w, 0) + pick(1, 10U) + assert_eq(comp.layout_mode, @wm.LayoutMode::Monocle) + assert_true(comp.windows.get(1UL).unwrap().geometry.w > tiled_w + 100) + pick(2, 20U) + assert_eq(comp.layout_mode, @wm.LayoutMode::Floating) + pick(0, 30U) + assert_eq(comp.layout_mode, @wm.LayoutMode::Tiling) + assert_eq(comp.windows.get(1UL).unwrap().geometry.w, tiled_w) +} + +///| +test "title-bar buttons minimize, maximize and close windows" { + let socket_path = "/tmp/wayland-moon-btn-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + let (c, _shm, _surf, _xdg, tl, _deco) = open_and_configure_client(comp, socket_path, "A", "a") + let _b = open_and_configure_client(comp, socket_path, "B", "b") + ignore(comp.compose_frame()) + // Button centres, from the decoration layout (18px buttons, 10px from the right edge). + let btn = fn(wid : UInt64, n : Int) { + let g = comp.windows.get(wid).unwrap().geometry + let outer_w = g.w + 4 + let x = g.x - 2 + outer_w - 10 - 9 - (3 - n) * 26 + let y = g.y - 32 + 16 + (x, y) + } + let click = fn(p : (Int, Int), t : UInt) { + click_at(comp, p.0, p.1, t) + } + // Maximize window 1: it grows. + let w0 = comp.windows.get(1UL).unwrap().geometry.w + click(btn(1UL, 2), 1U) + assert_true(comp.windows.get(1UL).unwrap().geometry.w > w0) + click(btn(1UL, 2), 10U) + assert_eq(comp.windows.get(1UL).unwrap().geometry.w, w0) + // Minimize window 1: it leaves the stacking order, then its pill in the task list restores it. + click(btn(1UL, 1), 20U) + assert_true(comp.wm.windows.get(1UL).unwrap().minimized) + assert_true(!comp.wm.stacking_order().contains(1UL)) + let tasks = rect_of(comp, "tasks") + // pills: the visible window first, the minimized one second (140 wide, 6 apart) + click((tasks.x + 146 + 20, tasks.y + tasks.h / 2), 30U) + assert_true(!comp.wm.windows.get(1UL).unwrap().minimized) + // Close window 2: the client receives xdg_toplevel.close (opcode 1 on its toplevel). + ignore(drain_msgs(c)) + click(btn(1UL, 3), 40U) + for _i = 0; _i < 5; _i = _i + 1 { + comp.step() + @sys.sleep_ms(2) + } + assert_true(has_msg(drain_msgs(c), tl, 1U)) +} + +///| +test "the task list module focuses the window whose pill is clicked" { + let socket_path = "/tmp/wayland-moon-tasks-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + let _a = open_and_configure_client(comp, socket_path, "A", "a") + let _b = open_and_configure_client(comp, socket_path, "B", "b") + ignore(comp.compose_frame()) + let focused = fn() { + let mut f = 0UL + for id, w in comp.windows { + if w.focused { + f = id + } + } + f + } + let tasks = rect_of(comp, "tasks") + assert_true(tasks.w > 300) // the stretching module takes the free space + let first = comp.wm.stacking_order()[0] + click_at(comp, tasks.x + 20, tasks.y + tasks.h / 2, 1U) // pill 0 + assert_eq(focused(), first) + let other = comp.wm.stacking_order() + click_at(comp, tasks.x + 146 + 20, tasks.y + tasks.h / 2, 10U) // pill 1 + assert_true(focused() != first || other.length() == 1) +} + +///| +test "right-click a panel module to replace it in place, or remove it" { + let comp = new_comp("swap") + let before = comp.shell.slots() + let clock = rect_of(comp, "clock-digital12") + assert_true(clock.w > 0) + let find_row = fn(label : String) { + let mut i = -1 + for k = 0; k < comp.shell.menu_rows.length(); k = k + 1 { + if comp.shell.menu_rows[k].label == label { + i = k + } + } + i + } + click_at(comp, clock.x + clock.w / 2, clock.y + clock.h / 2, 1U, btn=273U) + assert_true(comp.shell.menu_open) + let m = comp.shell.menu_rect + assert_true(m.w > 0 && m.y + m.h <= clock.y) // above the panel, not off-screen + let bin = find_row("Replace with Binary Clock") + assert_true(bin >= 0) + assert_true(find_row("Remove widget") >= 0) + assert_true(find_row("Module manager...") >= 0) + // Hover the row (hand cursor), click it: the binary clock takes the digital clock's place. + let ix = m.x + m.w / 2 + let iy = m.y + 26 + 28 * bin + 14 + comp.handle_input(@nested.InputEvent::PointerMove(ix.to_double(), iy.to_double()), 10U) + assert_eq(comp.desired_cursor(), 4U) + click_at(comp, ix, iy, 11U) + assert_true(!comp.shell.menu_open) + assert_eq(comp.shell.slot_of("clock-digital12"), "") + let after = comp.shell.slots() + assert_eq(after.length(), before.length()) + assert_eq(after[after.length() - 1], comp.shell.slot_of("clock-binary")) // same place in the panel + assert_true(rect_of(comp, "clock-binary").w > 0) + // Escape dismisses the menu; "Remove widget" unloads the module. + let moon = rect_of(comp, "moon-disc") + click_at(comp, moon.x + moon.w / 2, moon.y + moon.h / 2, 20U, btn=273U) + assert_true(comp.shell.menu_open) + comp.handle_input(@nested.InputEvent::Key(1U, true), 30U) + assert_true(!comp.shell.menu_open) + click_at(comp, moon.x + moon.w / 2, moon.y + moon.h / 2, 40U, btn=273U) + let m2 = comp.shell.menu_rect + click_at(comp, m2.x + m2.w / 2, m2.y + 26 + 28 * find_row("Remove widget") + 14, 50U) + assert_eq(comp.shell.slot_of("moon-disc"), "") + assert_eq(comp.shell.slots().length(), before.length() - 1) +} + +///| +test "tapping Super toggles the launcher; Super+key does not" { + let comp = new_comp("super") + let tap = fn(t : UInt) { + comp.handle_input(@nested.InputEvent::Key(125U, true), t) + comp.handle_input(@nested.InputEvent::Key(125U, false), t + 1U) + } + assert_false(comp.shell.popup_open()) + tap(1U) + assert_true(comp.shell.popup_open()) + tap(3U) + assert_false(comp.shell.popup_open()) + // Super held while another key is pressed: not a tap. + comp.handle_input(@nested.InputEvent::Key(125U, true), 5U) + comp.handle_input(@nested.InputEvent::Key(30U, true), 6U) + comp.handle_input(@nested.InputEvent::Key(30U, false), 7U) + comp.handle_input(@nested.InputEvent::Key(125U, false), 8U) + assert_false(comp.shell.popup_open()) +} + +///| +test "the panel is saved to panel.edn and restored" { + // Never touch the user's real config: only run when a scratch dir is provided. + if @sys.getenv("MOON_PLASMA_TEST_CONFIG") == "1" { + let theme = @scene.ThemeTokens::moon_night() + let a = @shell.DesktopShell::new("x") + a.persist = true + a.set_output(theme, 1280, 720) + assert_true(a.unload_slot(a.slot_of("moon-disc"))) + assert_true(a.load_module("clock-binary")) + let b = @shell.DesktopShell::new("x") + b.persist = true + b.set_output(theme, 1280, 720) + assert_eq(b.slot_of("moon-disc"), "") + assert_true(b.slot_of("clock-binary") != "") + assert_eq(b.slots().length(), a.slots().length()) + } +} + +///| +test "the wasm picker opens the module manager, which loads and unloads modules" { + let comp = new_comp("manager") + // The manager is not in the default panel: the picker loads it on demand. + assert_eq(comp.shell.slot_of("module-manager"), "") + let n0 = comp.shell.slots().length() + // Right-click empty panel space (the margin): the menu offers the module manager. + let panel = comp.shell.panel_rect + click_at(comp, 1, panel.y + 5, 1U, btn=273U) + assert_true(comp.shell.menu_open) + assert_eq(comp.shell.menu_rows[0].label, "Module manager...") + let m = comp.shell.menu_rect + click_at(comp, m.x + m.w / 2, m.y + 26 + 14, 10U) + assert_eq(comp.shell.slots().length(), n0 + 1) + let mgr = comp.shell.slot_of("module-manager") + assert_true(mgr != "") + ignore(comp.compose_frame()) + let pr = comp.shell.slot_popup_rect(mgr) + assert_true(pr.w > 0) // the picker opened the app's popup + // Rows: header(24), one per loaded module (28), header(24), one per available module (28), browse. + let loaded = comp.shell.slots().length() + let avail_y = fn(k : Int) { pr.y + 4 + 24 + loaded * 28 + 24 + k * 28 + 14 } + let mut k_bin = -1 + for k = 0; k < comp.shell.catalog.length(); k = k + 1 { + if comp.shell.catalog[k].id == "clock-binary" { + k_bin = k + } + } + assert_true(k_bin >= 0) + assert_eq(comp.shell.slot_of("clock-binary"), "") + click_at(comp, pr.x + 40, avail_y(k_bin), 20U) // select it: it is loaded into the panel + assert_true(comp.shell.slot_of("clock-binary") != "") + assert_eq(comp.shell.slots().length(), loaded + 1) + // The popup stays open; click the loaded module's row to unload it again. + let pr2 = comp.shell.slot_popup_rect(mgr) + assert_true(pr2.w > 0) + let slots = comp.shell.slots() + let mut idx = -1 + for i = 0; i < slots.length(); i = i + 1 { + if slots[i] == comp.shell.slot_of("clock-binary") { + idx = i + } + } + click_at(comp, pr2.x + 40, pr2.y + 4 + 24 + idx * 28 + 14, 30U) + assert_eq(comp.shell.slot_of("clock-binary"), "") + assert_eq(comp.shell.slots().length(), loaded) + // The manager is just another module: it can be removed too, and the picker brings it back. + assert_true(comp.shell.unload_slot(mgr)) + assert_eq(comp.shell.slot_of("module-manager"), "") + assert_true(comp.shell.open_module_manager()) + assert_true(comp.shell.slot_of("module-manager") != "") +} + +///| +test "dragging a panel module reorders it" { + let comp = new_comp("wdrag") + let order0 = comp.shell.slots() + let moon = rect_of(comp, "moon-disc") + let clock = rect_of(comp, "clock-digital12") + assert_true(moon.x < clock.x) + let cy = (clock.y + clock.h / 2).to_double() + comp.handle_input(@nested.InputEvent::PointerMove((clock.x + clock.w / 2).to_double(), cy), 1U) + assert_eq(comp.desired_cursor(), 4U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), 2U) + // Drag the clock left past the moon. + comp.handle_input(@nested.InputEvent::PointerMove((moon.x + 2).to_double(), cy), 3U) + assert_eq(comp.desired_cursor(), 17U) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), 4U) + ignore(comp.compose_frame()) + let order1 = comp.shell.slots() + assert_eq(order1.length(), order0.length()) + assert_true(order1 != order0) + assert_eq(order1[order1.length() - 2], comp.shell.slot_of("clock-digital12")) + assert_true(rect_of(comp, "clock-digital12").x < rect_of(comp, "moon-disc").x) + assert_true(comp.desired_cursor() != 17U) +} + +///| +test "any .wasm plasmoid can be loaded from a path and unloaded again" { + let comp = new_comp("path") + let n0 = comp.shell.slots().length() + let theme = @scene.ThemeTokens::moon_night() + ignore(theme) + assert_true(comp.shell.load_path("compositor/wasm/testdata/clock-digital.component.wasm") is Some(_)) + assert_eq(comp.shell.slots().length(), n0 + 1) + ignore(comp.compose_frame()) + let slot = comp.shell.slots()[n0] + assert_true(comp.shell.slot_rect(slot).w > 0) // it got a panel placement and was drawn + assert_true(comp.shell.load_path("compositor/wasm/testdata/missing.wasm") is None) + assert_eq(comp.shell.slots().length(), n0 + 1) + // It unloads like any module. + assert_true(comp.shell.unload_slot(slot)) + ignore(comp.compose_frame()) + assert_eq(comp.shell.slot_rect(slot).w, 0) +} + +///| +test "modules are added until the panel is full" { + let comp = new_comp("full") + let n0 = comp.shell.slots().length() + let mut added = 0 + for _i = 0; _i < 40; _i = _i + 1 { + if comp.shell.load_module("moon-disc") { + added = added + 1 + } + } + assert_true(added > 2 && added < 40) + assert_eq(comp.shell.slots().length(), n0 + added) + ignore(comp.compose_frame()) + assert_true(rect_of(comp, "moon-disc").w > 0) +} + +///| +test "Desktop Pulse reads live machine and window state through its granted interfaces and can raise a window" { + let socket_path = "/tmp/wayland-moon-pulse-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + let _a = open_and_configure_client(comp, socket_path, "A", "a") + let _b = open_and_configure_client(comp, socket_path, "B", "b") + ignore(comp.compose_frame()) + let n0 = comp.shell.slots().length() + assert_true(comp.shell.load_path("compositor/wasm/testdata/pulse.component.wasm") is Some(_)) + // Its capability grant is exactly what the component imports; nothing else is reachable. + let slot = comp.shell.slots()[n0] + let w = comp.shell.widgets[n0] + assert_eq(w.slot, slot) + assert_eq(w.caps.length(), 3) + assert_true(w.caps.contains("system") && w.caps.contains("theme") && w.caps.contains("windows")) + ignore(comp.compose_frame()) + // The host provider fed it real numbers and the window list. + assert_true(comp.shell.sampler.cur.mem_total_kib > 0L) + assert_true(comp.shell.sampler.cur.uptime_secs > 0L) + assert_eq(comp.shell.win_list.length(), 2) + let r = comp.shell.slot_rect(slot) + assert_true(r.w >= 300) + // Clicking each window's chip raises that window (first chip starts at x = 280). + for i = 0; i < 2; i = i + 1 { + let id = comp.shell.win_list[i].id + let cx = r.x + 280 + i * 23 + 10 + let cy = r.y + r.h / 2 + comp.handle_input(@nested.InputEvent::PointerMove(cx.to_double(), cy.to_double()), (10 + i * 4).reinterpret_as_uint()) + comp.handle_input(@nested.InputEvent::PointerButton(272U, true), (11 + i * 4).reinterpret_as_uint()) + comp.handle_input(@nested.InputEvent::PointerButton(272U, false), (12 + i * 4).reinterpret_as_uint()) + ignore(comp.compose_frame()) + assert_true(comp.windows.get(id).unwrap().focused) + let others_focused = comp.windows.iter().filter(kv => kv.0 != id && kv.1.focused).count() + assert_eq(others_focused, 0) + } +} diff --git a/compositor/host/inspector_test.mbt b/compositor/host/inspector_test.mbt new file mode 100644 index 0000000..e9b13a7 --- /dev/null +++ b/compositor/host/inspector_test.mbt @@ -0,0 +1,58 @@ +///| Interface Explorer: toggle from the panel, hover components, see their WIT. + +///| +test "inspector shows the WIT interface of the hovered component" { + let socket_path = "/tmp/wayland-moon-inspect-" + + @sys.getpid().to_string() + + ".sock" + let theme = @scene.ThemeTokens::moon_night() + let comp = @host.MoonPlasmaCompositor::new(socket_path, theme, 1280, 720).unwrap() + let (c, shm, surf, xdg, _tl, _deco) = open_and_configure_client( + comp, socket_path, "T", "t", + ) + commit_shm_frame(comp, c, shm, surf, xdg, 1UL) + ignore(comp.compose_frame()) // lays out the panel + assert_false(comp.shell.inspecting()) + + // Open the apps popup first; turning the explorer on must not close it. + let (lx, ly) = center_of(comp, "launcher") + click_at(comp, lx.to_int(), ly.to_int(), 0U) + assert_true(comp.shell.popup_open()) + + // Click the Interface Explorer button to turn inspect mode on. + let (bx, by) = center_of(comp, "inspector") + click_at(comp, bx.to_int(), by.to_int(), 1U) + assert_true(comp.shell.inspecting()) + assert_true(comp.shell.popup_open()) + assert_eq(comp.desired_cursor(), 4U) + + // Hover the launcher. + let (lx, ly) = center_of(comp, "launcher") + comp.handle_input(@nested.InputEvent::PointerMove(lx, ly), 4U) + let lslot = comp.shell.slot_of("launcher") + assert_eq(comp.shell.hover_id, lslot) + assert_eq(comp.desired_cursor(), 3U) + // The explorer describes the module's real binary: what it exports and which capabilities it imports. + let lines = comp.shell.inspector_lines_for(lslot) + assert_true(lines.iter().any(l => l.has_prefix("# plasmoid"))) + assert_true(lines.iter().any(l => l.has_prefix("# app launch"))) + assert_true(lines.iter().any(l => l.has_prefix("# app catalog"))) + let frame = comp.compose_frame() + let png = @renderer.encode_png(frame) + ignore(@sys.write_file_bytes("_build/inspector_launcher.png", png)) + + // Clock, panel, window title bar and desktop resolve to their own components. + let (cx, cy) = center_of(comp, "clock-digital12") + comp.handle_input(@nested.InputEvent::PointerMove(cx, cy), 5U) + assert_eq(comp.shell.hover_id, comp.shell.slot_of("clock-digital12")) + comp.handle_input(@nested.InputEvent::PointerMove(1270.0, 5.0), 6U) + assert_eq(comp.shell.hover_id, "desktop") + + // Clicks are swallowed while inspecting; Escape leaves the mode. + comp.handle_input(@nested.InputEvent::PointerButton(0x110U, true), 7U) + assert_true(comp.shell.popup_open()) // unchanged: the click was swallowed + comp.handle_input(@nested.InputEvent::Key(1U, true), 8U) + assert_false(comp.shell.inspecting()) + comp.close() +} + diff --git a/compositor/host/moon.pkg b/compositor/host/moon.pkg index bd9ccc6..f9ffbe2 100644 --- a/compositor/host/moon.pkg +++ b/compositor/host/moon.pkg @@ -4,10 +4,20 @@ import { "moonplasma/desktop/compositor/sys" @sys, "moonplasma/desktop/compositor/scene" @scene, "moonplasma/desktop/compositor/shell" @shell, + "moonplasma/desktop/compositor/wasm" @wasm, "moonplasma/desktop/compositor/nested" @nested, + "moonplasma/desktop/compositor/font" @font, "moonplasma/desktop/compositor/renderer" @renderer, "moonplasma/desktop/compositor/wayland" @wayland, "moonplasma/desktop/compositor/gfx" @gfx, } supported_targets = "-all+native" + +options( + link: { + "native": { + "cc-link-flags": "-lwasmer", + }, + }, +) diff --git a/compositor/nested/nested.mbt b/compositor/nested/nested.mbt index 655c098..ec0640f 100644 --- a/compositor/nested/nested.mbt +++ b/compositor/nested/nested.mbt @@ -7,6 +7,8 @@ pub(all) enum InputEvent { PointerMove(Double, Double) PointerButton(UInt, Bool) + /// Vertical wheel scroll in wl_fixed units / 256 (positive = down). + Scroll(Double) Key(UInt, Bool) Modifiers(UInt, UInt, UInt, UInt) } @@ -241,6 +243,14 @@ fn NestedWindow::dispatch( let state = r.u32() self.input.push(PointerButton(button, state == 1U)) } + 4U => { + let _time = r.u32() + let axis = r.u32() + let value = r.i32().to_double() / 256.0 + if axis == 0U { + self.input.push(Scroll(value)) + } + } _ => () } } else if self.live_buffers.contains(obj) { diff --git a/compositor/renderer/pkg.generated.mbti b/compositor/renderer/pkg.generated.mbti index bf148ac..5fbbd70 100644 --- a/compositor/renderer/pkg.generated.mbti +++ b/compositor/renderer/pkg.generated.mbti @@ -16,9 +16,23 @@ pub fn encode_ppm(Pixmap) -> Bytes pub fn render_scene(@scene.SceneGraph) -> Pixmap +pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit + +pub fn text_width(String, Int32, Bool, Bool) -> Int32 + // Errors // Types and methods +pub(all) struct Glyph { + w : Int32 + h : Int32 + xoff : Int32 + yoff : Int32 + advance : Int32 + coverage : Bytes + embolden : Bool +} + pub(all) struct Pixmap { width : Int32 height : Int32 diff --git a/compositor/renderer/renderer.mbt b/compositor/renderer/renderer.mbt index 819fdfe..f0e9b77 100644 --- a/compositor/renderer/renderer.mbt +++ b/compositor/renderer/renderer.mbt @@ -259,13 +259,22 @@ fn draw_circle( let cg = color.g.to_int() let cb = color.b.to_int() let ca = color.a.to_int() - let r2 = radius * radius - let inner_r2 = if radius > 1 { (radius - 1) * (radius - 1) } else { 0 } - for dy = -radius; dy <= radius; dy = dy + 1 { - for dx = -radius; dx <= radius; dx = dx + 1 { - let d2 = dx * dx + dy * dy - if d2 <= r2 && (filled || d2 >= inner_r2) { - blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, ca, clip) + // Antialiased: per-pixel coverage from the distance to the edge (1px wide ring when unfilled). + let rad = radius.to_double() + for dy = -radius - 1; dy <= radius + 1; dy = dy + 1 { + for dx = -radius - 1; dx <= radius + 1; dx = dx + 1 { + let d = (dx * dx + dy * dy).to_double().sqrt() + let outer = rad + 0.5 - d + let mut cov = if outer > 1.0 { 1.0 } else { outer } + if !filled { + let inner = d - (rad - 1.0 - 0.5) + let ic = if inner > 1.0 { 1.0 } else { inner } + if ic < cov { + cov = ic + } + } + if cov > 0.02 { + blend_pixel(dst, cx + dx, cy + dy, cr, cg, cb, (ca.to_double() * cov).round().to_int(), clip) } } } @@ -378,8 +387,98 @@ fn glyph_rows(ch : Int) -> Array[Int] { } } +///| A rasterised glyph: 8-bit coverage `w`x`h`, top-left at (xoff, yoff) +/// relative to the pen position on the baseline. +pub(all) struct Glyph { + w : Int + h : Int + xoff : Int + yoff : Int + advance : Int + coverage : Bytes + /// Draw twice, 1px apart (faces without a real bold). + embolden : Bool +} + +///| Optional real-font glyph source: (codepoint, pixel size, bold) -> glyph. +/// Unset (e.g. in wasm builds), text uses the built-in 5x7 bitmap font. +let glyph_source : Ref[((Int, Int, Bool, Bool) -> Glyph)?] = { val: None } + +///| +pub fn set_glyph_source(f : (Int, Int, Bool, Bool) -> Glyph) -> Unit { + glyph_source.val = Some(f) +} + +///| Pixel width `text` would occupy when drawn with the given face. +pub fn text_width(text : String, size : Int, bold : Bool, mono : Bool) -> Int { + match glyph_source.val { + Some(src) => { + let mut w = 0 + for ch in text { + let g = src(ch.to_int(), size, bold, mono) + w = w + g.advance + (if g.embolden { 1 } else { 0 }) + } + w + } + None => text.length() * (if size >= 14 { 12 } else { 6 }) + } +} + +///| +fn draw_text_font( + dst : Pixmap, + src : (Int, Int, Bool, Bool) -> Glyph, + mono : Bool, + x : Int, + y : Int, + text : String, + size : Int, + color : @scene.Rgba, + align : @scene.TextAlign, + bold : Bool, + clip : @scene.Rect?, +) -> Unit { + let glyphs : Array[Glyph] = [] + let mut total_w = 0 + for ch in text { + let g = src(ch.to_int(), size, bold, mono) + glyphs.push(g) + total_w = total_w + g.advance + (if g.embolden { 1 } else { 0 }) + } + let start_x = match align { + Left => x + Center => x - total_w / 2 + Right => x - total_w + } + // `y` is the vertical centre of the text; centre the capital height on it. + let cap = src(72, size, false, mono) // 'H' + let baseline = y + (-cap.yoff) / 2 + let cr = color.r.to_int() + let cg = color.g.to_int() + let cb = color.b.to_int() + let ca = color.a.to_int() + let mut pen = start_x + for g in glyphs { + for row = 0; row < g.h; row = row + 1 { + for col = 0; col < g.w; col = col + 1 { + let cov = g.coverage[row * g.w + col].to_int() + if cov > 0 { + let px = pen + g.xoff + col + let py = baseline + g.yoff + row + blend_pixel(dst, px, py, cr, cg, cb, ca * cov / 255, clip) + if g.embolden { + blend_pixel(dst, px + 1, py, cr, cg, cb, ca * cov / 255, clip) + } + } + } + } + pen = pen + g.advance + (if g.embolden { 1 } else { 0 }) + } +} + ///| fn draw_text( + mono : Bool, dst : Pixmap, x : Int, y : Int, @@ -393,6 +492,13 @@ fn draw_text( if text.length() == 0 || color.a.to_int() == 0 { return } + match glyph_source.val { + Some(src) => { + draw_text_font(dst, src, mono, x, y, text, size, color, align, bold, clip) + return + } + None => () + } let scale = if size >= 14 { 2 } else { 1 } let char_w = 6 * scale let total_w = text.length() * char_w @@ -469,7 +575,9 @@ pub fn draw_ops( Circle(cx, cy, rad, col, filled) => draw_circle(dst, cx + ox, cy + oy, rad, col, filled, cur_clip) Text(x, y, txt, sz, col, align, bold) => - draw_text(dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip) + draw_text(false, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip) + MonoText(x, y, txt, sz, col, align, bold) => + draw_text(true, dst, x + ox, y + oy, txt, sz, col, align, bold, cur_clip) PushClip(r) => clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h)) PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) } @@ -486,6 +594,26 @@ pub fn blit_shm_surface( if buf.width <= 0 || buf.height <= 0 || dst_rect.w <= 0 || dst_rect.h <= 0 { return } + // While the client catches up with a resize, its buffer is smaller than the window: + // extend the buffer's bottom-right colour over the rest instead of showing the wallpaper. + if (buf.width < dst_rect.w || buf.height < dst_rect.h) && + buf.stride * buf.height <= buf.bytes.length() && + buf.width > 0 { + let o = (buf.height - 1) * buf.stride + (buf.width - 1) * 4 + let a = if buf.format == 1 { 255 } else { buf.bytes[o + 3].to_int() } + fill_rounded_rect( + dst, + dst_rect, + @scene.Rgba::new( + buf.bytes[o + 2].to_int(), + buf.bytes[o + 1].to_int(), + buf.bytes[o].to_int(), + a, + ), + 0, + None, + ) + } let copy_w = if buf.width < dst_rect.w { buf.width } else { dst_rect.w } let copy_h = if buf.height < dst_rect.h { buf.height } else { dst_rect.h } let is_xrgb = buf.format == 1 diff --git a/compositor/scene/pkg.generated.mbti b/compositor/scene/pkg.generated.mbti index aa55013..8ed4c5a 100644 --- a/compositor/scene/pkg.generated.mbti +++ b/compositor/scene/pkg.generated.mbti @@ -28,6 +28,7 @@ pub(all) enum DrawOp { Line(Int32, Int32, Int32, Int32, Rgba, Int32) Circle(Int32, Int32, Int32, Rgba, Bool) Text(Int32, Int32, String, Int32, Rgba, TextAlign, Bool) + MonoText(Int32, Int32, String, Int32, Rgba, TextAlign, Bool) PushClip(Rect) PopClip } diff --git a/compositor/scene/scene.mbt b/compositor/scene/scene.mbt index 616f73c..7da987f 100644 --- a/compositor/scene/scene.mbt +++ b/compositor/scene/scene.mbt @@ -224,6 +224,8 @@ pub(all) enum DrawOp { Line(Int, Int, Int, Int, Rgba, Int) Circle(Int, Int, Int, Rgba, Bool) Text(Int, Int, String, Int, Rgba, TextAlign, Bool) + /// Same as Text but in the monospace face (code listings). + MonoText(Int, Int, String, Int, Rgba, TextAlign, Bool) PushClip(Rect) PopClip } diff --git a/compositor/shell/apps.mbt b/compositor/shell/apps.mbt new file mode 100644 index 0000000..a2cae31 --- /dev/null +++ b/compositor/shell/apps.mbt @@ -0,0 +1,166 @@ +///| Installed desktop applications, discovered from freedesktop `.desktop` files +/// (XDG data dirs + flatpak exports). Feeds the launcher's search. + +///| +priv struct DesktopApp { + id : String + name : String + comment : String + category : String + command : String +} + +///| Directories scanned, lowest priority first (later ones override by file name). +fn app_dirs() -> Array[String] { + let home = @sys.getenv("HOME") + let data_home = { + let x = @sys.getenv("XDG_DATA_HOME") + if x.length() > 0 { x } else { home + "/.local/share" } + } + let dirs : Array[String] = [] + let xdg = @sys.getenv("XDG_DATA_DIRS") + let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" } + let parts : Array[String] = list.split(":").map(x => x.to_string()).collect() + // XDG_DATA_DIRS is highest priority first; we want lowest first. + for i = parts.length() - 1; i >= 0; i = i - 1 { + if parts[i].length() > 0 { + dirs.push(parts[i] + "/applications") + } + } + dirs.push("/var/lib/flatpak/exports/share/applications") + dirs.push(home + "/.local/share/flatpak/exports/share/applications") + dirs.push(data_home + "/applications") + dirs +} + +///| Drop Exec field codes (%f %U ...), keep a literal %%. +fn clean_exec(exec : String) -> String { + let sb = StringBuilder::new() + let chars = exec.to_array() + let mut i = 0 + while i < chars.length() { + if chars[i] == '%' && i + 1 < chars.length() { + if chars[i + 1] == '%' { + sb.write_char('%') + } + i = i + 2 + } else { + sb.write_char(chars[i]) + i = i + 1 + } + } + sb.to_string().trim(chars=" ").to_string() +} + +///| Parse one .desktop file; None when it should not be listed. +fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp? { + let mut in_entry = false + let mut name = "" + let mut generic = "" + let mut comment = "" + let mut exec = "" + let mut cats = "" + let mut hidden = false + let mut terminal = false + let mut kind = "Application" + for raw in text.split("\n") { + let line = raw.trim(chars=" \r\t").to_string() + if line.length() == 0 || line.has_prefix("#") { + continue + } + if line.has_prefix("[") { + in_entry = line == "[Desktop Entry]" + continue + } + if !in_entry { + continue + } + match line.find("=") { + None => () + Some(eq) => { + let key = line[:eq].trim(chars=" ").to_string() + let val = line[eq + 1:].trim(chars=" ").to_string() + match key { + "Name" => name = val + "GenericName" => generic = val + "Comment" => comment = val + "Exec" => exec = val + "Categories" => cats = val + "Type" => kind = val + "NoDisplay" | "Hidden" => if val == "true" { hidden = true } + "Terminal" => terminal = val == "true" + _ => () + } + } + } + } + if hidden || kind != "Application" || name.length() == 0 || exec.length() == 0 { + return None + } + if terminal && !have_terminal { + return None + } + let mut command = clean_exec(exec) + if terminal { + command = "foot -e " + command + } + let category = match cats.split(";").next() { + Some(c) if c.length() > 0 => c.to_string() + _ => "Other" + } + let comment = if comment.length() > 0 { comment } else { generic } + Some({ id, name, comment, category, command }) +} + +///| Scan every applications dir; later dirs override earlier ones, result sorted by name. +fn scan_desktop_apps() -> Array[DesktopApp] { + let have_terminal = @sys.has_exe("foot") + let by_id : Map[String, DesktopApp] = {} + let removed : Map[String, Bool] = {} + for dir in app_dirs() { + for file in @sys.list_desktop_files(dir) { + let bytes = @sys.read_file_bytes(dir + "/" + file) + let id = file[:file.length() - 8].to_string() + match parse_desktop(id, @utf8.decode_lossy(bytes), have_terminal) { + Some(app) => { + by_id.set(id, app) + removed.remove(id) + } + None => { + by_id.remove(id) + } + } + } + } + let apps : Array[DesktopApp] = [] + for _, a in by_id { + apps.push(a) + } + apps.sort_by(fn(a, b) { + let x = a.name.to_lower() + let y = b.name.to_lower() + if x < y { -1 } else if x > y { 1 } else { 0 } + }) + apps +} + +///| +test "parse_desktop reads a normal entry and strips field codes" { + let t = "[Desktop Entry]\nType=Application\nName=Firefox\nName[de]=Feuerfuchs\nComment=Browse\nExec=firefox %u\nCategories=Network;WebBrowser;\n[Desktop Action x]\nName=Nope\n" + match parse_desktop("firefox", t, true) { + Some(a) => { + assert_eq(a.name, "Firefox") + assert_eq(a.command, "firefox") + assert_eq(a.category, "Network") + assert_eq(a.comment, "Browse") + } + None => fail("expected entry") + } +} + +///| +test "parse_desktop hides NoDisplay entries" { + let t = "[Desktop Entry]\nType=Application\nName=X\nExec=x\nNoDisplay=true\n" + assert_true(parse_desktop("x", t, true) is None) +} + diff --git a/compositor/shell/desktop_widget.mbt b/compositor/shell/desktop_widget.mbt new file mode 100644 index 0000000..fd860ee --- /dev/null +++ b/compositor/shell/desktop_widget.mbt @@ -0,0 +1,44 @@ +///| Desktop widget: a card on the wallpaper (below all windows, top-right) showing +/// the time, the date and the current moon phase. Built from the same pure lib/* +/// renderers as the panel widgets. + +///| +let desktop_widget_w : Int = 260 + +///| +let desktop_widget_h : Int = 120 + +///| +fn render_desktop_widget( + screen_w : Int, + tokens : @theme.Tokens, + at : @types.Datetime, + out : Array[@scene.DrawOp], +) -> Unit { + let r = tokens.radius.reinterpret_as_int() + let hour = at.hour.to_int() + let minute = at.minute.to_int() + let time = @timefmt.hhmm12(hour, minute) + let date = @timefmt.weekday_short(at.weekday.to_int()) + + ", " + + at.day.to_int().to_string() + + " " + + @timefmt.month_short(at.month.to_int()) + let p = @moon.phase(at.year.reinterpret_as_int(), at.month.to_int(), at.day.to_int()) + let ops : Array[@types.DrawOp] = [ + @ui.fill_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.surface, radius=r), + @ui.stroke_rect(@ui.rect(0, 0, desktop_widget_w, desktop_widget_h), tokens.palette.border, width=1, radius=r), + @ui.text(18, 38, time, 32, tokens.palette.foreground, bold=true), + @ui.text(18, 74, date, tokens.font_size.reinterpret_as_int(), tokens.palette.foreground), + @ui.text( + 18, + 98, + @moon.phase_name(p) + " " + @moon.illumination(p).to_string() + "%", + tokens.font_size.reinterpret_as_int() - 2, + tokens.palette.foreground, + ), + ] + let x0 = screen_w - desktop_widget_w - 24 + translate(ops, x0, 24, out) + translate(@moon.render_disc(@ui.size(56, 56), tokens, p), x0 + desktop_widget_w - 56 - 18, 24 + 18, out) +} diff --git a/compositor/shell/humanise.mbt b/compositor/shell/humanise.mbt new file mode 100644 index 0000000..bcaa9b9 --- /dev/null +++ b/compositor/shell/humanise.mbt @@ -0,0 +1,429 @@ +///| Turns WIT source into narrative prose for the Interface Explorer. +/// +/// Output is one paragraph per line (the renderer word-wraps), with `""` between +/// paragraphs. A `# ` prefix marks a heading. Terms are wrapped in `**bold**`. + +///| +fn trim(s : String) -> String { + s.trim(chars=" \t\r").to_string() +} + +///| "window-state" -> "window state" +fn dashes(s : String) -> String { + let sb = StringBuilder::new() + for ch in s { + sb.write_char(if ch == '-' { ' ' } else { ch }) + } + sb.to_string() +} + +///| +fn pad(n : Int) -> String { + let sb = StringBuilder::new() + for _i = 0; _i < n; _i = _i + 1 { + sb.write_char(' ') + } + sb.to_string() +} + +///| Split on `sep` outside <...>, (...) and {...}. +fn split_top(s : String, sep : Char) -> Array[String] { + let out : Array[String] = [] + let mut depth = 0 + let mut start = 0 + for i = 0; i < s.length(); i = i + 1 { + let ch = s[i] + if ch == '<' || ch == '(' || ch == '{' { + depth = depth + 1 + } else if ch == '>' || ch == ')' || ch == '}' { + depth = depth - 1 + } else if ch == sep.to_int().to_uint16() && depth == 0 { + out.push(trim(s[start:i].to_string())) + start = i + 1 + } + } + let last = trim(s[start:].to_string()) + if last.length() > 0 { + out.push(last) + } + out +} + +///| Index of `ch` in `s`, or -1. +fn index_of(s : String, ch : Char) -> Int { + for i = 0; i < s.length(); i = i + 1 { + if s[i] == ch.to_int().to_uint16() { + return i + } + } + -1 +} + +///| Index of the last `ch` in `s`, or -1. +fn last_index_of(s : String, ch : Char) -> Int { + for i = s.length() - 1; i >= 0; i = i - 1 { + if s[i] == ch.to_int().to_uint16() { + return i + } + } + -1 +} + +///| A WIT type in words. +fn ty(t0 : String) -> String { + let t = trim(t0) + match t { + "string" => "text" + "bool" => "yes/no" + "u8" | "u16" | "u32" | "u64" | "s8" | "s16" | "s32" | "s64" | "f32" | "f64" => + "number" + "char" => "a character" + "_" => "nothing" + _ => { + let lt = index_of(t, '<') + if lt > 0 && t.has_suffix(">") { + let head = t[:lt].to_string() + let args = split_top(t[lt + 1:t.length() - 1].to_string(), ',') + let a0 = if args.length() > 0 { ty(args[0]) } else { "" } + match head { + "list" => "list of " + a0 + "option" => "optional " + a0 + "borrow" | "own" => a0 + "tuple" => "(" + args.map(ty).join(", ") + ")" + "result" => { + let err = if args.length() > 1 { ty(args[1]) } else { "" } + let ok = if a0 == "nothing" { "success" } else { a0 } + if err == "" || err == "nothing" { + ok + ", or failure" + } else { + ok + ", or an error (" + err + ")" + } + } + _ => dashes(t) + } + } else { + dashes(t) + } + } + } +} + +///| Strip "///" and one space. +fn doc_text(l : String) -> String { + trim(trim(l)[3:].to_string()) +} + +///| +fn bold(s : String) -> String { + "**" + s + "**" +} + +///| Join with commas and a final "and". +fn and_list(items : Array[String]) -> String { + if items.length() == 0 { + "nothing" + } else if items.length() == 1 { + items[0] + } else { + items[:items.length() - 1].to_array().join(", ") + + " and " + + items[items.length() - 1] + } +} + +///| Docs as running text, with a trailing space if non-empty. +fn doc_prose(docs : Array[String]) -> String { + if docs.length() == 0 { + "" + } else { + let t = docs.join(" ") + (if t.has_suffix(".") { t } else { t + "." }) + " " + } +} + +///| "name: func(a: t, b: t) -> r" as one sentence. +fn func_sentence(entry : String) -> String { + let c = index_of(entry, ':') + let name = dashes(trim(entry[:c].to_string())) + let rest = entry[c + 1:].to_string() + let open = index_of(rest, '(') + let mut depth = 0 + let mut close = -1 + for i = open; i >= 0 && i < rest.length(); i = i + 1 { + if rest[i] == '(' { + depth = depth + 1 + } else if rest[i] == ')' { + depth = depth - 1 + if depth == 0 { + close = i + break + } + } + } + let params = if open >= 0 && close > open { + split_top(rest[open + 1:close].to_string(), ',') + } else { + [] + } + let after = if close >= 0 { rest[close + 1:].to_string() } else { "" } + let arrow = after.find("->") + let ret = match arrow { + Some(i) => trim(after[i + 2:].to_string()) + None => "" + } + let gives = if ret == "" { "returns nothing" } else { "returns " + ty(ret) } + if params.length() == 0 { + bold(name) + " " + gives + "." + } else { + let ps = params.map(fn(p) { + let pc = index_of(p, ':') + if pc < 0 { + bold(dashes(p)) + } else { + bold(dashes(trim(p[:pc].to_string()))) + + " (" + + ty(p[pc + 1:].to_string()) + + ")" + } + }) + bold(name) + " takes " + and_list(ps) + " and " + gives + "." + } +} + +///| One field / case / call as a clause, plus its docs. +fn entry_sentence(kind : String, entry : String, docs : Array[String]) -> String { + let e = trim(entry) + let body = if e.contains(": func(") { + func_sentence(e) + } else if kind == "record" { + let c = index_of(e, ':') + if c >= 0 { + bold(dashes(trim(e[:c].to_string()))) + " is " + ty(e[c + 1:].to_string()) + "." + } else { + bold(dashes(e)) + "." + } + } else if kind == "variant" { + let p = index_of(e, '(') + if p > 0 && e.has_suffix(")") { + bold(dashes(e[:p].to_string())) + + " carries " + + ty(e[p + 1:e.length() - 1].to_string()) + + "." + } else { + bold(dashes(e)) + " carries nothing." + } + } else { + bold(dashes(e)) + "." + } + body + (if docs.length() > 0 { " " + doc_prose(docs).trim(chars=" ").to_string() } else { "" }) +} + +///| Plain-English rendering of a `interface { ... }` block (as returned by extract_block). +fn humanise_interface(name : String, block : Array[String]) -> Array[String] { + let out : Array[String] = [] + let mut i = 0 + let head_docs : Array[String] = [] + while i < block.length() && trim(block[i]).has_prefix("///") { + head_docs.push(doc_text(block[i])) + i = i + 1 + } + out.push("# " + dashes(name) + " (interface)") + if head_docs.length() > 0 { + out.push(doc_prose(head_docs).trim(chars=" ").to_string()) + } + i = i + 1 // header line + let mut pending : Array[String] = [] + let mut calls_shown = false + let kinds = ["record", "enum", "variant", "flags", "resource"] + while i < block.length() { + let l = trim(block[i]) + i = i + 1 + if l.has_prefix("///") { + pending.push(doc_text(l)) + continue + } + if l == "" || l == "}" { + continue + } + if l.has_prefix("use ") { + pending = [] + continue + } + let kw = first_word(l) + if kinds.contains(kw) { + let nm = dashes(first_word(trim(l[kw.length():].to_string()))) + let entries : Array[(Array[String], String)] = [] + let lb = index_of(l, '{') + let rb = last_index_of(l, '}') + if lb >= 0 && rb > lb { + for e in split_top(l[lb + 1:rb].to_string(), ',') { + entries.push(([], e)) + } + } else { + let mut ed : Array[String] = [] + while i < block.length() { + let el = trim(block[i]) + i = i + 1 + if el.has_prefix("}") { + break + } + if el.has_prefix("///") { + ed.push(doc_text(el)) + } else if el != "" { + let clean = if el.has_suffix(",") || el.has_suffix(";") { + el[:el.length() - 1].to_string() + } else { + el + } + entries.push((ed, clean)) + ed = [] + } + } + } + out.push("") + let intro = match kw { + "record" => "A " + bold(nm) + " is a group of fields. " + "enum" => "A " + bold(nm) + " is exactly one of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". " + "variant" => "A " + bold(nm) + " is one of several cases, some carrying data. " + "flags" => "A " + bold(nm) + " is any combination of " + and_list(entries.map(fn(e) { bold(dashes(e.1)) })) + ". " + _ => "A " + bold(nm) + " is a handle owned by the host. " + } + let sb = StringBuilder::new() + sb.write_string(intro + doc_prose(pending)) + if kw == "record" || kw == "variant" { + let parts = entries.map(fn(e) { entry_sentence(kw, e.1, e.0) }) + sb.write_string(parts.join(" ")) + } + out.push(sb.to_string().trim(chars=" ").to_string()) + } else if kw == "type" && l.contains("=") { + let eq = index_of(l, '=') + let nm = dashes(first_word(trim(l[kw.length():].to_string()))) + let tgt = trim(l[eq + 1:].to_string()) + let tgt = if tgt.has_suffix(";") { tgt[:tgt.length() - 1].to_string() } else { tgt } + out.push("") + out.push(bold(nm) + " is just another name for " + ty(tgt) + ". " + doc_prose(pending).trim(chars=" ").to_string()) + } else if l.contains(": func(") { + if !calls_shown { + out.push("") + out.push("What it can do:") + calls_shown = true + out.push("") + } + let clean = if l.has_suffix(";") { l[:l.length() - 1].to_string() } else { l } + out.push(entry_sentence("func", clean, pending)) + } + pending = [] + } + out +} + +///| "moonplasma:desktop/theme@0.1.0;" -> "theme" (raw WIT identifier, dashes kept) +fn ref_name(s : String) -> String { + let mut r = trim(s) + if r.has_suffix(";") { + r = r[:r.length() - 1].to_string() + } + let sl = last_index_of(r, '/') + if sl >= 0 { + r = r[sl + 1:].to_string() + } + let at = index_of(r, '@') + if at >= 0 { + r = r[:at].to_string() + } + r +} + +///| "moonplasma:desktop/app-catalog@0.1.0" -> "app catalog" +fn short_ref(s : String) -> String { + dashes(ref_name(s)) +} + +///| Interfaces a world uses, resolved through `include`: exports first, then imports. +fn world_interfaces(text : String, name : String) -> Array[String] { + let imports : Array[String] = [] + let exports : Array[String] = [] + collect_world_raw(text, name, imports, exports, 0) + let out : Array[String] = [] + for e in exports { + if !out.contains(e) { + out.push(e) + } + } + for i in imports { + if !out.contains(i) { + out.push(i) + } + } + out +} + +///| +fn collect_world_raw( + text : String, + name : String, + imports : Array[String], + exports : Array[String], + depth : Int, +) -> Unit { + if depth > 3 { + return + } + for l in extract_block(text, "world", name) { + let t = trim(l) + if t.has_prefix("import ") { + imports.push(ref_name(t[7:].to_string())) + } else if t.has_prefix("export ") { + exports.push(ref_name(t[7:].to_string())) + } else if t.has_prefix("include ") { + collect_world_raw(text, ref_name(t[8:].to_string()), imports, exports, depth + 1) + } + } +} + +///| +fn collect_world( + text : String, + name : String, + imports : Array[String], + exports : Array[String], + depth : Int, +) -> Unit { + if depth > 3 { + return + } + for l in extract_block(text, "world", name) { + let t = trim(l) + if t.has_prefix("import ") { + imports.push(short_ref(t[7:].to_string())) + } else if t.has_prefix("export ") { + exports.push(short_ref(t[7:].to_string())) + } else if t.has_prefix("include ") { + collect_world(text, trim(short_ref(t[8:].to_string())).replace_all(old=" ", new="-"), imports, exports, depth + 1) + } + } +} + +///| Plain-English rendering of a world: what it provides and what it needs. +fn humanise_world(text : String, name : String) -> Array[String] { + let out : Array[String] = [] + let block = extract_block(text, "world", name) + let docs : Array[String] = [] + for l in block { + if trim(l).has_prefix("///") { + docs.push(doc_text(l)) + } else { + break + } + } + out.push("# " + dashes(name) + " (component)") + if docs.length() > 0 { + out.push(doc_prose(docs).trim(chars=" ").to_string()) + } + let imports : Array[String] = [] + let exports : Array[String] = [] + collect_world(text, name, imports, exports, 0) + out.push("") + out.push("It provides " + and_list(exports.map(bold)) + ", and needs " + and_list(imports.map(bold)) + " from the host.") + out +} diff --git a/compositor/shell/inspector.mbt b/compositor/shell/inspector.mbt new file mode 100644 index 0000000..1bd130b --- /dev/null +++ b/compositor/shell/inspector.mbt @@ -0,0 +1,396 @@ +///| Interface Explorer: a shell tool. Toggle it from the panel's "Interface Explorer" button, then +/// hover any system component (launcher, clock, panel, window title bar, ...) +/// to see the WIT interface that component implements in a dialog. +/// WIT text is read from the repo's `wit/` directory at runtime, so the dialog +/// always shows what is on disk. + +///| A system component the inspector knows about. +priv struct Component { + id : String + title : String + note : String + /// (file, world name) + world : (String, String)? + /// (file, interface name) pairs, in display order. + ifaces : Array[(String, String)] +} + +///| +let components : Array[Component] = [ + { + id: "panel", + title: "Panel", + note: "containment: places widgets and draws the panel frame", + world: Some(("wit/worlds.wit", "panel")), + ifaces: [], + }, + { + id: "desktop", + title: "Desktop surface", + note: "wallpaper / desktop containment", + world: Some(("wit/worlds.wit", "shell")), + ifaces: [], + }, + { + id: "window-decoration", + title: "Window decoration", + note: "server-side title bar and buttons", + world: Some(("wit/wm/worlds.wit", "decoration-provider")), + ifaces: [], + }, + { + id: "window-surface", + title: "Client surface", + note: "a client's committed buffer, composited by the host", + world: None, + ifaces: [("wit/compositor/surface.wit", "surface")], + }, +] + +///| The component behind `id`: a loaded panel module (described from its real binary: +/// the plasmoid contract it exports and the capability interfaces it imports) or one +/// of the fixed shell parts (panel, desktop, window decoration, client surface). +fn DesktopShell::find_component(self : DesktopShell, id : String) -> Component? { + match self.widget_by_slot(id) { + Some(w) => { + let ifaces : Array[(String, String)] = [("", "plasmoid")] + for c in w.caps { + ifaces.push(("", c)) + } + Some({ + id, + title: w.pl.name, + note: "wasm module " + w.module_id + ", imports: " + (if w.caps.length() == 0 { "nothing" } else { w.caps.join(", ") }), + world: None, + ifaces, + }) + } + None => { + for c in components { + if c.id == id { + return Some(c) + } + } + None + } + } +} + +///| Read a file under the repo's wit/ directory (cached); "" when missing. +fn DesktopShell::wit_file(self : DesktopShell, path : String) -> String { + match self.wit_cache.get(path) { + Some(t) => t + None => { + let bytes = @sys.read_file_bytes(path) + let text = if bytes.length() == 0 { + "" + } else { + @utf8.decode_lossy(bytes) + } + self.wit_cache.set(path, text) + text + } + } +} + +///| The `kind name { ... }` block (with its leading /// docs), one line per entry. +fn extract_block(text : String, kind : String, name : String) -> Array[String] { + let lines : Array[String] = [] + for l in text.split("\n") { + lines.push(l.to_string()) + } + let head = kind + " " + name + " {" + let out : Array[String] = [] + let mut start = -1 + for i = 0; i < lines.length(); i = i + 1 { + if lines[i].has_prefix(head) { + start = i + break + } + } + if start < 0 { + return out + } + // leading doc comments + let mut s = start + while s > 0 && lines[s - 1].has_prefix("///") { + s = s - 1 + } + for i = s; i < lines.length(); i = i + 1 { + out.push(lines[i]) + if i >= start && (lines[i] == "}" || (i == start && lines[i].has_suffix("}"))) { + break + } + } + out +} + +///| WIT files searched for interface/world definitions. +let wit_sources : Array[String] = [ + "wit/worlds.wit", "wit/plasmoid.wit", "wit/capabilities.wit", "wit/shell.wit", + "wit/theme.wit", "wit/types.wit", "wit/wm/worlds.wit", "wit/wm/policy.wit", + "wit/wm/decoration.wit", "wit/compositor/surface.wit", +] + +///| Interface block `name` from whichever WIT file defines it. +fn DesktopShell::find_interface(self : DesktopShell, name : String) -> Array[String] { + for f in wit_sources { + let b = extract_block(self.wit_file(f), "interface", name) + if b.length() > 0 { + return b + } + } + [] +} + +///| All dialog lines for a component (blank line between blocks). +fn DesktopShell::inspector_lines(self : DesktopShell, c : Component) -> Array[String] { + let out : Array[String] = [] + match c.world { + Some((file, name)) => { + for l in humanise_world(self.wit_file(file), name) { + out.push(l) + } + out.push("") + } + None => () + } + // Interfaces come from the world (exports + imports) unless listed explicitly. + let names : Array[String] = [] + match c.world { + Some((file, wname)) if c.ifaces.length() == 0 => + for n in world_interfaces(self.wit_file(file), wname) { + names.push(n) + } + _ => for fi in c.ifaces { names.push(fi.1) } + } + for name in names { + let b = self.find_interface(name) + if b.length() == 0 { + out.push("(interface " + name + " not found - run from the repo root)") + } else { + for l in humanise_interface(name, b) { + out.push(l) + } + } + out.push("") + } + if names.length() == 0 && c.world is None { + out.push("(no WIT: not a component)") + } + // drop trailing blank + while out.length() > 0 && out[out.length() - 1] == "" { + ignore(out.pop()) + } + out +} + +///| Word length at the start of `s` (letters, digits, '-'). +fn first_word(s : String) -> String { + let mut n = 0 + while n < s.length() { + let ch = s[n] + let ok = (ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' + if !ok { + break + } + n = n + 1 + } + s[:n].to_string() +} + +///| Draw the dialog for the hovered component into `ops`. +fn DesktopShell::render_inspector( + self : DesktopShell, + w : Int, + h : Int, + tokens : @theme.Tokens, + ops : Array[@scene.DrawOp], +) -> Unit { + match self.find_component(self.hover_id) { + None => () + Some(c) => { + let p = tokens.palette + let line_h = 18 + let body_sz = 12 + let header_h = 22 + 16 + 10 + let text_w = 400 + let dw = text_w + 28 + // Word-wrap each paragraph to `text_w` using real glyph widths. A row is + // a list of (word, bold) runs; `**term**` in the prose marks bold terms. + let rows_all : Array[(Int, Array[(String, Bool, Bool)])] = [] // (kind: 0 body, 1 heading, 2 blank) + for para in self.inspector_lines(c) { + if para == "" { + rows_all.push((2, [])) + } else if para.has_prefix("# ") { + rows_all.push((1, [(para[2:].to_string(), true, false)])) + } else { + // (word, bold, glued to the previous word: no space between) + let words : Array[(String, Bool, Bool)] = [] + let mut is_bold = false + let mut prev_space = true + for seg in para.split("**") { + let sg = seg.to_string() + let mut first_word = true + for wd in sg.split(" ") { + let wd = wd.to_string() + if wd.length() > 0 { + words.push((wd, is_bold, first_word && !sg.has_prefix(" ") && !prev_space)) + } + first_word = false + } + if sg.length() > 0 { + prev_space = sg.has_suffix(" ") + } + is_bold = !is_bold + } + let space = @renderer.text_width(" ", body_sz, false, false) + let mut cur : Array[(String, Bool, Bool)] = [] + let mut cw = 0 + for wv in words { + let ww = @renderer.text_width(wv.0, body_sz, wv.1, false) + if cur.length() > 0 && !wv.2 && cw + space + ww > text_w { + rows_all.push((0, cur)) + cur = [] + cw = 0 + } + cw = cw + (if cur.length() > 0 && !wv.2 { space } else { 0 }) + ww + cur.push(wv) + } + if cur.length() > 0 { + rows_all.push((0, cur)) + } + } + } + // Compact dialog: at most ~14 visible rows (or what fits the screen), + // the rest scrolls with the mouse wheel. + let fit = (h - 16 - header_h - 12) / line_h + let max_rows = if fit < 14 { fit } else { 14 } + let max_rows = if max_rows < 1 { 1 } else { max_rows } + let rows = if rows_all.length() < max_rows { rows_all.length() } else { max_rows } + let max_scroll = rows_all.length() - rows + if self.inspect_scroll > max_scroll { + self.inspect_scroll = max_scroll + } + if self.inspect_scroll < 0 { + self.inspect_scroll = 0 + } + let first = self.inspect_scroll + let dh = header_h + rows * line_h + 12 + let mut dx = self.hover_x + 18 + let mut dy = self.hover_y + 18 + if dx + dw > w { + dx = w - dw - 4 + } + if dx < 4 { + dx = 4 + } + if dy + dh > h { + dy = self.hover_y - dh - 12 + } + if dy < 4 { + dy = 4 + } + let local : Array[@types.DrawOp] = [] + let r = tokens.radius.reinterpret_as_int() + local.push(@ui.fill_rect(@ui.rect(0, 0, dw, dh), p.surface_popup, radius=r + 4)) + local.push(@ui.stroke_rect(@ui.rect(0, 0, dw, dh), p.accent, radius=r + 4)) + local.push(@ui.text(14, 16, c.title, 14, p.foreground, bold=true)) + local.push(@ui.text(14, 34, c.note, 11, p.foreground_muted)) + local.push(@ui.fill_rect(@ui.rect(10, 46, dw - 20, 1), p.border)) + let mut y = 58 + line_h / 2 + let space = @renderer.text_width(" ", body_sz, false, false) + for i = first; i < rows_all.length() && i < first + rows; i = i + 1 { + let (kind, runs) = rows_all[i] + if kind == 1 { + local.push(@ui.text(14, y, runs[0].0, 13, p.accent, bold=true)) + } else if kind == 0 { + let mut x = 14 + for run in runs { + let (wd, b, glued) = run + if glued { + x = x - space + } + local.push(@ui.text(x, y, wd, body_sz, if b { p.accent } else { p.foreground }, bold=b)) + x = x + @renderer.text_width(wd, body_sz, b, false) + space + } + } + y = y + line_h + } + if max_scroll > 0 { + // Scrollbar track + thumb on the right edge, plus a hint. + let th = rows * line_h + let thumb = if th * rows / rows_all.length() < 12 { 12 } else { th * rows / rows_all.length() } + let ty = 52 + (th - thumb) * first / max_scroll + local.push(@ui.fill_rect(@ui.rect(dw - 8, 52, 3, th), p.border)) + local.push(@ui.fill_rect(@ui.rect(dw - 8, ty, 3, thumb), p.accent)) + local.push(@ui.text(dw - 24 - 90, 34, "scroll for more", 11, p.foreground_muted)) + } + let scene_ops : Array[@scene.DrawOp] = [] + translate(local, dx, dy, scene_ops) + for op in scene_ops { + ops.push(op) + } + } + } +} + +///| True while inspect mode is on. +pub fn DesktopShell::inspecting(self : DesktopShell) -> Bool { + self.inspect_on +} + +///| Turn inspect mode on/off. The launcher popup is left as it is. +pub fn DesktopShell::set_inspecting(self : DesktopShell, on : Bool) -> Unit { + self.inspect_on = on + self.hover_id = "" +} + +///| Shell component under (x, y): a panel widget id, "panel" for bare panel, +/// "" for anything else (windows or the desktop - the compositor resolves those). +pub fn DesktopShell::component_at(self : DesktopShell, x : Int, y : Int) -> String { + for entry in self.comps { + let (id, r) = entry + if inside(r, x, y) { + return id + } + } + if inside(self.panel_rect, x, y) { + "panel" + } else { + "" + } +} + +///| Record what the pointer is over while inspecting. +pub fn DesktopShell::set_hover(self : DesktopShell, id : String, x : Int, y : Int) -> Unit { + if id != self.hover_id { + self.inspect_scroll = 0 + } + self.hover_id = id + self.hover_x = x + self.hover_y = y +} + +///| Dialog lines for component `id` (for tests and tooling). +pub fn DesktopShell::inspector_lines_for(self : DesktopShell, id : String) -> Array[String] { + match self.find_component(id) { + Some(c) => self.inspector_lines(c) + None => [] + } +} + +///| Mouse-wheel scroll of the explorer dialog (lines, + = down). True if consumed. +pub fn DesktopShell::scroll_inspector(self : DesktopShell, lines : Int) -> Bool { + if !self.inspect_on || self.hover_id == "" { + return false + } + self.inspect_scroll = self.inspect_scroll + lines + if self.inspect_scroll < 0 { + self.inspect_scroll = 0 + } + true +} diff --git a/compositor/shell/moon.pkg b/compositor/shell/moon.pkg index 448d2b9..c93000b 100644 --- a/compositor/shell/moon.pkg +++ b/compositor/shell/moon.pkg @@ -1,14 +1,27 @@ import { "moonbitlang/core/builtin", + "moonbitlang/core/encoding/utf8" @utf8, "moonplasma/desktop/interface/moonplasma/desktop/types" @types, "moonplasma/desktop/interface/moonplasma/desktop/theme" @theme, "moonplasma/desktop/lib/ui" @ui, "moonplasma/desktop/lib/shell" @libshell, "moonplasma/desktop/lib/panel" @panel, "moonplasma/desktop/lib/clock" @clock, + "moonplasma/desktop/lib/moon" @moon, + "moonplasma/desktop/lib/timefmt" @timefmt, "moonplasma/desktop/lib/launcher" @launcher, "moonplasma/desktop/compositor/scene" @scene, "moonplasma/desktop/compositor/sys" @sys, + "moonplasma/desktop/compositor/renderer" @renderer, + "moonplasma/desktop/compositor/wasm" @wasm, } supported_targets = "-all+native" + +options( + link: { + "native": { + "cc-link-flags": "-lwasmer", + }, + }, +) diff --git a/compositor/shell/shell.mbt b/compositor/shell/shell.mbt index a6cd8ab..885e5ab 100644 --- a/compositor/shell/shell.mbt +++ b/compositor/shell/shell.mbt @@ -125,59 +125,279 @@ fn now() -> @types.Datetime { } } -///| The desktop shell: wallpaper + bottom panel with launcher, task list and clock. +///| A window as the panel's task list sees it (handed to modules through the `windows` capability). +pub(all) struct WinInfo { + id : UInt64 + title : String + focused : Bool + minimized : Bool +} + +///| Something a panel module asked the compositor to do. +pub(all) enum ShellAction { + SetLayout(Int) + FocusWindow(UInt64) +} derive(Eq, Debug) + +///| One wasm module loaded into the panel. +pub(all) struct Widget { + /// Panel slot id ("w1", "w2", ...): one per loaded instance. + slot : String + /// The module's file stem ("clock-digital"), or its path for modules loaded from elsewhere. + module_id : String + path : String + pl : @wasm.Plasmoid + /// Host interfaces the module imports (its capabilities). + caps : Array[String] + mut rect : @scene.Rect + /// Where its popup is on screen (w == 0 while closed), and what to draw there. + mut popup_rect : @scene.Rect + mut popup_ops : Array[@types.DrawOp] + mut popup_hot : Bool +} + +///| A wasm module file found on the module path. +pub(all) struct CatalogEntry { + id : String + path : String + /// Filled in (by loading the module once) the first time names are needed; "" until then. + mut name : String +} + +///| One row of the right-click menu: kind 0 replace with module `arg` (a path), 1 remove, 2 open the module manager. +pub(all) struct MenuRow { + label : String + kind : Int + arg : String +} + +///| The desktop shell: wallpaper + a bottom panel made entirely of wasm modules +/// (application menu, Interface Explorer, layout switcher, task list, moon, clock ...). +/// Nothing on the panel is built in: every element is a plasmoid component loaded +/// from a `.wasm` file and can be unloaded or replaced while the compositor runs. pub(all) struct DesktopShell { - launcher_state : @launcher.State apps : Array[@types.AppEntry] exec : Map[String, String] /// Wayland socket handed to launched apps as WAYLAND_DISPLAY. display : String + /// Panel modules in panel order; a module with `stretch` splits the panel into a left and a right group. + widgets : Array[Widget] + mut next_slot : Int + /// Module files on the search path (see `module_dirs`). + catalog : Array[CatalogEntry] + mut catalog_named : Bool + mut booted : Bool + /// Read and write panel.edn (the compositor binary turns this on; tests leave it off). + mut persist : Bool + mut tokens : @theme.Tokens mut screen_w : Int - mut launcher_rect : @scene.Rect - mut popup_rect : @scene.Rect + mut screen_h : Int + mut panel_h : Int + /// Window list + layout mode, set by the compositor before each frame. + mut windows : Array[WinInfo] + mut layout_sel : Int + mut layout_names : Array[String] + /// Things modules asked for (focus a window, switch layout), drained by the compositor. + actions : Array[ShellAction] + mut apps_dirty : Bool + /// The native file chooser opened by the module manager's "Browse" row, and a transient notice. + mut picker : @wasm.Picker? + /// Machine-state provider behind the `system` interface, and the window list behind `windows`. + sampler : SysSampler + mut win_list : Array[@wasm.WindowEntry] + mut notice : String + mut notice_frames : Int + mut notice_start : Int + /// Right-click menu. + mut menu_open : Bool + mut menu_rect : @scene.Rect + mut menu_title : String + mut menu_rows : Array[MenuRow] + mut menu_hover : Int + mut menu_anchor_x : Int + mut menu_slot : String + /// Panel widget being dragged (slot id, "" if none), press point, and whether it moved past the click threshold. + mut drag_slot : String + mut drag_x0 : Int + mut drag_y0 : Int + mut drag_active : Bool + // WIT inspector state (see inspector.mbt) + mut inspect_on : Bool + mut hover_id : String + mut hover_x : Int + mut inspect_scroll : Int + mut hover_y : Int + mut panel_rect : @scene.Rect + comps : Array[(String, @scene.Rect)] + wit_cache : Map[String, String] + /// Most-recently-launched app ids, newest first (persisted). + recents : Array[String] } -///| Apps the launcher offers, kept only if their executable exists. -/// (id, name, comment, category, glyph, executable) -let candidates : Array[(String, String, String, String, String, String)] = [ - ("org.moonplasma.terminal", "Terminal", "Command-line shell", "System", ">_", "foot"), - ("org.moonplasma.konsole", "Konsole", "KDE terminal", "System", ">_", "konsole"), - ("org.moonplasma.files", "Files", "Browse folders and files", "Utilities", "F", "dolphin"), - ("org.moonplasma.browser", "Web Browser", "Browse the web", "Internet", "W", "firefox"), - ("org.moonplasma.editor", "Text Editor", "Edit plain text files", "Utilities", "T", "kate"), - ("org.moonplasma.settings", "System Settings", "Configure the desktop", "System", "S", "systemsettings"), -] - ///| pub fn DesktopShell::new(display : String) -> DesktopShell { let apps : Array[@types.AppEntry] = [] let exec : Map[String, String] = {} - for c in candidates { - let (id, name, comment, category, glyph, bin) = c - if @sys.has_exe(bin) { - apps.push({ id, name, comment, category, glyph }) - exec.set(id, bin) + for a in scan_desktop_apps() { + let glyph = match a.name.to_array().get(0) { + Some(c) => c.to_string().to_upper() + None => "?" } + apps.push({ id: a.id, name: a.name, comment: a.comment, category: a.category, glyph }) + exec.set(a.id, a.command) } - { - launcher_state: @launcher.State::new(), + let zero : @scene.Rect = { x: 0, y: 0, w: 0, h: 0 } + let sh : DesktopShell = { apps, exec, display, + widgets: [], + next_slot: 1, + catalog: [], + catalog_named: false, + booted: false, + persist: false, + tokens: conv_theme(@scene.ThemeTokens::moon_night()), screen_w: 0, - launcher_rect: { x: 0, y: 0, w: 0, h: 0 }, - popup_rect: { x: 0, y: 0, w: 0, h: 0 }, + screen_h: 0, + panel_h: 40, + windows: [], + layout_sel: 0, + layout_names: ["Tiling (BSP)", "Monocle", "Floating"], + actions: [], + apps_dirty: true, + sampler: SysSampler::new(), + win_list: [], + picker: None, + notice: "", + notice_frames: 0, + notice_start: 0, + menu_open: false, + menu_rect: zero, + menu_title: "", + menu_rows: [], + menu_hover: -1, + menu_anchor_x: 0, + menu_slot: "", + drag_slot: "", + drag_x0: 0, + drag_y0: 0, + drag_active: false, + inspect_on: false, + hover_id: "", + hover_x: 0, + inspect_scroll: 0, + hover_y: 0, + panel_rect: zero, + comps: [], + wit_cache: {}, + recents: load_recents(), + } + sh.order_apps() + sh +} + +///| Tell the shell the theme and output size it will first be drawn with (modules are loaded +/// against these); the panel itself is loaded on first use. +pub fn DesktopShell::set_output(self : DesktopShell, theme : @scene.ThemeTokens, w : Int, h : Int) -> Unit { + self.tokens = conv_theme(theme) + self.screen_w = w + self.screen_h = h + self.panel_h = theme.panel_height +} + +///| Default launcher entries, in order: each group is matched against app ids (first hit wins). +let default_groups : Array[Array[String]] = [ + ["foot", "konsole", "terminal", "kitty", "alacritty"], + ["dolphin", "nautilus", "thunar", "files"], + ["firefox", "chromium", "chrome", "browser"], + ["kate", "gedit", "texteditor", "code", "editor"], + ["systemsettings", "settings", "control"], +] + +///| +let max_recents : Int = 8 + +///| +fn recents_path() -> String { + let c = @sys.getenv("XDG_CACHE_HOME") + (if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.cache" }) + + "/moon-plasma-recent" +} + +///| +fn load_recents() -> Array[String] { + let out : Array[String] = [] + let text = @utf8.decode_lossy(@sys.read_file_bytes(recents_path())) + for l in text.split("\n") { + let id = l.trim(chars=" \r").to_string() + if id.length() > 0 { + out.push(id) + } + } + out +} + +///| Reorder the launcher: defaults first, then recents (newest first), then the rest A-Z. +fn DesktopShell::order_apps(self : DesktopShell) -> Unit { + let by_id : Map[String, @types.AppEntry] = {} + for a in self.apps { + by_id.set(a.id, a) + } + let out : Array[@types.AppEntry] = [] + let seen : Map[String, Bool] = {} + fn take(a : @types.AppEntry, out : Array[@types.AppEntry], seen : Map[String, Bool]) -> Unit { + if !seen.contains(a.id) { + seen.set(a.id, true) + out.push(a) + } + } + for g in default_groups { + let mut found = false + for key in g { + if !found { + for a in self.apps { + if !found && a.id.to_lower().contains(key) { + take(a, out, seen) + found = true + } + } + } + } + } + for id in self.recents { + match by_id.get(id) { + Some(a) => take(a, out, seen) + None => () + } + } + for a in self.apps { + take(a, out, seen) // already A-Z from the scan + } + self.apps.clear() + for a in out { + self.apps.push(a) } } -///| Truncate `s` with ".." so it fits `width` px (the renderer's small text is 6 px per char). -fn fit_title(s : String, width : Int) -> String { - let max_chars = width / 6 - if s.length() <= max_chars { - s - } else { - s[:max_chars - 2].to_string() + ".." +///| Remember `id` as the most recent launch and persist the list. +fn DesktopShell::note_recent(self : DesktopShell, id : String) -> Unit { + let next : Array[String] = [id] + for r in self.recents { + if r != id && next.length() < max_recents { + next.push(r) + } } + self.recents.clear() + for r in next { + self.recents.push(r) + } + let sb = StringBuilder::new() + for r in self.recents { + sb.write_string(r + "\n") + } + ignore(@sys.write_file_bytes(recents_path(), @utf8.encode(sb.to_string()))) + self.order_apps() } ///| @@ -185,43 +405,122 @@ fn inside(r : @scene.Rect, x : Int, y : Int) -> Bool { r.w > 0 && x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h } -///| True while the launcher popup is open (it then owns keyboard input). +///| The launcher module (the Super key opens it). +let launcher_module : String = "launcher" + +///| True while any panel popup or the right-click menu is open (it then owns keyboard input). pub fn DesktopShell::popup_open(self : DesktopShell) -> Bool { - self.launcher_state.open + self.menu_open || self.open_popup_widget() is Some(_) } -///| True if (x, y) is over the launcher button or its open popup. -pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool { - inside(self.launcher_rect, x, y) || - (self.launcher_state.open && inside(self.popup_rect, x, y)) +///| The widget whose popup is open, if any. +fn DesktopShell::open_popup_widget(self : DesktopShell) -> Widget? { + for w in self.widgets { + if w.popup_rect.w > 0 { + return Some(w) + } + } + None } ///| -fn DesktopShell::launch(self : DesktopShell, id : String) -> Result[Unit, String] { - match self.exec.get(id) { - None => Err("no executable for " + id) - Some(bin) => - if @sys.spawn(bin, self.display) { - Ok(()) - } else { - Err("could not start " + bin) - } +fn DesktopShell::widget_at(self : DesktopShell, x : Int, y : Int) -> Widget? { + for w in self.widgets { + if inside(w.rect, x, y) { + return Some(w) + } + } + None +} + +///| +fn DesktopShell::widget_by_slot(self : DesktopShell, slot : String) -> Widget? { + for w in self.widgets { + if w.slot == slot { + return Some(w) + } + } + None +} + +///| Widget whose popup contains (x, y). +fn DesktopShell::popup_at(self : DesktopShell, x : Int, y : Int) -> Widget? { + for w in self.widgets { + if inside(w.popup_rect, x, y) { + return Some(w) + } + } + None +} + +///| Does the widget import host interface `cap`? +fn Widget::has_cap(self : Widget, cap : String) -> Bool { + self.caps.contains(cap) +} + +///| Hand an event to a module, then carry out whatever it asked of the host. +fn DesktopShell::deliver(self : DesktopShell, w : Widget, popup : Bool, ev : @wasm.PlasmoidEvent) -> Bool { + self.publish_host_data() + let changed = w.pl.on_event(popup, ev) + self.process_requests() + // The module may have unloaded itself (or been replaced) while handling the event. + if self.widget_by_slot(w.slot) is Some(_) { + self.refresh_popup(w) + } + changed +} + +///| Close every popup except `keep`'s (a press elsewhere dismisses them). +fn DesktopShell::dismiss_popups(self : DesktopShell, keep : String) -> Unit { + for w in self.widgets.copy() { + if w.slot != keep && w.popup_rect.w > 0 { + ignore(self.deliver(w, false, FocusLost)) + } } } -///| wp_cursor_shape_v1 value for the shell UI under (x, y): 4 pointer (hand) over the -/// launcher button and popup entries, 9 text over the search field, else 0 (not shell-specific). -pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt { - if inside(self.launcher_rect, x, y) { - 4U - } else if self.launcher_state.open && inside(self.popup_rect, x, y) { - if self.launcher_state.hover >= 0 { - 4U - } else if y - self.popup_rect.y < 52 { - 9U - } else { - 1U +///| Open the launcher module's popup, or close it if already open (the Super-key tap). +pub fn DesktopShell::toggle_launcher(self : DesktopShell) -> Unit { + self.ensure_booted() + self.menu_open = false + for w in self.widgets { + if w.module_id == launcher_module { + if w.popup_rect.w > 0 { + ignore(self.deliver(w, false, FocusLost)) + } else { + self.dismiss_popups(w.slot) + ignore(self.deliver(w, false, PointerDown(0, 0))) + } + return } + } +} + +///| True if (x, y) is over the panel, an open popup or the menu (so windows don't see it). +pub fn DesktopShell::hit(self : DesktopShell, x : Int, y : Int) -> Bool { + inside(self.panel_rect, x, y) || + (self.menu_open && inside(self.menu_rect, x, y)) || + self.popup_at(x, y) is Some(_) +} + +///| wp_cursor_shape_v1 value for the shell UI under (x, y): hand over panel modules, grabbing +/// while one is dragged, 0 when (x, y) is not shell UI. +pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt { + if self.inspect_on { + // help cursor everywhere while inspecting; hand over the Interface Explorer toggle itself + return match self.widget_at(x, y) { + Some(w) if w.has_cap("inspector") => 4U + _ => 3U + } + } + if self.drag_active { + 17U // grabbing + } else if self.menu_open && inside(self.menu_rect, x, y) { + if self.menu_hover >= 0 { 4U } else { 1U } + } else if self.popup_at(x, y) is Some(_) { + 1U + } else if self.widget_at(x, y) is Some(_) { + 4U } else { 0U } @@ -229,47 +528,139 @@ pub fn DesktopShell::cursor_at(self : DesktopShell, x : Int, y : Int) -> UInt { ///| Pointer press at (x, y). Returns true when the shell consumed it. pub fn DesktopShell::pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool { - let launch = fn(id : String) { self.launch(id) } - if inside(self.launcher_rect, x, y) { - ignore( - @launcher.handle_event(self.apps, self.launcher_state, Widget, PointerDown({ x: x - self.launcher_rect.x, y: y - self.launcher_rect.y }), launch), - ) - true - } else if self.launcher_state.open { - if inside(self.popup_rect, x, y) { - ignore( - @launcher.handle_event(self.apps, self.launcher_state, Popup, PointerDown({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch), - ) - true - } else { - // Click outside: dismiss, and let the click through. - ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, FocusLost, launch)) - false - } - } else { - false + self.ensure_booted() + if self.menu_open { + // A press outside the menu dismisses it and goes through. + return self.menu_pointer_down(x, y) } -} - -///| Pointer motion; returns true when over the popup (so windows don't see it). -pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool { - if self.launcher_state.open { - let launch = fn(id : String) { self.launch(id) } - if inside(self.popup_rect, x, y) { - ignore( - @launcher.handle_event(self.apps, self.launcher_state, Popup, PointerMove({ x: x - self.popup_rect.x, y: y - self.popup_rect.y }), launch), - ) + if self.inspect_on { + // Inspecting: clicks reach only modules that hold the `inspector` capability (the toggle). + match self.widget_at(x, y) { + Some(w) if w.has_cap("inspector") => + ignore(self.deliver(w, false, PointerDown(x - w.rect.x, y - w.rect.y))) + _ => () + } + return true + } + match self.popup_at(x, y) { + Some(w) => { + ignore(self.deliver(w, true, PointerDown(x - w.popup_rect.x, y - w.popup_rect.y))) return true } - ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, PointerLeave, launch)) + None => () + } + match self.widget_at(x, y) { + Some(w) => { + // A click (delivered on release) or the start of a drag that reorders the panel. + // The Interface Explorer toggle leaves open popups alone. + if !w.has_cap("inspector") { + self.dismiss_popups(w.slot) + } + self.drag_slot = w.slot + self.drag_x0 = x + self.drag_y0 = y + self.drag_active = false + true + } + None => { + // Click elsewhere: dismiss any popup and let the click through. + self.dismiss_popups("") + inside(self.panel_rect, x, y) + } } - false } -///| Key name as used by lib/launcher ("Escape", "Backspace", "Enter" or one character). +///| Move the dragged widget in panel order to where the pointer is: it lands after every +/// other widget whose centre is left of `x`. +fn DesktopShell::reorder_dragged(self : DesktopShell, x : Int) -> Unit { + match self.widget_by_slot(self.drag_slot) { + None => () + Some(dragged) => { + let others = self.widgets.filter(w => w.slot != self.drag_slot) + let mut idx = 0 + for w in others { + if w.rect.x + w.rect.w / 2 < x { + idx = idx + 1 + } + } + others.insert(idx, dragged) + self.widgets.clear() + for w in others { + self.widgets.push(w) + } + } + } +} + +///| Pointer release: ends a widget drag, or clicks the widget if it never moved. True when a press was pending. +pub fn DesktopShell::pointer_up(self : DesktopShell) -> Bool { + let slot = self.drag_slot + let was_drag = self.drag_active + self.drag_slot = "" + self.drag_active = false + if slot == "" { + return false + } + if was_drag { + self.save_panel_config() + } else { + match self.widget_by_slot(slot) { + Some(w) => ignore(self.deliver(w, false, PointerDown(self.drag_x0 - w.rect.x, self.drag_y0 - w.rect.y))) + None => () + } + } + true +} + +///| Pointer motion; returns true when over a popup or the menu (so windows don't see it). +pub fn DesktopShell::pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool { + if self.drag_slot != "" { + if !self.drag_active && (x - self.drag_x0 > 4 || self.drag_x0 - x > 4) { + self.drag_active = true + } + if self.drag_active { + self.reorder_dragged(x) + } + return true + } + if self.menu_open { + return self.menu_pointer_move(x, y) + } + let mut over = false + for w in self.widgets.copy() { + if w.popup_rect.w > 0 { + if inside(w.popup_rect, x, y) { + w.popup_hot = true + over = true + ignore(self.deliver(w, true, PointerMove(x - w.popup_rect.x, y - w.popup_rect.y))) + } else if w.popup_hot { + w.popup_hot = false + ignore(self.deliver(w, true, PointerLeave)) + } + } + } + over +} + +///| Key name as used by the plasmoid contract ("Escape", "Backspace", "Enter" or one character). pub fn DesktopShell::key_down(self : DesktopShell, name : String) -> Unit { - let launch = fn(id : String) { self.launch(id) } - ignore(@launcher.handle_event(self.apps, self.launcher_state, Popup, KeyDown(name), launch)) + if self.menu_open { + if name == "Escape" { + self.menu_open = false + } + return + } + match self.open_popup_widget() { + Some(w) => ignore(self.deliver(w, true, KeyDown(name))) + None => () + } +} + +///| Things panel modules asked the compositor to do since the last call (focus a window, switch layout). +pub fn DesktopShell::take_actions(self : DesktopShell) -> Array[ShellAction] { + let out = self.actions.copy() + self.actions.clear() + out } ///| Build the (background, panel) render-lists for the current frame. @@ -278,72 +669,73 @@ pub fn DesktopShell::render( w : Int, h : Int, theme : @scene.ThemeTokens, - layout_label : String, - window_titles : Array[String], ) -> (Array[@scene.DrawOp], Array[@scene.DrawOp]) { let tokens = conv_theme(theme) + self.tokens = tokens self.screen_w = w + self.screen_h = h + self.panel_h = theme.panel_height + self.ensure_booted() + self.poll_picker() + self.publish_host_data() + // Machine state and the rich window list only matter to modules that import them. + if self.widgets.iter().any(w => w.has_cap("system") || w.has_cap("windows")) { + self.sampler.refresh() + @wasm.set_windows(self.win_list) + } let bg : Array[@scene.DrawOp] = [] translate(@libshell.render_background(@ui.size(w, h), tokens), 0, 0, bg) + render_desktop_widget(w, tokens, now(), bg) - let (_, _, clock_w, clock_h, clock_min) = @clock.digital_info() - let slots : Array[@panel.SlotIn] = [ - { id: "launcher", pref_w: 190, pref_h: 36, min_w: 170, stretch: false, end_align: false }, - { id: "layout", pref_w: 96, pref_h: 36, min_w: 80, stretch: false, end_align: false }, - { id: "tasks", pref_w: 100, pref_h: 36, min_w: 0, stretch: true, end_align: false }, - { id: "clock", pref_w: clock_w, pref_h: clock_h, min_w: clock_min, stretch: false, end_align: true }, - ] let panel_ops : Array[@scene.DrawOp] = [] - match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), slots) { + self.comps.clear() + self.panel_rect = { x: 0, y: 0, w: 0, h: 0 } + match @panel.layout(w, h, theme.panel_height, 4, tokens.spacing.reinterpret_as_int(), self.panel_slots()) { Err(_) => () Ok(pl) => { - let pr = @ui.rect(pl.x, pl.y, pl.w, pl.h) - translate(@libshell.render_panel(pr, tokens), 0, 0, panel_ops) - for p in pl.placements { - let size = @ui.size(p.w, p.h) - let local : Array[@types.DrawOp] = match p.id { - "launcher" => @launcher.render_button(size, tokens, self.launcher_state) - "clock" => @clock.render_digital(size, tokens, now(), hour12=true) - "layout" => [ - @ui.fill_rect(@ui.rect(0, 0, p.w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()), - @ui.text(p.w / 2, p.h / 2, layout_label, tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground, align=CENTER), - ] - _ => [] - } - translate(local, p.x, p.y, panel_ops) - if p.id == "launcher" { - self.launcher_rect = { x: p.x, y: p.y, w: p.w, h: p.h } - } - if p.id == "tasks" { - let mut tx = 0 - for title in window_titles { - let pill_w = 140 - if tx + pill_w <= p.w { - translate( - [ - @ui.fill_rect(@ui.rect(tx, 0, pill_w, p.h), tokens.palette.surface_hover, radius=tokens.radius.reinterpret_as_int()), - @ui.text(tx + 10, p.h / 2, fit_title(title, pill_w - 20), tokens.font_size.reinterpret_as_int() - 2, tokens.palette.foreground), - ], - p.x, - p.y, - panel_ops, - ) - tx = tx + pill_w + 6 - } - } - } + self.panel_rect = { x: pl.x, y: pl.y, w: pl.w, h: pl.h } + translate(@libshell.render_panel(@ui.rect(pl.x, pl.y, pl.w, pl.h), tokens), 0, 0, panel_ops) + for i = 0; i < pl.placements.length() && i < self.widgets.length(); i = i + 1 { + let p = pl.placements[i] + let wd = self.widgets[i] + translate(wd.pl.render(p.w, p.h, tokens), p.x, p.y, panel_ops) + wd.rect = { x: p.x, y: p.y, w: p.w, h: p.h } + self.comps.push((wd.slot, wd.rect)) } } } - if self.launcher_state.open { - let size = @launcher.popup_size(self.apps, self.launcher_state) - let pw = size.w.reinterpret_as_int() - let ph = size.h.reinterpret_as_int() - let (px, py) = @panel.popup_position(w, h - theme.panel_height, self.launcher_rect.x, pw, ph, 6) - self.popup_rect = { x: px, y: py, w: pw, h: ph } - translate(@launcher.render_popup(self.apps, tokens, self.launcher_state), px, py, panel_ops) + // Popups sit above the panel, left-aligned with their widget. + for wd in self.widgets { + self.refresh_popup(wd) + if wd.popup_rect.w > 0 { + translate(wd.popup_ops, wd.popup_rect.x, wd.popup_rect.y, panel_ops) + } + } + if self.menu_open { + self.render_menu(w, tokens, panel_ops) } else { - self.popup_rect = { x: 0, y: 0, w: 0, h: 0 } + self.menu_rect = { x: 0, y: 0, w: 0, h: 0 } + } + if self.notice_frames > 0 { + if (wall_secs() - self.notice_start + 86400) % 86400 >= 4 { + self.notice_frames = 0 + } + } + if self.notice_frames > 0 { + let nw = self.notice.length() * 7 + 24 + translate( + [ + @ui.fill_rect(@ui.rect(0, 0, nw, 28), tokens.palette.surface_popup, radius=tokens.radius.reinterpret_as_int()), + @ui.stroke_rect(@ui.rect(0, 0, nw, 28), tokens.palette.border, radius=tokens.radius.reinterpret_as_int()), + @ui.text(12, 14, self.notice, tokens.font_size.reinterpret_as_int() - 3, tokens.palette.foreground), + ], + w - nw - 12, + self.panel_rect.y - 40, + panel_ops, + ) + } + if self.inspect_on { + self.render_inspector(w, h, tokens, panel_ops) } (bg, panel_ops) } diff --git a/compositor/shell/sysinfo.mbt b/compositor/shell/sysinfo.mbt new file mode 100644 index 0000000..b125998 --- /dev/null +++ b/compositor/shell/sysinfo.mbt @@ -0,0 +1,199 @@ +///| Linux provider for the `system` interface: samples /proc and /sys about once a second +/// and hands widgets a `SystemSnapshot`. Widgets never see these paths; swapping this file +/// for another provider (a VM, a remote host, a mock) changes nothing for them. + +///| +pub(all) struct SysSampler { + mut last_secs : Int + mut prev_busy : Int64 + mut prev_total : Int64 + mut prev_rx : Int64 + mut prev_tx : Int64 + mut primed : Bool + mut cur : @wasm.SystemSnapshot +} + +///| +fn SysSampler::new() -> SysSampler { + { + last_secs: -1, + prev_busy: 0L, + prev_total: 0L, + prev_rx: 0L, + prev_tx: 0L, + primed: false, + cur: { + cpu_permille: 0, + mem_used_kib: 0L, + mem_total_kib: 0L, + battery_percent: -1, + charging: false, + uptime_secs: 0L, + rx_bps: 0L, + tx_bps: 0L, + load_centi: 0, + }, + } +} + +///| +fn proc_text(path : String) -> String { + @utf8.decode_lossy(@sys.read_proc_bytes(path)) +} + +///| Leading unsigned integer of `s` (0 if none). +fn parse_i64(s : String) -> Int64 { + let mut v = 0L + for ch in s { + let c = ch.to_int() + if c >= 48 && c <= 57 { + v = v * 10L + (c - 48).to_int64() + } else { + break + } + } + v +} + +///| Whitespace-separated fields. +fn fields(s : String) -> Array[String] { + let out : Array[String] = [] + let mut cur = "" + for ch in s { + if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' { + if cur.length() > 0 { + out.push(cur) + cur = "" + } + } else { + cur = cur + ch.to_string() + } + } + if cur.length() > 0 { + out.push(cur) + } + out +} + +///| "0.52" -> 52 (hundredths). +fn parse_centi(s : String) -> Int { + let parts = s.split(".").collect() + let whole = parse_i64(parts[0].to_string()).to_int() + let frac = if parts.length() > 1 { + let f = parts[1].to_string() + let two = if f.length() >= 2 { f[:2].to_string() } else { f + "0" } + parse_i64(two).to_int() + } else { + 0 + } + whole * 100 + frac +} + +///| (busy, total) jiffies from the aggregate "cpu" line of /proc/stat. +fn cpu_times() -> (Int64, Int64) { + let text = proc_text("/proc/stat") + for line in text.split("\n") { + let f = fields(line.to_string()) + if f.length() > 5 && f[0] == "cpu" { + let mut total = 0L + for i = 1; i < f.length() && i <= 8; i = i + 1 { + total = total + parse_i64(f[i]) + } + let idle = parse_i64(f[4]) + parse_i64(f[5]) + return (total - idle, total) + } + } + (0L, 0L) +} + +///| (rx, tx) bytes summed over every interface but loopback. +fn net_bytes() -> (Int64, Int64) { + let mut rx = 0L + let mut tx = 0L + for line in proc_text("/proc/net/dev").split("\n") { + let l = line.to_string() + match l.find(":") { + None => () + Some(i) => { + let name = l[:i].to_string().trim(chars=" ").to_string() + if name != "lo" { + let f = fields(l[i + 1:].to_string()) + if f.length() > 8 { + rx = rx + parse_i64(f[0]) + tx = tx + parse_i64(f[8]) + } + } + } + } + } + (rx, tx) +} + +///| (total, available) KiB from /proc/meminfo. +fn mem_kib() -> (Int64, Int64) { + let mut total = 0L + let mut avail = 0L + for line in proc_text("/proc/meminfo").split("\n") { + let f = fields(line.to_string()) + if f.length() >= 2 { + if f[0] == "MemTotal:" { + total = parse_i64(f[1]) + } else if f[0] == "MemAvailable:" { + avail = parse_i64(f[1]) + } + } + } + (total, avail) +} + +///| (percent, plugged-in) for the first battery, or (-1, true) without one. +fn battery() -> (Int, Bool) { + for name in ["BAT0", "BAT1", "BATT"] { + let base = "/sys/class/power_supply/" + name + let cap = proc_text(base + "/capacity") + if cap.length() > 0 { + let status = proc_text(base + "/status").trim(chars=" \n").to_string() + return (parse_i64(cap).to_int(), status != "Discharging") + } + } + (-1, true) +} + +///| Re-sample if a wall-clock second passed since the last call; cheap otherwise. +fn SysSampler::refresh(self : SysSampler) -> Unit { + let now = wall_secs() + if now == self.last_secs { + return + } + let dt = if self.last_secs < 0 { + 1 + } else { + let d = now - self.last_secs + if d <= 0 { d + 86400 } else { d } + } + self.last_secs = now + let (busy, total) = cpu_times() + let (rx, tx) = net_bytes() + let (mt, ma) = mem_kib() + let (pct, plugged) = battery() + let dtotal = total - self.prev_total + let cpu = if self.primed && dtotal > 0L { ((busy - self.prev_busy) * 1000L / dtotal).to_int() } else { 0 } + let load = parse_centi(fields(proc_text("/proc/loadavg")).get(0).unwrap_or("0")) + self.cur = { + cpu_permille: if cpu < 0 { 0 } else if cpu > 1000 { 1000 } else { cpu }, + mem_used_kib: mt - ma, + mem_total_kib: mt, + battery_percent: pct, + charging: plugged, + uptime_secs: parse_i64(fields(proc_text("/proc/uptime")).get(0).unwrap_or("0")), + rx_bps: if self.primed && rx >= self.prev_rx { (rx - self.prev_rx) / dt.to_int64() } else { 0L }, + tx_bps: if self.primed && tx >= self.prev_tx { (tx - self.prev_tx) / dt.to_int64() } else { 0L }, + load_centi: load, + } + self.prev_busy = busy + self.prev_total = total + self.prev_rx = rx + self.prev_tx = tx + self.primed = true + @wasm.set_system(self.cur) +} diff --git a/compositor/shell/widgets.mbt b/compositor/shell/widgets.mbt new file mode 100644 index 0000000..cc32c50 --- /dev/null +++ b/compositor/shell/widgets.mbt @@ -0,0 +1,724 @@ +///| The panel's modules: finding them on disk, loading, unloading and replacing them +/// while the compositor runs, the capabilities (host data + requests) they use, the +/// right-click menu, and the saved panel layout. +/// +/// A module is a wasm plasmoid component (`moonplasma:desktop/plasmoid`). Its imports +/// are the capabilities it was granted: `theme` and `clock` always, `app-catalog` / +/// `app-launch` for the application menu, `windows` for the task list, `layout-control` +/// for the layout switcher, `inspector` for the Interface Explorer button and `modules` +/// for the module manager. The manager is itself just a module: the wasm picker +/// ("Module manager..." in the panel menu) loads it on demand and opens it. + +///| Modules loaded into a fresh panel, in order. `tasks` stretches, so what follows it packs right. +let default_panel : Array[String] = [ + "launcher", "inspector", "layout", "tasks", "moon-disc", "clock-digital12", +] + +///| The module whose popup is the wasm picker. +let manager_module : String = "module-manager" + +///| Directories searched for `*.wasm` modules, highest priority first. +fn module_dirs() -> Array[String] { + let dirs : Array[String] = [] + let env = @sys.getenv("MOON_PLASMA_MODULES") + if env.length() > 0 { + for d in env.split(":") { + if d.length() > 0 { + dirs.push(d.to_string()) + } + } + } + let data_home = { + let x = @sys.getenv("XDG_DATA_HOME") + if x.length() > 0 { x } else { @sys.getenv("HOME") + "/.local/share" } + } + dirs.push(data_home + "/moon-plasma/modules") + dirs.push("/usr/local/share/moon-plasma/modules") + dirs.push("/usr/share/moon-plasma/modules") + dirs.push("modules") // the login session runs from /usr/local/share/moon-plasma + // In a source checkout (and from a package directory when running its tests). + dirs.push("build/components") + dirs.push("../build/components") + dirs.push("../../build/components") + dirs +} + +///| "/a/b/clock.wasm" -> "clock" +fn stem(path : String) -> String { + let mut start = 0 + for i = 0; i < path.length(); i = i + 1 { + if path[i] == '/' { + start = i + 1 + } + } + let name = path[start:].to_string() + if name.has_suffix(".wasm") { + name[:name.length() - 5].to_string() + } else { + name + } +} + +///| Find every module file on the search path (earlier directories win on the same name). +fn DesktopShell::scan_catalog(self : DesktopShell) -> Unit { + self.catalog.clear() + self.catalog_named = false + let seen : Map[String, Bool] = {} + for dir in module_dirs() { + for f in @wasm.list_wasm_files(dir) { + let id = stem(f) + if !seen.contains(id) { + seen.set(id, true) + self.catalog.push({ id, path: dir + "/" + f, name: "" }) + } + } + } +} + +///| Learn each module's display name by loading it once; files that are not plasmoids +/// (the shell, window-manager and gfx components live in the same directory) drop out. +fn DesktopShell::name_catalog(self : DesktopShell) -> Unit { + if self.catalog_named { + return + } + self.catalog_named = true + let keep : Array[CatalogEntry] = [] + for e in self.catalog { + match @wasm.load(e.path, self.tokens) { + Ok(pl) => { + e.name = pl.name + pl.unload() + keep.push(e) + } + Err(_) => () + } + } + self.catalog.clear() + for e in keep { + self.catalog.push(e) + } +} + +///| Catalog entry for module id `id`. +fn DesktopShell::find_module(self : DesktopShell, id : String) -> CatalogEntry? { + for e in self.catalog { + if e.id == id { + return Some(e) + } + } + None +} + +///| Panel slot descriptions for every loaded module, in panel order. A stretching module +/// (the task list) splits the panel: modules after it pack against the right edge. +fn DesktopShell::panel_slots(self : DesktopShell) -> Array[@panel.SlotIn] { + let mut first_stretch = -1 + for i = 0; i < self.widgets.length(); i = i + 1 { + if first_stretch < 0 && self.widgets[i].pl.stretch { + first_stretch = i + } + } + let out : Array[@panel.SlotIn] = [] + for i = 0; i < self.widgets.length(); i = i + 1 { + let w = self.widgets[i] + out.push({ + id: w.slot, + pref_w: w.pl.pref_w, + pref_h: w.pl.pref_h, + min_w: w.pl.min_w, + stretch: w.pl.stretch, + end_align: first_stretch >= 0 && i > first_stretch, + }) + } + out +} + +///| Would the panel still fit on screen with the current modules? +fn DesktopShell::panel_fits(self : DesktopShell) -> Bool { + match @panel.layout(self.screen_w, 100000, 40, 4, 6, self.panel_slots()) { + Ok(_) => true + Err(_) => false + } +} + +///| Show a short message above the panel for a few seconds. +fn DesktopShell::say(self : DesktopShell, msg : String) -> Unit { + self.notice = msg + self.notice_frames = 1 + self.notice_start = wall_secs() +} + +///| Seconds since local midnight (wall clock). +fn wall_secs() -> Int { + @sys.wall_time_field(3) * 3600 + @sys.wall_time_field(4) * 60 + @sys.wall_time_field(5) +} + +///| Load the panel on first use: the saved layout if there is one, else the default modules. +fn DesktopShell::ensure_booted(self : DesktopShell) -> Unit { + if self.booted { + return + } + self.booted = true + self.scan_catalog() + let entries = match self.load_panel_config() { + Some(e) => e + None => default_panel + } + for e in entries { + let path = if e.has_prefix("/") { + e + } else { + match self.find_module(e) { + Some(c) => c.path + None => { + self.say("Module '" + e + "' not found (build it with scripts/build-modules.sh)") + "" + } + } + } + if path != "" { + ignore(self.load_path(path)) + } + } +} + +///| Load the module file at `path` into the panel (any number of instances may be loaded). +/// None, with a notice, when it is not a plasmoid or the panel has no room for it. +pub fn DesktopShell::load_path(self : DesktopShell, path : String) -> Widget? { + match @wasm.load(path, self.tokens) { + Err(e) => { + self.say("Can't load module: " + e) + None + } + Ok(pl) => { + let id = stem(path) + let known = match self.find_module(id) { + Some(c) => c.path == path + None => false + } + let w : Widget = { + slot: "w" + self.next_slot.to_string(), + module_id: if known { id } else { path }, + path, + pl, + caps: pl.imports(), + rect: { x: 0, y: 0, w: 0, h: 0 }, + popup_rect: { x: 0, y: 0, w: 0, h: 0 }, + popup_ops: [], + popup_hot: false, + } + self.next_slot = self.next_slot + 1 + self.widgets.push(w) + if self.screen_w > 0 && !self.panel_fits() { + self.widgets.retain(x => x.slot != w.slot) + pl.unload() + self.say("No room in the panel for " + pl.name) + None + } else { + Some(w) + } + } + } +} + +///| Load module `id` (a file stem from the catalog, or a path) and persist the panel. +pub fn DesktopShell::load_module(self : DesktopShell, id : String) -> Bool { + self.ensure_booted() + let path = match self.find_module(id) { + Some(c) => c.path + None => id + } + match self.load_path(path) { + Some(w) => { + self.say("Loaded " + w.pl.name) + self.save_panel_config() + true + } + None => false + } +} + +///| Unload the module in `slot`, freeing its panel space. False if there is none. +pub fn DesktopShell::unload_slot(self : DesktopShell, slot : String) -> Bool { + match self.widget_by_slot(slot) { + None => false + Some(w) => { + self.widgets.retain(x => x.slot != slot) + w.pl.unload() + if self.drag_slot == slot { + self.drag_slot = "" + self.drag_active = false + } + self.save_panel_config() + true + } + } +} + +///| Replace the module in `slot` with the module file at `path`, keeping its place in the panel. +pub fn DesktopShell::replace_slot(self : DesktopShell, slot : String, path : String) -> Bool { + let mut idx = -1 + for i = 0; i < self.widgets.length(); i = i + 1 { + if self.widgets[i].slot == slot { + idx = i + } + } + if idx < 0 { + return false + } + let old = self.widgets[idx] + self.widgets.remove(idx) |> ignore + match self.load_path(path) { + None => { + self.widgets.insert(idx, old) + false + } + Some(nw) => { + // load_path appended it; move it into the old module's place, then drop the old one. + self.widgets.retain(x => x.slot != nw.slot) + self.widgets.insert(idx, nw) + old.pl.unload() + self.save_panel_config() + true + } + } +} + +///| Unload every module (the compositor is closing). +pub fn DesktopShell::shutdown(self : DesktopShell) -> Unit { + for w in self.widgets { + w.pl.unload() + } + self.widgets.clear() +} + +///| Slot ids of the loaded modules, in panel order. +pub fn DesktopShell::slots(self : DesktopShell) -> Array[String] { + self.ensure_booted() + self.widgets.map(w => w.slot) +} + +///| Module id of the module in `slot` ("" if none). +pub fn DesktopShell::slot_module(self : DesktopShell, slot : String) -> String { + match self.widget_by_slot(slot) { + Some(w) => w.module_id + None => "" + } +} + +///| Slot of the first loaded instance of module `id` ("" if none). +pub fn DesktopShell::slot_of(self : DesktopShell, id : String) -> String { + self.ensure_booted() + for w in self.widgets { + if w.module_id == id { + return w.slot + } + } + "" +} + +///| Panel rectangle of the module in `slot` as last drawn. +pub fn DesktopShell::slot_rect(self : DesktopShell, slot : String) -> @scene.Rect { + match self.widget_by_slot(slot) { + Some(w) => w.rect + None => { x: 0, y: 0, w: 0, h: 0 } + } +} + +///| Rectangle of the module's open popup (w == 0 when closed). +pub fn DesktopShell::slot_popup_rect(self : DesktopShell, slot : String) -> @scene.Rect { + match self.widget_by_slot(slot) { + Some(w) => w.popup_rect + None => { x: 0, y: 0, w: 0, h: 0 } + } +} + +///| Publish what modules can read through their capabilities (apps, windows, layout, loaded modules). +fn DesktopShell::publish_host_data(self : DesktopShell) -> Unit { + if self.apps_dirty { + self.apps_dirty = false + let t = @wasm.Table::new() + for a in self.apps { + t.str(a.id) + t.str(a.name) + t.str(a.comment) + t.str(a.category) + t.str(a.glyph) + t.end_row() + } + @wasm.publish(Apps, t) + } + let wt = @wasm.Table::new() + for win in self.windows { + wt.int(win.id.to_int()) + wt.str(win.title) + wt.int(if win.focused { 1 } else { 0 }) + wt.int(if win.minimized { 1 } else { 0 }) + wt.end_row() + } + @wasm.publish(Windows, wt) + let lt = @wasm.Table::new() + for n in self.layout_names { + lt.str(n) + lt.end_row() + } + @wasm.publish(Layouts, lt) + @wasm.publish_state(self.layout_sel, self.inspect_on) + let it = @wasm.Table::new() + for w in self.widgets { + it.str(w.slot) + it.str(w.module_id) + it.str(w.pl.name) + it.end_row() + } + @wasm.publish(Instances, it) + let mut wants_modules = false + for w in self.widgets { + if w.has_cap("modules") { + wants_modules = true + } + } + if wants_modules { + self.name_catalog() + let mt = @wasm.Table::new() + for e in self.catalog { + let mut n = 0 + for w in self.widgets { + if w.path == e.path { + n = n + 1 + } + } + mt.str(e.id) + mt.str(e.name) + mt.str(e.path) + mt.int(n) + mt.end_row() + } + @wasm.publish(Modules, mt) + } +} + +///| Carry out what modules asked of the host during their last calls. +fn DesktopShell::process_requests(self : DesktopShell) -> Unit { + while true { + match @wasm.next_request() { + None => break + Some(Launch(id)) => { + match self.exec.get(id) { + Some(bin) => + if @sys.spawn(bin, self.display) { + self.note_recent(id) + self.apps_dirty = true + } else { + self.say("Could not start " + bin) + } + None => self.say("No executable for " + id) + } + } + Some(FocusWindow(n)) => self.actions.push(FocusWindow(n.to_int64().to_uint64())) + Some(SetLayout(m)) => self.actions.push(SetLayout(m)) + Some(SetInspector(on)) => self.set_inspecting(on) + Some(LoadModule(path)) => { + match self.load_path(path) { + Some(w) => { + self.say("Loaded " + w.pl.name) + self.save_panel_config() + } + None => () + } + } + Some(UnloadInstance(slot)) => ignore(self.unload_slot(slot)) + Some(Browse) => + if self.picker is None { + self.picker = @wasm.Picker::start() + if self.picker is None { + self.say("No file chooser available (install zenity)") + } + } + } + } + // A module that imports `windows.focus` (the 64-bit-id form) asks through its own slot. + match @wasm.take_focus_request() { + Some(id) => self.actions.push(FocusWindow(id)) + None => () + } +} + +///| Re-read the module's popup (size and drawing) and place it above the panel. +fn DesktopShell::refresh_popup(self : DesktopShell, w : Widget) -> Unit { + if self.widget_by_slot(w.slot) is None { + return + } + match w.pl.popup() { + None => { + w.popup_rect = { x: 0, y: 0, w: 0, h: 0 } + w.popup_ops = [] + w.popup_hot = false + } + Some(ps) => { + let (px, py) = @panel.popup_position(self.screen_w, self.screen_h - self.panel_h, w.rect.x, ps.w, ps.h, 6) + w.popup_rect = { x: px, y: py, w: ps.w, h: ps.h } + w.popup_ops = ps.ops + } + } +} + +///| Check the open file dialog; load the chosen .wasm into the panel. +fn DesktopShell::poll_picker(self : DesktopShell) -> Unit { + match self.picker { + None => () + Some(pk) => + match pk.poll() { + None => () + Some(None) => self.picker = None + Some(Some(path)) => { + self.picker = None + match self.load_path(path) { + Some(w) => { + self.say("Loaded " + w.pl.name) + self.save_panel_config() + } + None => () + } + } + } + } +} + +///| The wasm picker: open the module manager app to choose what to load, loading the +/// manager itself first if it is not in the panel. +pub fn DesktopShell::open_module_manager(self : DesktopShell) -> Bool { + self.ensure_booted() + let mut mgr : Widget? = None + for w in self.widgets { + if mgr is None && w.module_id == manager_module { + mgr = Some(w) + } + } + if mgr is None { + match self.find_module(manager_module) { + None => { + self.say("Module manager not found (build it with scripts/build-modules.sh)") + return false + } + Some(c) => mgr = self.load_path(c.path) + } + } + match mgr { + None => false + Some(w) => { + self.dismiss_popups(w.slot) + if w.popup_rect.w == 0 { + ignore(self.deliver(w, false, PointerDown(0, 0))) + } + self.save_panel_config() + true + } + } +} + +// ---------------------------------------------------------------- right-click menu + +///| Title row height and item row height of the menu. +let menu_title_h : Int = 26 + +///| +let menu_item_h : Int = 28 + +///| +let menu_w : Int = 250 + +///| Most "Replace with" rows listed. +let max_replace_rows : Int = 8 + +///| Right-click: on a module its replace/remove menu, on empty panel space the picker entry. +/// True when consumed. +pub fn DesktopShell::right_click(self : DesktopShell, x : Int, y : Int) -> Bool { + self.ensure_booted() + if self.inspect_on { + return false + } + let was_open = self.menu_open + self.menu_open = false + self.dismiss_popups("") + match self.widget_at(x, y) { + Some(w) => { + self.name_catalog() + let rows : Array[MenuRow] = [] + for e in self.catalog { + if e.id != w.module_id && e.path != w.path && rows.length() < max_replace_rows { + rows.push({ label: "Replace with " + e.name, kind: 0, arg: e.path }) + } + } + rows.push({ label: "Remove widget", kind: 1, arg: "" }) + rows.push({ label: "Module manager...", kind: 2, arg: "" }) + self.open_menu(w.pl.name, rows, w.slot, x) + true + } + None => + if inside(self.panel_rect, x, y) { + self.open_menu("Add widget", [{ label: "Module manager...", kind: 2, arg: "" }], "", x) + true + } else { + was_open + } + } +} + +///| +fn DesktopShell::open_menu(self : DesktopShell, title : String, rows : Array[MenuRow], slot : String, x : Int) -> Unit { + self.menu_open = true + self.menu_title = title + self.menu_rows = rows + self.menu_slot = slot + self.menu_hover = -1 + self.menu_anchor_x = x +} + +///| +fn DesktopShell::menu_item_at(self : DesktopShell, x : Int, y : Int) -> Int { + if !self.menu_open || !inside(self.menu_rect, x, y) { + return -1 + } + let i = (y - self.menu_rect.y - menu_title_h) / menu_item_h + if y - self.menu_rect.y >= menu_title_h && i >= 0 && i < self.menu_rows.length() { + i + } else { + -1 + } +} + +///| Left press while the menu is open: choose a row or dismiss. True when consumed. +fn DesktopShell::menu_pointer_down(self : DesktopShell, x : Int, y : Int) -> Bool { + let i = self.menu_item_at(x, y) + let over = inside(self.menu_rect, x, y) + self.menu_open = false + if i >= 0 { + let row = self.menu_rows[i] + let slot = self.menu_slot + match row.kind { + 0 => ignore(self.replace_slot(slot, row.arg)) + 1 => ignore(self.unload_slot(slot)) + _ => ignore(self.open_module_manager()) + } + } + over +} + +///| +fn DesktopShell::menu_pointer_move(self : DesktopShell, x : Int, y : Int) -> Bool { + self.menu_hover = self.menu_item_at(x, y) + inside(self.menu_rect, x, y) +} + +///| +fn DesktopShell::render_menu( + self : DesktopShell, + w : Int, + tokens : @theme.Tokens, + out : Array[@scene.DrawOp], +) -> Unit { + let n = self.menu_rows.length() + let mh = menu_title_h + n * menu_item_h + 6 + let mx = clamp_menu(self.menu_anchor_x - menu_w / 2, 4, w - menu_w - 4) + let my = self.panel_rect.y - mh - 6 + self.menu_rect = { x: mx, y: my, w: menu_w, h: mh } + let fs = tokens.font_size.reinterpret_as_int() + let r = tokens.radius.reinterpret_as_int() + let ops : Array[@types.DrawOp] = [ + @ui.fill_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.surface_popup, radius=r), + @ui.stroke_rect(@ui.rect(0, 0, menu_w, mh), tokens.palette.border, radius=r), + @ui.text(12, menu_title_h / 2 + 2, self.menu_title, fs - 3, tokens.palette.foreground_muted), + ] + for i = 0; i < n; i = i + 1 { + let top = menu_title_h + i * menu_item_h + let hot = i == self.menu_hover + if hot { + ops.push(@ui.fill_rect(@ui.rect(4, top, menu_w - 8, menu_item_h - 2), tokens.palette.surface_hover, radius=r)) + } + ops.push(@ui.text(14, top + menu_item_h / 2, self.menu_rows[i].label, fs - 2, tokens.palette.foreground)) + } + translate(ops, mx, my, out) +} + +///| +fn clamp_menu(v : Int, lo : Int, hi : Int) -> Int { + if v > hi { hi } else if v < lo { lo } else { v } +} + +// ---------------------------------------------------------------- saved panel + +///| Panel config lives in $XDG_CONFIG_HOME/moon-plasma/panel.edn (default ~/.config). +fn panel_config_dir() -> String { + let c = @sys.getenv("XDG_CONFIG_HOME") + (if c.length() > 0 { c } else { @sys.getenv("HOME") + "/.config" }) + + "/moon-plasma" +} + +///| Write the loaded modules, in panel order, as EDN: +/// {:panel ["launcher" "layout" "tasks" "/home/me/my-widget.wasm"]} +/// (catalog modules by name, others by path). A no-op unless `persist` is on. +pub fn DesktopShell::save_panel_config(self : DesktopShell) -> Unit { + if !self.persist || !self.booted { + return + } + let sb = StringBuilder::new() + sb.write_string(";; Moon Plasma panel: the wasm modules loaded into it, in order\n") + sb.write_string("{:panel [") + let mut first = true + for w in self.widgets { + if !first { + sb.write_string("\n ") + } + first = false + sb.write_string("\"" + w.module_id + "\"") + } + sb.write_string("]}\n") + let dir = panel_config_dir() + if @sys.mkdir_p(dir) { + ignore(@sys.write_file_bytes(dir + "/panel.edn", @utf8.encode(sb.to_string()))) + } +} + +///| The module list saved in panel.edn; None when persistence is off or there is no saved panel. +fn DesktopShell::load_panel_config(self : DesktopShell) -> Array[String]? { + if !self.persist { + return None + } + let text = @utf8.decode_lossy(@sys.read_file_bytes(panel_config_dir() + "/panel.edn")) + let lines : Array[String] = [] + for l in text.split("\n") { + if !l.trim(chars=" \t\r").to_string().has_prefix(";") { + lines.push(l.to_string()) + } + } + let body = lines.join("\n") + match body.find(":panel") { + None => None + Some(i) => { + let rest = body[i:].to_string() + match (rest.find("["), rest.find("]")) { + (Some(a), Some(b)) if b > a => { + let out : Array[String] = [] + for part in rest[a + 1:b].to_string().split("\"") { + // quoted strings are the odd-numbered parts + out.push(part.to_string()) + } + let names : Array[String] = [] + for k = 1; k < out.length(); k = k + 2 { + if out[k].length() > 0 { + names.push(out[k]) + } + } + Some(names) + } + _ => None + } + } + } +} + +///| Theme tokens in the WIT shape the plasmoids expect. +pub fn DesktopShell::tokens_for(_self : DesktopShell, theme : @scene.ThemeTokens) -> @theme.Tokens { + conv_theme(theme) +} diff --git a/compositor/sys/sys.mbt b/compositor/sys/sys.mbt index 541935f..0e25889 100644 --- a/compositor/sys/sys.mbt +++ b/compositor/sys/sys.mbt @@ -194,3 +194,55 @@ pub fn has_exe(name : String) -> Bool { pub fn spawn(cmd : String, display : String) -> Bool { c_spawn(str_to_utf8_bytes(cmd), str_to_utf8_bytes(display)) == 0 } + +///| +extern "C" fn c_list_desktop(dir : Bytes) -> Bytes = "mp_list_desktop" + +///| +extern "C" fn c_getenv(name : Bytes) -> Bytes = "mp_getenv" + +///| Newline-separated names of the `*.desktop` files directly in `dir`. +pub fn list_desktop_files(dir : String) -> Array[String] { + let raw = c_list_desktop(str_to_utf8_bytes(dir)) + let out : Array[String] = [] + let sb = StringBuilder::new() + let mut i = 0 + while i < raw.length() { + if raw[i] == b'\n' { + out.push(sb.to_string()) + sb.reset() + } else { + sb.write_char(Int::unsafe_to_char(raw[i].to_int())) + } + i = i + 1 + } + out +} + +///| Environment variable, or "" when unset. +pub fn getenv(name : String) -> String { + let raw = c_getenv(str_to_utf8_bytes(name)) + let sb = StringBuilder::new() + for i = 0; i < raw.length(); i = i + 1 { + sb.write_char(Int::unsafe_to_char(raw[i].to_int())) + } + sb.to_string() +} + +///| +extern "C" fn c_mkdir_p(path : Bytes) -> Int = "mp_mkdir_p" + +///| Create `path` and any missing parents; true when it exists afterwards. +pub fn mkdir_p(path : String) -> Bool { + c_mkdir_p(str_to_utf8_bytes(path)) == 0 +} + +///| +#borrow(path) +extern "C" fn c_read_proc(path : Bytes) -> Bytes = "mp_read_proc" + +///| Contents of a small /proc or /sys file ("" when unreadable). Unlike `read_file_bytes` +/// this works on files that report size 0. +pub fn read_proc_bytes(path : String) -> Bytes { + c_read_proc(str_to_utf8_bytes(path)) +} diff --git a/compositor/sys/sys_stub.c b/compositor/sys/sys_stub.c index 119ddc8..2be095b 100644 --- a/compositor/sys/sys_stub.c +++ b/compositor/sys/sys_stub.c @@ -12,7 +12,10 @@ #include #include #include +#include +#include #include +#include #include "moonbit.h" @@ -332,22 +335,133 @@ int32_t mp_has_exe(moonbit_bytes_t name_bytes) { return found; } +/* Private session bus for launched apps, so single-instance apps (Firefox, Kate, + * Dolphin...) don't forward the launch to an instance on the host session. + * Started lazily; dies with the compositor. */ +static char private_bus[256]; +static int private_bus_tried = 0; + +static void start_private_bus(void) { + if (private_bus_tried) return; + private_bus_tried = 1; + int fds[2]; + if (pipe(fds) != 0) return; + pid_t pid = fork(); + if (pid < 0) { close(fds[0]); close(fds[1]); return; } + if (pid == 0) { + prctl(PR_SET_PDEATHSIG, SIGTERM); + close(fds[0]); + char arg[64]; + snprintf(arg, sizeof(arg), "--print-address=%d", fds[1]); + execlp("dbus-daemon", "dbus-daemon", "--session", "--nofork", arg, (char *)NULL); + _exit(127); + } + close(fds[1]); + ssize_t n = read(fds[0], private_bus, sizeof(private_bus) - 1); + close(fds[0]); + if (n > 0) { + private_bus[n] = 0; + char *nl = strchr(private_bus, '\n'); + if (nl) *nl = 0; + } else { + private_bus[0] = 0; + } +} + /* Launch `cmd` detached, with WAYLAND_DISPLAY pointing at our socket. Returns 0 on fork success. */ MOONBIT_FFI_EXPORT int32_t mp_spawn(moonbit_bytes_t cmd_bytes, moonbit_bytes_t display_bytes) { - char cmd[256]; + char cmd[2048]; char display[512]; bytes_to_cstr(cmd_bytes, cmd, sizeof(cmd)); bytes_to_cstr(display_bytes, display, sizeof(display)); signal(SIGCHLD, SIG_IGN); /* no zombies */ + start_private_bus(); pid_t pid = fork(); if (pid < 0) return -1; if (pid == 0) { setsid(); + if (private_bus[0]) setenv("DBUS_SESSION_BUS_ADDRESS", private_bus, 1); setenv("WAYLAND_DISPLAY", display, 1); unsetenv("DISPLAY"); - execlp(cmd, cmd, (char *)NULL); + /* Make toolkits pick our Wayland socket, not X11 or the host session. */ + setenv("XDG_SESSION_TYPE", "wayland", 1); + setenv("QT_QPA_PLATFORM", "wayland", 1); + setenv("GDK_BACKEND", "wayland", 1); + setenv("SDL_VIDEODRIVER", "wayland", 1); + setenv("MOZ_ENABLE_WAYLAND", "1", 1); + setenv("ELECTRON_OZONE_PLATFORM_HINT", "wayland", 1); + setenv("CLUTTER_BACKEND", "wayland", 1); + execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); _exit(127); } return 0; } + +/* Names of "*.desktop" files in `dir`, newline-separated. */ +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_list_desktop(moonbit_bytes_t dir_bytes) { + char dir[512]; + bytes_to_cstr(dir_bytes, dir, sizeof(dir)); + DIR *d = opendir(dir); + if (!d) return moonbit_make_bytes_raw(0); + size_t cap = 4096, len = 0; + char *buf = malloc(cap); + struct dirent *e; + while ((e = readdir(d)) != NULL) { + size_t n = strlen(e->d_name); + if (n < 9 || strcmp(e->d_name + n - 8, ".desktop") != 0) continue; + if (len + n + 2 > cap) { cap = (len + n + 2) * 2; buf = realloc(buf, cap); } + memcpy(buf + len, e->d_name, n); + len += n; + buf[len++] = '\n'; + } + closedir(d); + moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len); + memcpy(out, buf, len); + free(buf); + return out; +} + +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_getenv(moonbit_bytes_t name_bytes) { + char name[128]; + bytes_to_cstr(name_bytes, name, sizeof(name)); + const char *v = getenv(name); + if (!v) return moonbit_make_bytes_raw(0); + size_t n = strlen(v); + moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n); + memcpy(out, v, n); + return out; +} + +/* mkdir -p; returns 0 when the directory exists afterwards. */ +MOONBIT_FFI_EXPORT +int32_t mp_mkdir_p(moonbit_bytes_t path_bytes) { + char path[512]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + for (char *p = path + 1; *p; p++) { + if (*p == '/') { + *p = 0; + mkdir(path, 0755); + *p = '/'; + } + } + if (mkdir(path, 0755) != 0 && errno != EEXIST) return -1; + return 0; +} + +/* Read a small /proc or /sys file (they report size 0, so read until EOF; capped at 64 KiB). */ +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_read_proc(moonbit_bytes_t path_bytes) { + char path[512]; + bytes_to_cstr(path_bytes, path, sizeof(path)); + FILE *f = fopen(path, "rb"); + if (!f) return moonbit_make_bytes_raw(0); + static char buf[65536]; + size_t n = fread(buf, 1, sizeof(buf), f); + fclose(f); + moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)n); + memcpy(out, buf, n); + return out; +} diff --git a/compositor/wasm/moon.pkg b/compositor/wasm/moon.pkg new file mode 100644 index 0000000..105b3a2 --- /dev/null +++ b/compositor/wasm/moon.pkg @@ -0,0 +1,16 @@ +import { + "moonbitlang/core/builtin", + "moonplasma/desktop/interface/moonplasma/desktop/types" @types, + "moonplasma/desktop/interface/moonplasma/desktop/theme" @theme, +} + +supported_targets = "-all+native" + +options( + "native-stub": [ "wasm_stub.c" ], + link: { + "native": { + "cc-link-flags": "-lwasmer", + }, + }, +) diff --git a/compositor/wasm/testdata/clock-digital.component.wasm b/compositor/wasm/testdata/clock-digital.component.wasm new file mode 100644 index 0000000..8965b32 Binary files /dev/null and b/compositor/wasm/testdata/clock-digital.component.wasm differ diff --git a/compositor/wasm/testdata/clock-digital.core.wasm b/compositor/wasm/testdata/clock-digital.core.wasm new file mode 100644 index 0000000..43b7686 Binary files /dev/null and b/compositor/wasm/testdata/clock-digital.core.wasm differ diff --git a/compositor/wasm/testdata/pulse.component.wasm b/compositor/wasm/testdata/pulse.component.wasm new file mode 100644 index 0000000..45fe9a8 Binary files /dev/null and b/compositor/wasm/testdata/pulse.component.wasm differ diff --git a/compositor/wasm/wasm.mbt b/compositor/wasm/wasm.mbt new file mode 100644 index 0000000..681080d --- /dev/null +++ b/compositor/wasm/wasm.mbt @@ -0,0 +1,723 @@ +///| Loads plasmoid components (.wasm) into the native compositor. The core module +/// is run with wasmer (see wasm_stub.c); this file does the canonical-ABI marshalling +/// of the `plasmoid` interface: info, render and the draw-op list, UTF-16 strings. + +///| +#borrow(path, tokens) +extern "C" fn c_wasm_load(path : Bytes, tokens : Bytes) -> Int = "mp_wasm_load" + +///| +#borrow(tokens) +extern "C" fn c_wasm_set_tokens(h : Int, tokens : Bytes) = "mp_wasm_set_tokens" + +///| +extern "C" fn c_wasm_unload(h : Int) = "mp_wasm_unload" + +///| +extern "C" fn c_wasm_call(h : Int, which : Int, a0 : Int, a1 : Int, a2 : Int, a3 : Int) -> Int = "mp_wasm_call" + +///| +#borrow(out) +extern "C" fn c_wasm_read(h : Int, off : Int, len : Int, out : Bytes) -> Int = "mp_wasm_read" + +///| +#borrow(b) +extern "C" fn c_wasm_set_system(b : Bytes) = "mp_wasm_set_system" + +///| +#borrow(b) +extern "C" fn c_wasm_set_windows(b : Bytes) = "mp_wasm_set_windows" + +///| +extern "C" fn c_wasm_take_focus() -> Int = "mp_wasm_take_focus" + +///| +#borrow(src) +extern "C" fn c_wasm_write(h : Int, off : Int, src : Bytes, len : Int) -> Int = "mp_wasm_write" + +///| +#borrow(out) +extern "C" fn c_wasm_imports(h : Int, out : Bytes) -> Int = "mp_wasm_imports" + +///| +#borrow(data) +extern "C" fn c_host_set_table(which : Int, data : Bytes) = "mp_host_set_table" + +///| +extern "C" fn c_host_set_int(which : Int, v : Int) = "mp_host_set_int" + +///| +extern "C" fn c_host_req_pop() -> Int = "mp_host_req_pop" + +///| +extern "C" fn c_host_req_int() -> Int = "mp_host_req_int" + +///| +#borrow(out) +extern "C" fn c_host_req_str(out : Bytes) -> Int = "mp_host_req_str" + +///| +#borrow(dir) +extern "C" fn c_list_wasm(dir : Bytes) -> Bytes = "mp_list_wasm" + +///| +extern "C" fn c_pick_start() -> Int = "mp_pick_start" + +///| +#borrow(out) +extern "C" fn c_fd_read(fd : Int, out : Bytes) -> Int = "mp_fd_read" + +///| +extern "C" fn c_fd_close(fd : Int) = "mp_fd_close" + +///| +fn utf8(s : String) -> Bytes { + let out : Array[Byte] = [] + for ch in s { + let c = ch.to_int() + if c < 0x80 { + out.push(c.to_byte()) + } else if c < 0x800 { + out.push((0xC0 | (c >> 6)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } else if c < 0x10000 { + out.push((0xE0 | (c >> 12)).to_byte()) + out.push((0x80 | ((c >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } else { + out.push((0xF0 | (c >> 18)).to_byte()) + out.push((0x80 | ((c >> 12) & 0x3F)).to_byte()) + out.push((0x80 | ((c >> 6) & 0x3F)).to_byte()) + out.push((0x80 | (c & 0x3F)).to_byte()) + } + } + Bytes::from_array(out) +} + +///| Decode UTF-8 bytes (file-picker output). +fn from_utf8(b : Bytes, len : Int) -> String { + let sb = StringBuilder::new() + let mut i = 0 + while i < len { + let c = b[i].to_int() + if c < 0x80 { + sb.write_char(c.unsafe_to_char()) + i = i + 1 + } else if c < 0xE0 && i + 1 < len { + sb.write_char((((c & 0x1F) << 6) | (b[i + 1].to_int() & 0x3F)).unsafe_to_char()) + i = i + 2 + } else if c < 0xF0 && i + 2 < len { + sb.write_char((((c & 0x0F) << 12) | ((b[i + 1].to_int() & 0x3F) << 6) | (b[i + 2].to_int() & 0x3F)).unsafe_to_char()) + i = i + 3 + } else if i + 3 < len { + sb.write_char((((c & 0x07) << 18) | ((b[i + 1].to_int() & 0x3F) << 12) | ((b[i + 2].to_int() & 0x3F) << 6) | (b[i + 3].to_int() & 0x3F)).unsafe_to_char()) + i = i + 4 + } else { + i = len + } + } + sb.to_string() +} + +///| Export indices in wasm_stub.c. +let ex_info : Int = 0 + +///| +let ex_render : Int = 1 + +///| +let ex_onevent : Int = 2 + +///| +let ex_popup : Int = 3 + +///| +let ex_post_info : Int = 4 + +///| +let ex_post_render : Int = 5 + +///| +let ex_post_popup : Int = 6 + +///| +let ex_realloc : Int = 7 + +///| The 64-byte `theme.tokens` record (name left empty) the guest reads through get-tokens. +pub fn pack_tokens(t : @theme.Tokens) -> Bytes { + let b = FixedArray::make(64, b'\x00') + let mut off = 8 + let col = fn(c : @types.Color) { + b[off] = c.r + b[off + 1] = c.g + b[off + 2] = c.b + b[off + 3] = c.a + off = off + 4 + } + let p = t.palette + col(p.desktop_top) + col(p.desktop_bottom) + col(p.surface) + col(p.surface_hover) + col(p.surface_popup) + col(p.foreground) + col(p.foreground_muted) + col(p.accent) + col(p.accent_foreground) + col(p.border) + let put32 = fn(o : Int, v : UInt) { + for k = 0; k < 4; k = k + 1 { + b[o + k] = ((v >> (8 * k)) & 0xFFU).to_int().to_byte() + } + } + put32(48, t.font_size) + put32(52, t.radius) + put32(56, t.spacing) + put32(60, t.panel_height) + Bytes::from_fixedarray(b) +} + +///| A loaded plasmoid instance. +pub(all) struct Plasmoid { + handle : Int + id : String + name : String + pref_w : Int + pref_h : Int + min_w : Int + stretch : Bool + /// The host interfaces this widget imports, i.e. what it was granted (e.g. "system,windows"). + imports : Array[String] +} + +///| +fn Plasmoid::mem(self : Plasmoid, off : Int, len : Int) -> Bytes? { + if len < 0 || off < 0 { + return None + } + let buf = Bytes::make(len, b'\x00') + if len == 0 || c_wasm_read(self.handle, off, len, buf) == 0 { + Some(buf) + } else { + None + } +} + +///| +fn rd32(b : Bytes, o : Int) -> Int { + b[o].to_int() | (b[o + 1].to_int() << 8) | (b[o + 2].to_int() << 16) | (b[o + 3].to_int() << 24) +} + +///| UTF-16LE string of `len` code units at `ptr` in guest memory. +fn Plasmoid::str(self : Plasmoid, ptr : Int, len : Int) -> String { + if len <= 0 || len > 4096 { + return "" + } + match self.mem(ptr, len * 2) { + None => "" + Some(b) => { + let sb = StringBuilder::new() + for i = 0; i < len; i = i + 1 { + sb.write_char((b[2 * i].to_int() | (b[2 * i + 1].to_int() << 8)).unsafe_to_char()) + } + sb.to_string() + } + } +} + +///| Load a plasmoid component or core module. Err carries a short reason. +pub fn load(path : String, tokens : @theme.Tokens) -> Result[Plasmoid, String] { + let h = c_wasm_load(utf8(path), pack_tokens(tokens)) + if h < 0 { + return Err( + match h { + -1 => "not a wasm file" + -2 => "cannot read file" + -3 | -4 => "no plasmoid (moonplasma:desktop/plasmoid) in this module" + _ => "wasm runtime error" + }, + ) + } + let p0 : Plasmoid = { handle: h, id: "", name: "", pref_w: 0, pref_h: 0, min_w: 0, stretch: false, imports: [] } + let ra = c_wasm_call(h, ex_info, 0, 0, 0, 0) + if ra < 0 { + c_wasm_unload(h) + return Err("widget trapped in info()") + } + match p0.mem(ra, 32) { + None => { + c_wasm_unload(h) + Err("bad info() result") + } + Some(b) => { + let p = { + ..p0, + id: p0.str(rd32(b, 0), rd32(b, 4)), + name: p0.str(rd32(b, 8), rd32(b, 12)), + pref_w: rd32(b, 16), + pref_h: rd32(b, 20), + min_w: rd32(b, 24), + stretch: b[28].to_int() != 0, + imports: read_imports(h), + } + ignore(c_wasm_call(h, ex_post_info, ra, 0, 0, 0)) + Ok(p) + } + } +} + +///| Names of the moonplasma interfaces (besides types/theme) the widget at `h` imports. +fn read_imports(h : Int) -> Array[String] { + let buf = Bytes::make(512, b'\x00') + let n = c_wasm_imports(h, buf) + let out : Array[String] = [] + if n > 0 { + for part in from_utf8(buf, n).split("\n") { + if part.length() > 0 && part.to_string() != "theme" { + out.push(part.to_string()) + } + } + } + out +} + +///| Machine state served to widgets through `system.read`. +pub(all) struct SystemSnapshot { + cpu_permille : Int + mem_used_kib : Int64 + mem_total_kib : Int64 + battery_percent : Int + charging : Bool + uptime_secs : Int64 + rx_bps : Int64 + tx_bps : Int64 + load_centi : Int +} + +///| One window served to widgets through `windows.all`. +pub(all) struct WindowEntry { + id : UInt64 + title : String + app_id : String + focused : Bool +} + +///| Publish the machine state widgets will read (canonical-ABI layout of `system.snapshot`). +pub fn set_system(s : SystemSnapshot) -> Unit { + let b = FixedArray::make(64, b'\x00') + let put = fn(o : Int, v : Int64, n : Int) { + for k = 0; k < n; k = k + 1 { + b[o + k] = ((v >> (8 * k)) & 0xFFL).to_int().to_byte() + } + } + put(0, s.cpu_permille.to_int64(), 4) + put(8, s.mem_used_kib, 8) + put(16, s.mem_total_kib, 8) + put(24, s.battery_percent.to_int64(), 4) + put(28, if s.charging { 1L } else { 0L }, 1) + put(32, s.uptime_secs, 8) + put(40, s.rx_bps, 8) + put(48, s.tx_bps, 8) + put(56, s.load_centi.to_int64(), 4) + c_wasm_set_system(Bytes::from_fixedarray(b)) +} + +///| Publish the window list widgets will read. +pub fn set_windows(wins : Array[WindowEntry]) -> Unit { + let out : Array[Byte] = [] + let u32 = fn(v : Int) { + for k = 0; k < 4; k = k + 1 { + out.push(((v >> (8 * k)) & 0xFF).to_byte()) + } + } + let units = fn(str : String) { + u32(str.length()) + for i = 0; i < str.length(); i = i + 1 { + let c = str[i].to_int() + out.push((c & 0xFF).to_byte()) + out.push(((c >> 8) & 0xFF).to_byte()) + } + } + let n = if wins.length() > 64 { 64 } else { wins.length() } + u32(n) + for i = 0; i < n; i = i + 1 { + let w = wins[i] + u32((w.id & 0xFFFFFFFFUL).to_int()) + u32((w.id >> 32).to_int()) + u32(if w.focused { 1 } else { 0 }) + // titles are capped so one huge title cannot crowd out the rest of the list + units(if w.title.length() > 200 { w.title[:200].to_string() } else { w.title }) + units(if w.app_id.length() > 200 { w.app_id[:200].to_string() } else { w.app_id }) + } + c_wasm_set_windows(Bytes::from_array(out)) +} + +///| Window a widget asked to focus (via `windows.focus`) since the last call. +pub fn take_focus_request() -> UInt64? { + let id = c_wasm_take_focus() + if id < 0 { None } else { Some(id.to_uint64()) } +} + +///| Forward a press at widget-local (x, y) to the widget's `on-event`. True when it asked for a redraw. +pub fn Plasmoid::pointer_down(self : Plasmoid, x : Int, y : Int) -> Bool { + c_wasm_call(self.handle, ex_onevent, 0, 1, x, y) == 1 +} + +///| +pub fn Plasmoid::unload(self : Plasmoid) -> Unit { + c_wasm_unload(self.handle) +} + +///| +fn col(b : Bytes, o : Int) -> @types.Color { + { r: b[o], g: b[o + 1], b: b[o + 2], a: b[o + 3] } +} + + +///| Decode `n` draw-ops at guest address `base` (the canonical-ABI list layout). +fn Plasmoid::decode_ops(self : Plasmoid, base : Int, n : Int, out : Array[@types.DrawOp]) -> Unit { + if n >= 0 && n <= 4096 { + match self.mem(base, n * 32) { + None => () + Some(b) => + for i = 0; i < n; i = i + 1 { + let o = i * 32 + let rect = fn(o2 : Int) -> @types.Rect { + { x: rd32(b, o2), y: rd32(b, o2 + 4), w: rd32(b, o2 + 8).reinterpret_as_uint(), h: rd32(b, o2 + 12).reinterpret_as_uint() } + } + match b[o].to_int() { + 0 => + out.push( + FillRect({ rect: rect(o + 4), color: col(b, o + 20), radius: rd32(b, o + 24).reinterpret_as_uint() }), + ) + 1 => + out.push( + StrokeRect({ + rect: rect(o + 4), + color: col(b, o + 20), + width: rd32(b, o + 24).reinterpret_as_uint(), + radius: rd32(b, o + 28).reinterpret_as_uint(), + }), + ) + 2 => + out.push( + Line({ + start: { x: rd32(b, o + 4), y: rd32(b, o + 8) }, + end: { x: rd32(b, o + 12), y: rd32(b, o + 16) }, + color: col(b, o + 20), + width: rd32(b, o + 24).reinterpret_as_uint(), + }), + ) + 3 => + out.push( + Circle({ + center: { x: rd32(b, o + 4), y: rd32(b, o + 8) }, + radius: rd32(b, o + 12).reinterpret_as_uint(), + color: col(b, o + 16), + filled: b[o + 20].to_int() != 0, + }), + ) + 4 => + out.push( + Text({ + origin: { x: rd32(b, o + 4), y: rd32(b, o + 8) }, + text: self.str(rd32(b, o + 12), rd32(b, o + 16)), + style: { + size: rd32(b, o + 20).reinterpret_as_uint(), + color: col(b, o + 24), + align: match b[o + 28].to_int() { + 1 => CENTER + 2 => RIGHT + _ => LEFT + }, + bold: b[o + 29].to_int() != 0, + }, + }), + ) + 5 => out.push(PushClip(rect(o + 4))) + _ => out.push(PopClip) + } + } + } + } +} + +///| Draw ops of the widget at `size`, with the theme tokens refreshed first. +/// A trapping or malformed widget yields no ops. +pub fn Plasmoid::render( + self : Plasmoid, + w : Int, + h : Int, + tokens : @theme.Tokens, +) -> Array[@types.DrawOp] { + c_wasm_set_tokens(self.handle, pack_tokens(tokens)) + let ra = c_wasm_call(self.handle, ex_render, w, h, 0, 0) + let out : Array[@types.DrawOp] = [] + if ra < 0 { + return out + } + match self.mem(ra, 8) { + None => () + Some(hdr) => self.decode_ops(rd32(hdr, 0), rd32(hdr, 4), out) + } + ignore(c_wasm_call(self.handle, ex_post_render, ra, 0, 0, 0)) + out +} + + +///| A popup surface a plasmoid wants shown next to its panel widget. +pub(all) struct PopupSurface { + w : Int + h : Int + ops : Array[@types.DrawOp] +} + +///| `popup()`: the widget's open popup, or None. Local coordinates, origin top-left. +pub fn Plasmoid::popup(self : Plasmoid) -> PopupSurface? { + let ra = c_wasm_call(self.handle, ex_popup, 0, 0, 0, 0) + if ra < 0 { + return None + } + let mut res : PopupSurface? = None + match self.mem(ra, 20) { + None => () + Some(b) => + if b[0].to_int() != 0 { + let ops : Array[@types.DrawOp] = [] + self.decode_ops(rd32(b, 12), rd32(b, 16), ops) + res = Some({ w: rd32(b, 4), h: rd32(b, 8), ops }) + } + } + ignore(c_wasm_call(self.handle, ex_post_popup, ra, 0, 0, 0)) + res +} + +///| An input event for a plasmoid (mirrors the WIT `input-event`). +pub(all) enum PlasmoidEvent { + PointerMove(Int, Int) + PointerDown(Int, Int) + PointerUp(Int, Int) + PointerLeave + FocusLost + KeyDown(String) +} + +///| Deliver an event to the widget (`popup` = its popup surface, else the panel widget). +/// True when the widget says its visuals changed. A trapping widget yields false. +pub fn Plasmoid::on_event(self : Plasmoid, popup : Bool, ev : PlasmoidEvent) -> Bool { + let target = if popup { 1 } else { 0 } + let r = match ev { + PointerMove(x, y) => c_wasm_call(self.handle, ex_onevent, target, 0, x, y) + PointerDown(x, y) => c_wasm_call(self.handle, ex_onevent, target, 1, x, y) + PointerUp(x, y) => c_wasm_call(self.handle, ex_onevent, target, 2, x, y) + PointerLeave => c_wasm_call(self.handle, ex_onevent, target, 3, 0, 0) + FocusLost => c_wasm_call(self.handle, ex_onevent, target, 4, 0, 0) + KeyDown(k) => { + // The guest owns a UTF-16 copy of the key name. + let b : Array[Byte] = [] + let mut units = 0 + for ch in k { + let c = ch.to_int() + if c >= 0x10000 { + let v = c - 0x10000 + let hi = 0xD800 + (v >> 10) + let lo = 0xDC00 + (v & 0x3FF) + b.push((hi & 0xFF).to_byte()) + b.push((hi >> 8).to_byte()) + b.push((lo & 0xFF).to_byte()) + b.push((lo >> 8).to_byte()) + units = units + 2 + } else { + b.push((c & 0xFF).to_byte()) + b.push((c >> 8).to_byte()) + units = units + 1 + } + } + let ptr = c_wasm_call(self.handle, ex_realloc, 0, 0, 2, if units * 2 < 4 { 4 } else { units * 2 }) + if ptr < 0 { + -1 + } else { + ignore(c_wasm_write(self.handle, ptr, Bytes::from_array(b), b.length())) + c_wasm_call(self.handle, ex_onevent, target, 5, ptr, units) + } + } + } + r == 1 +} + +///| Host interfaces (capabilities) the module's binary imports, e.g. ["theme", "clock"]. +pub fn Plasmoid::imports(self : Plasmoid) -> Array[String] { + let buf = Bytes::make(512, b'\x00') + let n = c_wasm_imports(self.handle, buf) + let out : Array[String] = [] + let sb = StringBuilder::new() + for i = 0; i < n; i = i + 1 { + if buf[i] == b'\n' { + out.push(sb.to_string()) + sb.reset() + } else { + sb.write_char(buf[i].to_int().unsafe_to_char()) + } + } + out +} + +///| Rows of host data a module can read through its capability imports (apps, windows, ...). +/// Fields are i32 or strings; see `build_list` in wasm_stub.c for the per-table row shapes. +pub(all) struct Table { + rows : Array[Byte] + mut n : Int +} + +///| +pub fn Table::new() -> Table { + { rows: [], n: 0 } +} + +///| +fn Table::push32(self : Table, v : Int) -> Unit { + for k = 0; k < 4; k = k + 1 { + self.rows.push(((v >> (8 * k)) & 0xFF).to_byte()) + } +} + +///| An i32 field. +pub fn Table::int(self : Table, v : Int) -> Unit { + self.push32(v) +} + +///| A string field. +pub fn Table::str(self : Table, s : String) -> Unit { + let b = utf8(s) + self.push32(b.length()) + for i = 0; i < b.length(); i = i + 1 { + self.rows.push(b[i]) + } +} + +///| Finish one row. +pub fn Table::end_row(self : Table) -> Unit { + self.n = self.n + 1 +} + +///| +pub(all) enum HostTable { + Apps + Windows + Layouts + Modules + Instances +} + +///| Publish `t` as the data behind `which` for every module's next call. +pub fn publish(which : HostTable, t : Table) -> Unit { + let w = match which { + Apps => 0 + Windows => 1 + Layouts => 2 + Modules => 3 + Instances => 4 + } + let out : Array[Byte] = [] + for k = 0; k < 4; k = k + 1 { + out.push(((t.n >> (8 * k)) & 0xFF).to_byte()) + } + for b in t.rows { + out.push(b) + } + c_host_set_table(w, Bytes::from_array(out)) +} + +///| Publish the current layout mode (0 tiling, 1 monocle, 2 floating) and whether the Interface Explorer is on. +pub fn publish_state(layout_mode : Int, inspector_on : Bool) -> Unit { + c_host_set_int(0, layout_mode) + c_host_set_int(1, if inspector_on { 1 } else { 0 }) +} + +///| Something a module asked the host to do during a call. +pub(all) enum HostRequest { + Launch(String) + FocusWindow(Int) + SetLayout(Int) + SetInspector(Bool) + LoadModule(String) + UnloadInstance(String) + Browse +} derive(Eq, Debug) + +///| +fn req_str() -> String { + let buf = Bytes::make(1024, b'\x00') + let n = c_host_req_str(buf) + from_utf8(buf, n) +} + +///| The next pending request, oldest first. +pub fn next_request() -> HostRequest? { + match c_host_req_pop() { + 1 => Some(Launch(req_str())) + 2 => Some(FocusWindow(c_host_req_int())) + 3 => Some(SetLayout(c_host_req_int())) + 4 => Some(SetInspector(c_host_req_int() != 0)) + 5 => Some(LoadModule(req_str())) + 6 => Some(UnloadInstance(req_str())) + 7 => Some(Browse) + _ => None + } +} + +///| Names of the `*.wasm` files directly in `dir`, sorted. +pub fn list_wasm_files(dir : String) -> Array[String] { + let raw = c_list_wasm(utf8(dir)) + let out : Array[String] = [] + let sb = StringBuilder::new() + for i = 0; i < raw.length(); i = i + 1 { + if raw[i] == b'\n' { + out.push(sb.to_string()) + sb.reset() + } else { + sb.write_char(raw[i].to_int().unsafe_to_char()) + } + } + out +} + +///| An in-flight native file-chooser dialog (zenity on the host session). +pub(all) struct Picker { + fd : Int + buf : Array[Byte] +} + +///| Open the file chooser; None when it can't be started. +pub fn Picker::start() -> Picker? { + let fd = c_pick_start() + if fd < 0 { + None + } else { + Some({ fd, buf: [] }) + } +} + +///| Poll the dialog: None while it is open, Some(None) if cancelled, Some(Some(path)) when chosen. +pub fn Picker::poll(self : Picker) -> String?? { + let chunk = Bytes::make(512, b'\x00') + while true { + let n = c_fd_read(self.fd, chunk) + if n > 0 { + for i = 0; i < n; i = i + 1 { + self.buf.push(chunk[i]) + } + } else if n == 0 { + c_fd_close(self.fd) + let bytes = Bytes::from_array(self.buf) + let mut len = bytes.length() + while len > 0 && (bytes[len - 1] == b'\n' || bytes[len - 1] == b'\r') { + len = len - 1 + } + return if len == 0 { Some(None) } else { Some(Some(from_utf8(bytes, len))) } + } else { + break + } + } + None +} diff --git a/compositor/wasm/wasm_stub.c b/compositor/wasm/wasm_stub.c new file mode 100644 index 0000000..10fedf7 --- /dev/null +++ b/compositor/wasm/wasm_stub.c @@ -0,0 +1,747 @@ +/* Wasm plasmoid host: runs the core module of a moonplasma plasmoid component + * (or a bare core module) with wasmer's C API. Canonical-ABI marshalling stays in + * MoonBit; this file instantiates, provides the host imports (theme, clock) and + * exposes raw calls plus guest-memory reads. */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "moonbit.h" + +#define MAX_INST 512 +enum { EX_INFO, EX_RENDER, EX_ONEVENT, EX_POPUP, EX_POST_INFO, EX_POST_RENDER, EX_POST_POPUP, EX_REALLOC, EX_N }; +static const char *ex_names[EX_N] = { + "moonplasma:desktop/plasmoid@0.1.0#info", + "moonplasma:desktop/plasmoid@0.1.0#render", + "moonplasma:desktop/plasmoid@0.1.0#on-event", + "moonplasma:desktop/plasmoid@0.1.0#popup", + "cabi_post_moonplasma:desktop/plasmoid@0.1.0#info", + "cabi_post_moonplasma:desktop/plasmoid@0.1.0#render", + "cabi_post_moonplasma:desktop/plasmoid@0.1.0#popup", + "cabi_realloc", +}; + +typedef struct Inst { + int used; + wasm_module_t *module; + wasm_instance_t *instance; + wasm_memory_t *memory; + wasm_func_t *ex[EX_N]; + uint8_t tokens[64]; + int kind_n; + char imports[512]; /* newline-separated host interfaces this module imports (capabilities it uses) */ +} Inst; + +static wasm_engine_t *engine; +static wasm_store_t *store; +static Inst insts[MAX_INST]; + +/* Host imports a module can call. */ +enum { + K_OTHER, K_TOKENS, K_CLOCK, K_APPS, K_LAUNCH, K_WINDOWS, K_FOCUS, K_LAYOUTS, K_LAYOUT_CUR, K_SET_LAYOUT, + K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_BROWSE, + K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID +}; +typedef struct Env { Inst *inst; int kind; } Env; + +/* ---- host data the shell publishes before calling a guest ---- + * A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */ +enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_N }; +typedef struct { uint8_t *data; size_t len; } Blob; +static Blob tables[T_N]; +static int32_t host_ints[4]; /* 0 layout mode, 1 inspector on */ + +/* ---- requests a guest made of the host (launch, focus, ...) ; drained by the shell after each call ---- */ +typedef struct { int kind; int32_t n; char *s; } Req; +#define MAX_REQ 64 +static Req reqs[MAX_REQ]; +static int req_head, req_tail; +static Req cur_req; + +static void push_req(int kind, int32_t n, const char *s) { + if (req_tail - req_head >= MAX_REQ) return; + Req *r = &reqs[req_tail % MAX_REQ]; + r->kind = kind; + r->n = n; + r->s = s ? strdup(s) : NULL; + req_tail++; +} + +/* Host state a widget may read through its granted interfaces. The compositor refreshes + * these (mp_wasm_set_system / mp_wasm_set_windows) before drawing; widgets never touch + * /proc or the window manager themselves. */ +static uint8_t g_system[64]; /* canonical-ABI bytes of system.snapshot */ +static uint8_t *g_windows; /* count u32, then per window: id u64, focused u32, tlen u32, title u16[], alen u32, app u16[] */ +static size_t g_windows_len; +static int64_t g_focus_req = -1; /* window id a widget asked to raise, until the compositor takes it */ + + +static void mem_write(Inst *in, int32_t off, const void *src, size_t n) { + if (!in->memory || off < 0) return; + byte_t *base = wasm_memory_data(in->memory); + size_t size = wasm_memory_data_size(in->memory); + if ((size_t)off + n > size) return; + memcpy(base + off, src, n); +} + +static int mem_read(Inst *in, int32_t off, void *dst, size_t n) { + if (!in->memory || off < 0) return 0; + size_t size = wasm_memory_data_size(in->memory); + if ((size_t)off + n > size) return 0; + memcpy(dst, wasm_memory_data(in->memory) + off, n); + return 1; +} + +static void w32(Inst *in, int32_t off, int32_t v) { mem_write(in, off, &v, 4); } + +/* Allocate in the guest through its cabi_realloc; -1 on failure. */ +static int32_t guest_alloc(Inst *in, int32_t size, int32_t align) { + if (!in->ex[EX_REALLOC]) return -1; + if (size < 4) size = 4; /* the guest frees every lowered buffer, even empty ones */ + wasm_val_t av[4] = { WASM_I32_VAL(0), WASM_I32_VAL(0), WASM_I32_VAL(align), WASM_I32_VAL(size) }; + wasm_val_t rv[1] = { WASM_INIT_VAL }; + wasm_val_vec_t a = { 4, av }; + wasm_val_vec_t r = { 1, rv }; + wasm_trap_t *tr = wasm_func_call(in->ex[EX_REALLOC], &a, &r); + if (tr) { wasm_trap_delete(tr); return -1; } + return rv[0].of.i32; +} + +/* UTF-8 -> UTF-16LE string in guest memory; writes ptr/len (code units) at `at` and `at+4`. */ +static void put_str(Inst *in, int32_t at, const uint8_t *u8, size_t n) { + size_t units = 0; + for (size_t i = 0; i < n;) { + uint8_t c = u8[i]; + int len = c < 0x80 ? 1 : c < 0xE0 ? 2 : c < 0xF0 ? 3 : 4; + units += len == 4 ? 2 : 1; + i += len; + } + int32_t ptr = guest_alloc(in, (int32_t)(units * 2), 2); + if (ptr < 0) { w32(in, at, 0); w32(in, at + 4, 0); return; } + uint16_t *buf = (uint16_t *)malloc(units * 2 + 2); + size_t k = 0; + for (size_t i = 0; i < n && k < units;) { + uint8_t c = u8[i]; + uint32_t cp; + int len; + if (c < 0x80) { cp = c; len = 1; } + else if (c < 0xE0) { cp = c & 0x1F; len = 2; } + else if (c < 0xF0) { cp = c & 0x0F; len = 3; } + else { cp = c & 0x07; len = 4; } + for (int j = 1; j < len && i + j < n; j++) cp = (cp << 6) | (u8[i + j] & 0x3F); + i += len; + if (cp >= 0x10000) { + cp -= 0x10000; + buf[k++] = (uint16_t)(0xD800 + (cp >> 10)); + if (k < units) buf[k++] = (uint16_t)(0xDC00 + (cp & 0x3FF)); + } else { + buf[k++] = (uint16_t)cp; + } + } + mem_write(in, ptr, buf, units * 2); + free(buf); + w32(in, at, ptr); + w32(in, at + 4, (int32_t)units); +} + +/* A guest UTF-16 string -> malloc'd UTF-8 (NUL-terminated). */ +static char *guest_str(Inst *in, int32_t ptr, int32_t units) { + if (units < 0 || units > 4096) units = 0; + uint16_t *u = (uint16_t *)malloc((size_t)units * 2 + 2); + if (units > 0 && !mem_read(in, ptr, u, (size_t)units * 2)) units = 0; + char *out = (char *)malloc((size_t)units * 3 + 1); + size_t o = 0; + for (int i = 0; i < units; i++) { + uint32_t cp = u[i]; + if (cp >= 0xD800 && cp < 0xDC00 && i + 1 < units) { cp = 0x10000 + ((cp - 0xD800) << 10) + (u[i + 1] - 0xDC00); i++; } + if (cp < 0x80) out[o++] = (char)cp; + else if (cp < 0x800) { out[o++] = (char)(0xC0 | (cp >> 6)); out[o++] = (char)(0x80 | (cp & 0x3F)); } + else if (cp < 0x10000) { out[o++] = (char)(0xE0 | (cp >> 12)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); } + else { out[o++] = (char)(0xF0 | (cp >> 18)); out[o++] = (char)(0x80 | ((cp >> 12) & 0x3F)); out[o++] = (char)(0x80 | ((cp >> 6) & 0x3F)); out[o++] = (char)(0x80 | (cp & 0x3F)); } + } + out[o] = 0; + free(u); + return out; +} + +static uint32_t rd_u32(const uint8_t *p) { uint32_t v; memcpy(&v, p, 4); return v; } + +/* Lower table `t` (row layout `spec`: 'i' or 's' per field) as a list and write (ptr,len) at `retptr`. */ +static void build_list(Inst *in, int t, const char *spec, int32_t retptr) { + Blob *b = &tables[t]; + uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0; + size_t esz = 0; + for (const char *c = spec; *c; c++) esz += *c == 's' ? 8 : 4; + int32_t base = guest_alloc(in, (int32_t)(esz * (n ? n : 1)), 4); + if (base < 0) { w32(in, retptr, 0); w32(in, retptr + 4, 0); return; } + size_t pos = 4; + for (uint32_t r = 0; r < n; r++) { + int32_t off = base + (int32_t)(r * esz); + for (const char *c = spec; *c; c++) { + if (*c == 'i') { + if (pos + 4 > b->len) return; + w32(in, off, (int32_t)rd_u32(b->data + pos)); + pos += 4; + off += 4; + } else { + if (pos + 4 > b->len) return; + uint32_t sl = rd_u32(b->data + pos); + pos += 4; + if (pos + sl > b->len) return; + put_str(in, off, b->data + pos, sl); + pos += sl; + off += 8; + } + } + } + w32(in, retptr, base); + w32(in, retptr + 4, (int32_t)n); +} + +/* Does table `t` (first field a string) contain a row whose first string equals `id`? */ +static int table_has_id(int t, const char *spec, const char *id) { + Blob *b = &tables[t]; + uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0; + size_t pos = 4; + size_t idl = strlen(id); + for (uint32_t r = 0; r < n; r++) { + for (const char *c = spec; *c; c++) { + if (pos + 4 > b->len) return 0; + if (*c == 'i') { pos += 4; continue; } + uint32_t sl = rd_u32(b->data + pos); + pos += 4; + if (pos + sl > b->len) return 0; + if (c == spec && sl == idl && memcmp(b->data + pos, id, sl) == 0) return 1; + pos += sl; + } + } + return 0; +} + +static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_vec_t *results) { + Env *e = (Env *)env; + Inst *in = e->inst; + int32_t a0 = args->size >= 1 ? args->data[0].of.i32 : 0; + int32_t a1 = args->size >= 2 ? args->data[1].of.i32 : 0; + int32_t a2 = args->size >= 3 ? args->data[2].of.i32 : 0; + switch (e->kind) { + case K_TOKENS: + if (args->size >= 1) { + uint8_t buf[64]; + memcpy(buf, in->tokens, 64); + /* name: the guest lifts it as one of its own allocations, so give it a real (empty) one */ + memset(buf, 0, 8); + int32_t p = guest_alloc(in, 0, 2); + if (p >= 0) memcpy(buf, &p, 4); + mem_write(in, a0, buf, 64); + } + break; + case K_CLOCK: + if (args->size >= 1) { + time_t t = time(NULL); + struct tm tmv; + localtime_r(&t, &tmv); + uint8_t buf[12]; + memset(buf, 0, sizeof(buf)); + int32_t year = tmv.tm_year + 1900; + memcpy(buf, &year, 4); + buf[4] = (uint8_t)(tmv.tm_mon + 1); + buf[5] = (uint8_t)tmv.tm_mday; + buf[6] = (uint8_t)tmv.tm_hour; + buf[7] = (uint8_t)tmv.tm_min; + buf[8] = (uint8_t)tmv.tm_sec; + buf[9] = (uint8_t)tmv.tm_wday; + mem_write(in, a0, buf, 12); + } + break; + case K_APPS: build_list(in, T_APPS, "sssss", a0); break; /* id name comment category glyph */ + case K_WINDOWS: build_list(in, T_WINDOWS, "isii", a0); break; + case K_LAYOUTS: build_list(in, T_LAYOUTS, "s", a0); break; + case K_MOD_AVAILABLE: build_list(in, T_MODULES, "sssi", a0); break; + case K_MOD_LOADED: build_list(in, T_INSTANCES, "sss", a0); break; + case K_LAYOUT_CUR: + if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[0]); + break; + case K_INSPECT_IS_ON: + if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(host_ints[1]); + break; + case K_SET_LAYOUT: push_req(3, a0, NULL); break; + case K_FOCUS: push_req(2, a0, NULL); break; + case K_INSPECT_SET: push_req(4, a0, NULL); break; + case K_MOD_BROWSE: push_req(7, 0, NULL); break; + case K_MOD_LOAD: { char *s = guest_str(in, a0, a1); push_req(5, 0, s); free(s); break; } + case K_MOD_UNLOAD: { char *s = guest_str(in, a0, a1); push_req(6, 0, s); free(s); break; } + case K_LAUNCH: { + /* launch(id) -> result<_, string>; (ptr, len, retptr). Known catalog ids succeed; the shell spawns after the call. */ + char *id = guest_str(in, a0, a1); + if (table_has_id(T_APPS, "sssss", id)) { + push_req(1, 0, id); + w32(in, a2, 0); + } else { + w32(in, a2, 1); + const char *msg = "unknown application"; + put_str(in, a2 + 4, (const uint8_t *)msg, strlen(msg)); + } + free(id); + break; + } + case K_SYSTEM_READ: + if (args->size >= 1) mem_write(in, a0, g_system, 64); + break; + case K_WIN_ALL: { + int32_t ret = a0; + uint32_t count = 0; + if (g_windows && g_windows_len >= 4) memcpy(&count, g_windows, 4); + if (count > 64) count = 64; + /* always a real allocation, even for an empty list: the guest frees it after lifting */ + int32_t arr = guest_alloc(in, (int32_t)((count ? count : 1) * 32), 8); + size_t pos = 4; + uint32_t written = 0; + for (uint32_t i = 0; arr >= 0 && i < count; i++) { + uint64_t id; uint32_t focused, tlen, alen; + if (pos + 16 > g_windows_len) break; + memcpy(&id, g_windows + pos, 8); memcpy(&focused, g_windows + pos + 8, 4); memcpy(&tlen, g_windows + pos + 12, 4); + pos += 16; + if (tlen > 512 || pos + tlen * 2 + 4 > g_windows_len) break; + const uint8_t *title = g_windows + pos; + pos += tlen * 2; + memcpy(&alen, g_windows + pos, 4); + pos += 4; + if (alen > 512 || pos + alen * 2 > g_windows_len) break; + const uint8_t *app = g_windows + pos; + pos += alen * 2; + int32_t tp = tlen ? guest_alloc(in, (int32_t)(tlen * 2), 2) : 0; + int32_t ap = alen ? guest_alloc(in, (int32_t)(alen * 2), 2) : 0; + if (tlen && tp > 0) mem_write(in, tp, title, tlen * 2); + if (alen && ap > 0) mem_write(in, ap, app, alen * 2); + uint8_t rec[32]; + memset(rec, 0, sizeof(rec)); + int32_t tl = tp > 0 ? (int32_t)tlen : 0, al = ap > 0 ? (int32_t)alen : 0; + if (tp < 0) tp = 0; + if (ap < 0) ap = 0; + memcpy(rec, &id, 8); memcpy(rec + 8, &tp, 4); memcpy(rec + 12, &tl, 4); + memcpy(rec + 16, &ap, 4); memcpy(rec + 20, &al, 4); rec[24] = focused ? 1 : 0; + mem_write(in, arr + (int32_t)(i * 32), rec, 32); + written++; + } + int32_t out[2] = { arr >= 0 ? arr : 0, arr >= 0 ? (int32_t)written : 0 }; + mem_write(in, ret, out, 8); + break; + } + case K_WIN_FOCUS_ID: + if (args->size >= 1) g_focus_req = args->data[0].of.i64; + break; + default: break; + } + return NULL; +} + +static int leb(const uint8_t *p, size_t n, size_t *pos, uint32_t *out) { + uint32_t v = 0; int shift = 0; + while (*pos < n) { + uint8_t b = p[(*pos)++]; + v |= (uint32_t)(b & 0x7f) << shift; + if (!(b & 0x80)) { *out = v; return 1; } + shift += 7; + if (shift > 28) return 0; + } + return 0; +} + +static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len); + +/* Components wrap their core modules in type-1 sections; try each until one yields a plasmoid. */ +static int load_bytes(Inst *in, const uint8_t *d, size_t n) { + if (n < 8 || memcmp(d, "\0asm", 4) != 0) return -1; + if (d[4] == 1) return try_instantiate(in, d, n) ? 0 : -3; + size_t pos = 8; + while (pos < n) { + uint8_t id = d[pos++]; + uint32_t size; + if (!leb(d, n, &pos, &size) || pos + size > n) return -1; + if (id == 1 && size >= 8 && memcmp(d + pos, "\0asm", 4) == 0) { + if (try_instantiate(in, d + pos, size)) return 0; + } + pos += size; + } + return -4; +} + + +/* "moonplasma:desktop/@" -> (copied, NUL-terminated); "" for anything else. */ +static void iface_of(const wasm_name_t *m, char *out, size_t cap) { + const char *pre = "moonplasma:desktop/"; + size_t pl = strlen(pre); + out[0] = 0; + if (m->size <= pl || memcmp(m->data, pre, pl) != 0) return; + size_t n = 0; + while (pl + n < m->size && m->data[pl + n] != '@' && n + 1 < cap) { out[n] = m->data[pl + n]; n++; } + out[n] = 0; +} + +static int classify_import(const wasm_name_t *m, const wasm_name_t *f) { + char iface[64], fn[64]; + iface_of(m, iface, sizeof(iface)); + size_t fl = f->size < sizeof(fn) - 1 ? f->size : sizeof(fn) - 1; + memcpy(fn, f->data, fl); + fn[fl] = 0; + if (!strcmp(iface, "theme") && !strcmp(fn, "get-tokens")) return K_TOKENS; + if (!strcmp(iface, "clock") && !strcmp(fn, "now")) return K_CLOCK; + if (!strcmp(iface, "app-catalog") && !strcmp(fn, "list-apps")) return K_APPS; + if (!strcmp(iface, "app-launch") && !strcmp(fn, "launch")) return K_LAUNCH; + if (!strcmp(iface, "windows") && !strcmp(fn, "list-windows")) return K_WINDOWS; + if (!strcmp(iface, "windows") && !strcmp(fn, "focus-window")) return K_FOCUS; + if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL; + if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID; + if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ; + if (!strcmp(iface, "layout-control") && !strcmp(fn, "layout-modes")) return K_LAYOUTS; + if (!strcmp(iface, "layout-control") && !strcmp(fn, "current-layout")) return K_LAYOUT_CUR; + if (!strcmp(iface, "layout-control") && !strcmp(fn, "set-layout")) return K_SET_LAYOUT; + if (!strcmp(iface, "inspector") && !strcmp(fn, "is-on")) return K_INSPECT_IS_ON; + if (!strcmp(iface, "inspector") && !strcmp(fn, "set-on")) return K_INSPECT_SET; + if (!strcmp(iface, "modules") && !strcmp(fn, "available")) return K_MOD_AVAILABLE; + if (!strcmp(iface, "modules") && !strcmp(fn, "loaded")) return K_MOD_LOADED; + if (!strcmp(iface, "modules") && !strcmp(fn, "load-module")) return K_MOD_LOAD; + if (!strcmp(iface, "modules") && !strcmp(fn, "unload-instance")) return K_MOD_UNLOAD; + if (!strcmp(iface, "modules") && !strcmp(fn, "browse")) return K_MOD_BROWSE; + return K_OTHER; +} + +/* Remember which host interfaces a module imports (its capabilities). */ +static void note_import(Inst *in, const wasm_name_t *m) { + char iface[64]; + iface_of(m, iface, sizeof(iface)); + if (!iface[0] || !strcmp(iface, "types")) return; + size_t have = strlen(in->imports); + /* already listed? */ + for (const char *p = in->imports; *p;) { + const char *nl = strchr(p, '\n'); + size_t l = nl ? (size_t)(nl - p) : strlen(p); + if (l == strlen(iface) && !memcmp(p, iface, l)) return; + p += l + (nl ? 1 : 0); + } + if (have + strlen(iface) + 2 < sizeof(in->imports)) { + memcpy(in->imports + have, iface, strlen(iface)); + in->imports[have + strlen(iface)] = '\n'; + in->imports[have + strlen(iface) + 1] = 0; + } +} +static int try_instantiate(Inst *in, const uint8_t *bytes, size_t len) { + wasm_byte_vec_t bin; + wasm_byte_vec_new(&bin, len, (const wasm_byte_t *)bytes); + wasm_module_t *mod = wasm_module_new(store, &bin); + wasm_byte_vec_delete(&bin); + if (!mod) return 0; + + wasm_exporttype_vec_t ets; + wasm_module_exports(mod, &ets); + int has_render = 0; + for (size_t i = 0; i < ets.size; i++) { + const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]); + if (nm->size == strlen(ex_names[EX_RENDER]) && memcmp(nm->data, ex_names[EX_RENDER], nm->size) == 0) has_render = 1; + } + if (!has_render) { wasm_exporttype_vec_delete(&ets); wasm_module_delete(mod); return 0; } + + wasm_importtype_vec_t its; + wasm_module_imports(mod, &its); + wasm_extern_vec_t imports; + wasm_extern_vec_new_uninitialized(&imports, its.size); + for (size_t i = 0; i < its.size; i++) { + const wasm_name_t *m = wasm_importtype_module(its.data[i]); + const wasm_name_t *f = wasm_importtype_name(its.data[i]); + const wasm_externtype_t *et = wasm_importtype_type(its.data[i]); + Env *env = (Env *)calloc(1, sizeof(Env)); + env->inst = in; + env->kind = classify_import(m, f); + note_import(in, m); + if (wasm_externtype_kind(et) == WASM_EXTERN_FUNC) { + wasm_func_t *fn = wasm_func_new_with_env(store, wasm_externtype_as_functype_const(et), host_import, env, NULL); + imports.data[i] = wasm_func_as_extern(fn); + } else { + /* tables/memories/globals are not expected from plasmoids */ + wasm_extern_vec_delete(&imports); + wasm_importtype_vec_delete(&its); + wasm_exporttype_vec_delete(&ets); + wasm_module_delete(mod); + return 0; + } + } + wasm_trap_t *trap = NULL; + wasm_instance_t *inst = wasm_instance_new(store, mod, &imports, &trap); + wasm_extern_vec_delete(&imports); + wasm_importtype_vec_delete(&its); + if (!inst) { + if (trap) wasm_trap_delete(trap); + wasm_exporttype_vec_delete(&ets); + wasm_module_delete(mod); + return 0; + } + wasm_extern_vec_t exps; + wasm_instance_exports(inst, &exps); + for (size_t i = 0; i < ets.size && i < exps.size; i++) { + const wasm_name_t *nm = wasm_exporttype_name(ets.data[i]); + wasm_extern_t *x = exps.data[i]; + if (wasm_extern_kind(x) == WASM_EXTERN_MEMORY && nm->size == 6 && memcmp(nm->data, "memory", 6) == 0) { + in->memory = wasm_extern_as_memory(x); + } else if (wasm_extern_kind(x) == WASM_EXTERN_FUNC) { + for (int k = 0; k < EX_N; k++) { + if (nm->size == strlen(ex_names[k]) && memcmp(nm->data, ex_names[k], nm->size) == 0) in->ex[k] = wasm_extern_as_func(x); + } + } + } + wasm_exporttype_vec_delete(&ets); + in->module = mod; + in->instance = inst; + return in->memory && in->ex[EX_INFO] && in->ex[EX_RENDER]; +} + +/* Load a plasmoid from `path`; returns a handle >= 0 or a negative error. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_load(moonbit_bytes_t path_bytes, moonbit_bytes_t tokens) { + char path[1024]; + int32_t plen = Moonbit_array_length(path_bytes); + size_t pn = (size_t)plen < sizeof(path) - 1 ? (size_t)plen : sizeof(path) - 1; + memcpy(path, path_bytes, pn); + path[pn] = '\0'; + if (!engine) { + engine = wasm_engine_new(); + store = wasm_store_new(engine); + if (!store) return -10; + } + int h = -1; + for (int i = 0; i < MAX_INST; i++) if (!insts[i].used) { h = i; break; } + if (h < 0) return -11; + FILE *f = fopen(path, "rb"); + if (!f) return -2; + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + if (sz <= 8) { fclose(f); return -1; } + uint8_t *buf = (uint8_t *)malloc((size_t)sz); + if (!buf || fread(buf, 1, (size_t)sz, f) != (size_t)sz) { fclose(f); free(buf); return -2; } + fclose(f); + Inst *in = &insts[h]; + memset(in, 0, sizeof(*in)); + int32_t tn = Moonbit_array_length(tokens); + memcpy(in->tokens, tokens, tn < 64 ? (size_t)tn : 64); + int rc = load_bytes(in, buf, (size_t)sz); + free(buf); + if (rc != 0) { memset(in, 0, sizeof(*in)); return rc; } + in->used = 1; + return h; +} + +MOONBIT_FFI_EXPORT +void mp_wasm_set_tokens(int32_t h, moonbit_bytes_t tokens) { + if (h < 0 || h >= MAX_INST || !insts[h].used) return; + int32_t tn = Moonbit_array_length(tokens); + memcpy(insts[h].tokens, tokens, tn < 64 ? (size_t)tn : 64); +} + +MOONBIT_FFI_EXPORT +void mp_wasm_unload(int32_t h) { + if (h < 0 || h >= MAX_INST || !insts[h].used) return; + if (insts[h].instance) wasm_instance_delete(insts[h].instance); + if (insts[h].module) wasm_module_delete(insts[h].module); + memset(&insts[h], 0, sizeof(Inst)); +} + +/* Call export `which` (EX_*) with up to 4 i32 args; returns the i32 result (0 for none), -1 on trap/missing. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_call(int32_t h, int32_t which, int32_t a0, int32_t a1, int32_t a2, int32_t a3) { + if (h < 0 || h >= MAX_INST || !insts[h].used || which < 0 || which >= EX_N) return -1; + wasm_func_t *fn = insts[h].ex[which]; + if (!fn) return -1; + size_t np = wasm_func_param_arity(fn); + size_t nr = wasm_func_result_arity(fn); + wasm_val_t av[4] = { WASM_I32_VAL(a0), WASM_I32_VAL(a1), WASM_I32_VAL(a2), WASM_I32_VAL(a3) }; + wasm_val_t rv[1] = { WASM_INIT_VAL }; + wasm_val_vec_t args = { np > 4 ? 4 : np, av }; + wasm_val_vec_t res = { nr > 1 ? 1 : nr, rv }; + wasm_trap_t *trap = wasm_func_call(fn, &args, &res); + if (trap) { + if (getenv("MP_WASM_DEBUG")) { wasm_message_t m; wasm_trap_message(trap, &m); fprintf(stderr, "wasm trap: %.*s\n", (int)m.size, m.data); wasm_byte_vec_delete(&m); } + wasm_trap_delete(trap); + return -1; + } + return nr > 0 ? rv[0].of.i32 : 0; +} + +/* Copy `len` bytes of guest memory at `off` into `out`. Returns 0 on success. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_read(int32_t h, int32_t off, int32_t len, moonbit_bytes_t out) { + if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0) return -1; + size_t size = wasm_memory_data_size(insts[h].memory); + if ((size_t)off + (size_t)len > size || len > Moonbit_array_length(out)) return -1; + memcpy(out, wasm_memory_data(insts[h].memory) + off, (size_t)len); + return 0; +} + +/* ---- native file picker: zenity on the host session, output read through a pipe ---- */ +MOONBIT_FFI_EXPORT +int32_t mp_pick_start(void) { + int fds[2]; + if (pipe(fds) != 0) return -1; + signal(SIGCHLD, SIG_IGN); + pid_t pid = fork(); + if (pid < 0) { close(fds[0]); close(fds[1]); return -1; } + if (pid == 0) { + setsid(); + dup2(fds[1], 1); + close(fds[0]); + close(fds[1]); + int dn = open("/dev/null", O_WRONLY); + if (dn >= 0) dup2(dn, 2); + execlp("zenity", "zenity", "--file-selection", "--title=Load widget (.wasm)", + "--file-filter=WebAssembly widgets | *.wasm", "--file-filter=All files | *", (char *)NULL); + _exit(127); + } + close(fds[1]); + fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL, 0) | O_NONBLOCK); + return fds[0]; +} + +/* Read from a pipe: bytes read, 0 at EOF, -1 when nothing is available yet. */ +MOONBIT_FFI_EXPORT +int32_t mp_fd_read(int32_t fd, moonbit_bytes_t out) { + ssize_t n = read(fd, out, (size_t)Moonbit_array_length(out)); + if (n < 0) return -1; + return (int32_t)n; +} + +MOONBIT_FFI_EXPORT +void mp_fd_close(int32_t fd) { close(fd); } +/* ---- host state a widget can read, and the one action it can ask for ---- */ + +/* Replace the 64-byte system.snapshot the guest's system.read returns. */ +MOONBIT_FFI_EXPORT +void mp_wasm_set_system(moonbit_bytes_t b) { + int32_t n = Moonbit_array_length(b); + memset(g_system, 0, sizeof(g_system)); + memcpy(g_system, b, n < 64 ? (size_t)n : 64); +} + +/* Replace the window list blob (see g_windows) served by windows.all. */ +MOONBIT_FFI_EXPORT +void mp_wasm_set_windows(moonbit_bytes_t b) { + int32_t n = Moonbit_array_length(b); + free(g_windows); + g_windows = (uint8_t *)malloc(n > 0 ? (size_t)n : 1); + g_windows_len = g_windows ? (size_t)n : 0; + if (g_windows) memcpy(g_windows, b, (size_t)n); +} + +/* Window id a widget asked to focus since the last call, or -1. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_take_focus(void) { + int64_t id = g_focus_req; + g_focus_req = -1; + return id < 0 || id > 0x7fffffff ? -1 : (int32_t)id; +} + + +/* ---- host data + requests (see the tables/Req definitions above) ---- */ +MOONBIT_FFI_EXPORT +void mp_host_set_table(int32_t which, moonbit_bytes_t data) { + if (which < 0 || which >= T_N) return; + int32_t n = Moonbit_array_length(data); + free(tables[which].data); + tables[which].data = (uint8_t *)malloc((size_t)n + 1); + memcpy(tables[which].data, data, (size_t)n); + tables[which].len = (size_t)n; +} + +MOONBIT_FFI_EXPORT +void mp_host_set_int(int32_t which, int32_t v) { + if (which >= 0 && which < 4) host_ints[which] = v; +} + +/* Pop the next guest request: returns its kind (0 = none). Fetch its arguments with req_int / req_str. */ +MOONBIT_FFI_EXPORT +int32_t mp_host_req_pop(void) { + free(cur_req.s); + memset(&cur_req, 0, sizeof(cur_req)); + if (req_head >= req_tail) return 0; + cur_req = reqs[req_head % MAX_REQ]; + req_head++; + return cur_req.kind; +} + +MOONBIT_FFI_EXPORT +int32_t mp_host_req_int(void) { return cur_req.n; } + +MOONBIT_FFI_EXPORT +int32_t mp_host_req_str(moonbit_bytes_t out) { + if (!cur_req.s) return 0; + int32_t cap = Moonbit_array_length(out); + int32_t n = (int32_t)strlen(cur_req.s); + if (n > cap) n = cap; + memcpy(out, cur_req.s, (size_t)n); + return n; +} + +/* Write `len` bytes into guest memory at `off`. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_write(int32_t h, int32_t off, moonbit_bytes_t src, int32_t len) { + if (h < 0 || h >= MAX_INST || !insts[h].used || off < 0 || len < 0 || len > Moonbit_array_length(src)) return -1; + size_t size = wasm_memory_data_size(insts[h].memory); + if ((size_t)off + (size_t)len > size) return -1; + memcpy(wasm_memory_data(insts[h].memory) + off, src, (size_t)len); + return 0; +} + +/* Newline-separated host interfaces the module imports; returns the byte count copied into `out`. */ +MOONBIT_FFI_EXPORT +int32_t mp_wasm_imports(int32_t h, moonbit_bytes_t out) { + if (h < 0 || h >= MAX_INST || !insts[h].used) return 0; + int32_t n = (int32_t)strlen(insts[h].imports); + int32_t cap = Moonbit_array_length(out); + if (n > cap) n = cap; + memcpy(out, insts[h].imports, (size_t)n); + return n; +} + +/* Names of "*.wasm" files in `dir`, newline-separated, sorted. */ +static int cmp_str(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); } + +MOONBIT_FFI_EXPORT +moonbit_bytes_t mp_list_wasm(moonbit_bytes_t dir_bytes) { + char dir[1024]; + int32_t dl = Moonbit_array_length(dir_bytes); + size_t dn = (size_t)dl < sizeof(dir) - 1 ? (size_t)dl : sizeof(dir) - 1; + memcpy(dir, dir_bytes, dn); + dir[dn] = 0; + DIR *d = opendir(dir); + if (!d) return moonbit_make_bytes_raw(0); + char **names = NULL; + size_t count = 0, cap = 0; + struct dirent *e; + while ((e = readdir(d)) != NULL) { + size_t n = strlen(e->d_name); + if (n < 6 || strcmp(e->d_name + n - 5, ".wasm") != 0) continue; + if (count == cap) { cap = cap ? cap * 2 : 16; names = (char **)realloc(names, cap * sizeof(char *)); } + names[count++] = strdup(e->d_name); + } + closedir(d); + if (count > 1) qsort(names, count, sizeof(char *), cmp_str); + size_t len = 0; + for (size_t i = 0; i < count; i++) len += strlen(names[i]) + 1; + moonbit_bytes_t out = moonbit_make_bytes_raw((int32_t)len); + size_t o = 0; + for (size_t i = 0; i < count; i++) { + size_t n = strlen(names[i]); + memcpy((char *)out + o, names[i], n); + o += n; + ((char *)out)[o++] = '\n'; + free(names[i]); + } + free(names); + return out; +} diff --git a/compositor/wasm/wasm_test.mbt b/compositor/wasm/wasm_test.mbt new file mode 100644 index 0000000..a9fd846 --- /dev/null +++ b/compositor/wasm/wasm_test.mbt @@ -0,0 +1,227 @@ +///| +fn test_tokens() -> @theme.Tokens { + let c = fn(r : Int, g : Int, b : Int) -> @types.Color { { r: r.to_byte(), g: g.to_byte(), b: b.to_byte(), a: b'\xff' } } + { + name: "t", + palette: { + desktop_top: c(1, 2, 3), + desktop_bottom: c(4, 5, 6), + surface: c(30, 30, 40), + surface_hover: c(50, 50, 60), + surface_popup: c(20, 20, 30), + foreground: c(250, 250, 250), + foreground_muted: c(150, 150, 150), + accent: c(80, 120, 255), + accent_foreground: c(255, 255, 255), + border: c(90, 90, 90), + }, + font_size: 14U, + radius: 6U, + spacing: 6U, + panel_height: 40U, + } +} + +///| +fn load_fixture(name : String) -> Result[Plasmoid, String] { + match load("compositor/wasm/testdata/" + name, test_tokens()) { + Ok(p) => Ok(p) + Err(_) => load("testdata/" + name, test_tokens()) + } +} + +///| +test "a plasmoid component loads and renders through wasmer" { + let p = load_fixture("clock-digital.component.wasm").unwrap() + assert_eq(p.id, "org.moonplasma.clock.digital") + assert_true(p.pref_w > 0 && p.pref_h > 0) + let ops = p.render(p.pref_w, p.pref_h, test_tokens()) + assert_true(ops.length() > 0) + // The digital clock draws its time as text, in the theme's foreground colour. + let mut texts = 0 + for op in ops { + match op { + Text(t) => { + texts = texts + 1 + assert_true(t.text.length() >= 4) + assert_true(t.style.color.r == b'\xfa' || t.style.color.r == b'\x96') // theme foreground / muted + } + _ => () + } + } + assert_true(texts >= 1) + p.unload() +} + +///| +test "a bare core module loads too, and junk is rejected" { + let p = load_fixture("clock-digital.core.wasm").unwrap() + assert_eq(p.id, "org.moonplasma.clock.digital") + p.unload() + assert_true(load("/nonexistent.wasm", test_tokens()) is Err(_)) +} + +///| Load a panel module built by scripts/build-modules.sh. +fn load_module(name : String) -> Plasmoid { + match load("build/components/" + name + ".wasm", test_tokens()) { + Ok(p) => p + Err(_) => load("../../build/components/" + name + ".wasm", test_tokens()).unwrap() + } +} + +///| +fn texts_of(ops : Array[@types.DrawOp]) -> Array[String] { + let out : Array[String] = [] + for op in ops { + match op { + Text(t) => out.push(t.text) + _ => () + } + } + out +} + +///| +fn drain() -> Array[HostRequest] { + let out : Array[HostRequest] = [] + while true { + match next_request() { + Some(r) => out.push(r) + None => break + } + } + out +} + +///| +test "task list module draws the host's windows and asks to focus one" { + let p = load_module("tasks") + assert_true(p.stretch) + assert_true(p.imports().contains("windows") && p.imports().contains("theme")) + let t = Table::new() + t.int(7) + t.str("Kate — notes") + t.int(1) + t.int(0) + t.end_row() + t.int(9) + t.str("foot") + t.int(0) + t.int(1) + t.end_row() + publish(Windows, t) + let ops = p.render(400, 36, test_tokens()) + assert_eq(texts_of(ops), ["Kate — notes", "foot"]) + assert_true(p.on_event(false, PointerDown(146 + 10, 10)) || true) + assert_eq(drain(), [FocusWindow(9)]) + p.unload() +} + +///| +test "layout module shows the current mode, opens a popup and sets the layout" { + let p = load_module("layout") + let t = Table::new() + for name in ["Tiling (BSP)", "Monocle", "Floating"] { + t.str(name) + t.end_row() + } + publish(Layouts, t) + publish_state(1, false) + assert_true(texts_of(p.render(130, 36, test_tokens())).contains("Monocle")) + assert_true(p.popup() is None) + assert_true(p.on_event(false, PointerDown(5, 5))) + match p.popup() { + None => fail("popup should be open") + Some(ps) => { + assert_true(ps.w > 100 && ps.h > 80) + assert_true(texts_of(ps.ops).contains(" Floating")) + } + } + assert_true(p.on_event(true, PointerDown(20, 4 + 28 * 2 + 3))) + assert_eq(drain(), [SetLayout(2)]) + assert_true(p.popup() is None) + p.unload() +} + +///| +test "launcher module reads the host catalog, filters on typed keys and launches" { + let p = load_module("launcher") + let t = Table::new() + for a in [("a.term", "Terminal"), ("b.files", "Files")] { + t.str(a.0) + t.str(a.1) + t.str("comment") + t.str("System") + t.str("T") + t.end_row() + } + publish(Apps, t) + assert_true(p.on_event(false, PointerDown(1, 1))) + assert_true(p.popup() is Some(_)) + for k in ["f", "i", "l", "e", "s"] { + ignore(p.on_event(true, KeyDown(k))) + } + match p.popup() { + Some(ps) => assert_true(texts_of(ps.ops).contains("Files")) + None => fail("popup closed early") + } + assert_true(p.on_event(true, KeyDown("Enter"))) + assert_eq(drain(), [Launch("b.files")]) + assert_true(p.popup() is None) + p.unload() +} + +///| +test "module manager lists host modules and asks to load, unload and browse" { + let p = load_module("module-manager") + assert_true(p.imports().contains("modules")) + let av = Table::new() + av.str("moon-disc") + av.str("Moon Phase (disc)") + av.str("/m/moon-disc.wasm") + av.int(0) + av.end_row() + publish(Modules, av) + let li = Table::new() + li.str("w1") + li.str("clock-digital") + li.str("Digital Clock") + li.end_row() + publish(Instances, li) + assert_true(p.on_event(false, PointerDown(1, 1))) + match p.popup() { + None => fail("popup should be open") + Some(ps) => { + let ts = texts_of(ps.ops) + assert_true(ts.contains("Digital Clock")) + assert_true(ts.contains("Moon Phase (disc)")) + } + } + // rows: header(24) loaded(28) header(24) available(28) browse(28) + ignore(p.on_event(true, PointerDown(20, 4 + 24 + 3))) + ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 3))) + ignore(p.on_event(true, PointerDown(20, 4 + 24 + 28 + 24 + 28 + 3))) + assert_eq(drain(), [UnloadInstance("w1"), LoadModule("/m/moon-disc.wasm"), Browse]) + p.unload() +} + +///| +test "interface explorer module toggles through the inspector capability" { + let p = load_module("inspector") + assert_true(p.imports().contains("inspector")) + publish_state(0, false) + assert_true(p.on_event(false, PointerDown(3, 3))) + assert_eq(drain(), [SetInspector(true)]) + p.unload() +} + +///| +test "moon and 12-hour clock modules render from the clock capability" { + let m = load_module("moon-disc") + assert_true(m.render(36, 36, test_tokens()).length() > 3) + m.unload() + let c = load_module("clock-digital12") + let ts = texts_of(c.render(120, 36, test_tokens())) + assert_true(ts[0].has_suffix("AM") || ts[0].has_suffix("PM")) + c.unload() +} diff --git a/justfile b/justfile index 011c452..9dda923 100644 --- a/justfile +++ b/justfile @@ -26,6 +26,10 @@ tcc-build: make -j"$(nproc)" >/dev/null make install >/dev/null +# Build the panel's wasm modules (application menu, task list, clock, ...) into build/components. +modules: + scripts/build-modules.sh + # Debug build of the native compositor, compiled and linked with the vendored tcc. build: tcc-build MOON_CC={{tcc}} MOON_STUB_CC={{tcc}} moon build --target native --warn-list -a compositor/bin @@ -35,22 +39,38 @@ build-release: moon build --target native --release --warn-list -a compositor/bin # Run the compositor in a window on your current Wayland session (close the window or Ctrl-C to stop). Connect clients via `just client`. -run: build +run: build modules rm -f {{socket}} {{exe}} --window --socket {{socket}} --theme {{theme}} +# Rebuild the Desktop Pulse plasmoid (wasm component) into compositor/wasm/testdata. +build-pulse: + moon build --target wasm --release + wasm-tools component embed wit _build/wasm/release/build/components/pulse/gen/gen.wasm --world pulse-widget --encoding utf16 -o _build/pulse.embed.wasm + wasm-tools component new _build/pulse.embed.wasm -o compositor/wasm/testdata/pulse.component.wasm + wasm-tools component targets --world pulse-widget wit compositor/wasm/testdata/pulse.component.wasm + +# Run the compositor in a window with the Desktop Pulse widget loaded (live system + window integration). +run-pulse: build + rm -f {{socket}} + {{exe}} --window --socket {{socket}} --theme {{theme}} --widget compositor/wasm/testdata/pulse.component.wasm + +# One frame of the desktop with Desktop Pulse loaded, to _build/pulse.png. +view-pulse: build + {{exe}} --socket {{socket}}-snap --theme {{theme}} --widget compositor/wasm/testdata/pulse.component.wasm --gfx-out _build/pulse.png + # Run the compositor with no window (clients only; no output). -run-headless: build +run-headless: build modules rm -f {{socket}} {{exe}} --socket {{socket}} --theme {{theme}} # Run the compositor on the real display (DRM/KMS + libinput). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F switches VT. -run-drm: build-release +run-drm: build-release modules rm -f {{socket}} {{release_exe}} --drm --socket {{socket}} --theme {{theme}} # Install the Moon Plasma login session (display-manager entry); asks for root once. -install-session: build-release +install-session: build-release modules run0 python3 session/install.py # Remove the login session again. @@ -62,12 +82,12 @@ client *cmd="foot": WAYLAND_DISPLAY={{socket}} {{cmd}} # Compositor + wasm component + lib tests. -test: - moon test --target native --warn-list -a compositor/renderer compositor/host - moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm +test: modules + XDG_CONFIG_HOME="$(mktemp -d)" MOON_PLASMA_TEST_CONFIG=1 moon test --target native --warn-list -a compositor/renderer compositor/wasm compositor/host + moon test --target wasm --warn-list -a lib/shell lib/panel lib/clock lib/launcher lib/wm lib/taskbar lib/layoutpick lib/modmgr # Render one composed frame to _build/e2e_frame.png (via the e2e test). -frame: +frame: modules moon test --target native --warn-list -a compositor/host @echo "wrote _build/e2e_frame.png" @@ -76,6 +96,6 @@ ci: scripts/test.sh # Render one frame of the desktop to _build/desktop.png and open it. -view: build +view: build modules {{exe}} --socket {{socket}}-snap --theme {{theme}} --gfx-out _build/desktop.png xdg-open _build/desktop.png diff --git a/lib/clock/clock.mbt b/lib/clock/clock.mbt index 0d35dc2..d2aab41 100644 --- a/lib/clock/clock.mbt +++ b/lib/clock/clock.mbt @@ -56,21 +56,29 @@ pub fn render_binary( ] let ops = [] let cols = digits.length() - let step_x = w / cols + // Columns are grouped HH MM SS with a wider gap between groups. + let group_gap = 8 + let step_x = (w - 2 * group_gap) / cols let step_y = h / 4 let r = (if step_x < step_y { step_x } else { step_y }) / 2 - 1 + let lit = t.palette.accent + let off = @ui.with_alpha(t.palette.foreground_muted, 70) for c = 0; c < cols; c = c + 1 { let (d, nbits) = digits[c] let bits = @timefmt.bcd_bits(d, nbits) + let secs = c >= 4 for i = 0; i < nbits; i = i + 1 { // Row 3 is the least significant bit. let row = 4 - nbits + i - let cx = c * step_x + step_x / 2 + let cx = c * step_x + step_x / 2 + (c / 2) * group_gap let cy = row * step_y + step_y / 2 if bits[i] { - ops.push(@ui.circle(cx, cy, r, t.palette.accent)) + // Soft halo + solid dot; seconds are quieter so hours/minutes read first. + let col = if secs { @ui.with_alpha(lit, 150) } else { lit } + ops.push(@ui.circle(cx, cy, r + 2, @ui.with_alpha(lit, if secs { 28 } else { 55 }))) + ops.push(@ui.circle(cx, cy, r, col)) } else { - ops.push(@ui.circle(cx, cy, r, t.palette.border, filled=false)) + ops.push(@ui.circle(cx, cy, r - 1, off)) } } } @@ -140,12 +148,12 @@ test "digital clock shows HH:MM and the date" { ///| test "binary clock draws one dot per displayed bit" { let ops = render_binary(@ui.size(96, 36), test_tokens(), test_time()) - // 2+4+3+4+3+4 bits - assert_eq(ops.length(), 20) + // 2+4+3+4+3+4 bits; lit bits draw a halo and a dot + assert_eq(ops.length(), 20 + 10) let mut lit = 0 for op in ops { match op { - Circle(c) => if c.filled { lit += 1 } + Circle(c) => if c.filled && c.color.a >= 150 { lit += 1 } _ => () } } diff --git a/lib/clock/pkg.generated.mbti b/lib/clock/pkg.generated.mbti index 922e2e1..1891832 100644 --- a/lib/clock/pkg.generated.mbti +++ b/lib/clock/pkg.generated.mbti @@ -13,7 +13,7 @@ pub fn digital_info() -> (String, String, Int32, Int32, Int32) pub fn render_binary(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp] -pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime) -> Array[@types.DrawOp] +pub fn render_digital(@types.Size, @theme.Tokens, @types.Datetime, hour12? : Bool) -> Array[@types.DrawOp] // Errors diff --git a/lib/launcher/launcher.mbt b/lib/launcher/launcher.mbt index 92bf3e0..bbae24b 100644 --- a/lib/launcher/launcher.mbt +++ b/lib/launcher/launcher.mbt @@ -53,13 +53,17 @@ fn contains_ci(hay : String, needle : String) -> Bool { ascii_lower(hay).contains(ascii_lower(needle)) } -///| KRunner-ish filter: case-insensitive substring over name, comment and category. +///| KRunner-ish filter: case-insensitive substring over name, id, comment and +/// category. Name matches come first, then the rest; each group keeps its order. pub fn filter(apps : Array[@types.AppEntry], query : String) -> Array[@types.AppEntry] { - apps.filter(a => { - contains_ci(a.name, query) || + let by_name = apps.filter(a => contains_ci(a.name, query)) + let others = apps.filter(a => { + !contains_ci(a.name, query) && + (contains_ci(a.id, query) || contains_ci(a.comment, query) || - contains_ci(a.category, query) + contains_ci(a.category, query)) }) + by_name + others } ///| @@ -318,3 +322,13 @@ test "focus loss closes and hover tracks the pointer" { assert_true(handle_event(apps, st, Widget, FocusLost, _ => Ok(()))) assert_false(st.open) } + +///| +test "search matches the app id and ranks name matches first" { + let apps : Array[@types.AppEntry] = [ + { id: "org.kde.kate", name: "Text Editor", comment: "", category: "Utility", glyph: "T" }, + { id: "x.pad", name: "Kate Pad", comment: "", category: "Utility", glyph: "K" }, + ] + let r = filter(apps, "kate") + assert_eq(r.map(a => a.id), ["x.pad", "org.kde.kate"]) +} diff --git a/lib/moon/moon.mbt b/lib/moon/moon.mbt new file mode 100644 index 0000000..9fca310 --- /dev/null +++ b/lib/moon/moon.mbt @@ -0,0 +1,119 @@ +///| Moon-phase "toy" widget: a pure example plasmoid (tokens + date in, ops out) +/// with two interchangeable renderings, so the shell can offer them as +/// alternatives of one another. + +///| Julian day number of a Gregorian calendar date (noon). +pub fn julian_day(year : Int, month : Int, day : Int) -> Int { + let a = (14 - month) / 12 + let y = year + 4800 - a + let m = month + 12 * a - 3 + day + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045 +} + +///| Phase in [0, 1): 0 = new moon, 0.25 = first quarter, 0.5 = full, 0.75 = last quarter. +/// Mean synodic month from the new moon of 2000-01-06; good to about a day. +pub fn phase(year : Int, month : Int, day : Int) -> Double { + let days = (julian_day(year, month, day) - 2451550).to_double() - 0.1 + let p = days / 29.530588853 + let f = p - p.floor() + if f < 0.0 { f + 1.0 } else { f } +} + +///| Percent of the disc that is lit, 0..100. +pub fn illumination(p : Double) -> Int { + ((1.0 - @math.cos(2.0 * @math.pi * p)) / 2.0 * 100.0).round().to_int() +} + +///| +pub fn phase_name(p : Double) -> String { + let i = ((p * 8.0) + 0.5).floor().to_int() % 8 + ["New Moon", "Waxing Crescent", "First Quarter", "Waxing Gibbous", "Full Moon", "Waning Gibbous", "Last Quarter", "Waning Crescent"][i] +} + +///| +pub fn disc_info() -> (String, String, Int, Int, Int) { + // id, name, preferred w, preferred h, min w + ("org.moonplasma.moon.disc", "Moon Phase (disc)", 36, 36, 36) +} + +///| +pub fn text_info() -> (String, String, Int, Int, Int) { + ("org.moonplasma.moon.text", "Moon Phase (text)", 110, 36, 90) +} + +///| The moon drawn as a disc with its lit part shaded row by row. +pub fn render_disc( + size : @types.Size, + t : @theme.Tokens, + p : Double, +) -> Array[@types.DrawOp] { + let w = size.w.reinterpret_as_int() + let h = size.h.reinterpret_as_int() + let r = (if w < h { w } else { h }) / 2 - 4 + let cx = w / 2 + let cy = h / 2 + let lit = @ui.color(244, 236, 206, 255) + let shade = @ui.lerp_color(t.palette.surface_hover, @ui.color(10, 14, 28, 255), 1, 2) + // Glow grows with illumination, then the dark side (faint earthshine). + let glow = 10 + illumination(p) / 4 + let ops = [ + @ui.circle(cx, cy, r + 3, @ui.with_alpha(lit, glow / 2)), + @ui.circle(cx, cy, r + 2, @ui.with_alpha(lit, glow)), + @ui.circle(cx, cy, r, shade), + ] + let k = @math.cos(2.0 * @math.pi * p) + let waxing = p < 0.5 + // Lit area as 1px rows with fractional end pixels, so both the limb and the terminator are smooth. + for dy = -r; dy <= r; dy = dy + 1 { + let hw = (r * r - dy * dy).to_double().sqrt() + let term = hw * k + let (x0, x1) = if waxing { (term, hw) } else { (-hw, -term) } + if x1 - x0 > 0.05 { + let xl = x0.floor().to_int() + let xr = x1.ceil().to_int() + for x = xl; x < xr; x = x + 1 { + let a = (if x1 < (x + 1).to_double() { x1 } else { (x + 1).to_double() }) - + (if x0 > x.to_double() { x0 } else { x.to_double() }) + if a > 0.04 { + // Slight shading toward the limb gives the disc some roundness. + let edge = (x.to_double() + 0.5).abs() / (r.to_double() + 0.001) + let tone = @ui.lerp_color(lit, @ui.color(214, 204, 172, 255), (edge * 100.0).to_int(), 220) + ops.push(@ui.fill_rect(@ui.rect(cx + x, cy + dy, 1, 1), @ui.with_alpha(tone, (a * 255.0).to_int()))) + } + } + } + } + ops.push(@ui.circle(cx, cy, r, @ui.with_alpha(t.palette.border, 160), filled=false)) + ops +} + +///| Phase name over illumination percent. +pub fn render_text( + size : @types.Size, + t : @theme.Tokens, + p : Double, +) -> Array[@types.DrawOp] { + let w = size.w.reinterpret_as_int() + let h = size.h.reinterpret_as_int() + let fs = t.font_size.reinterpret_as_int() + [ + @ui.text(w / 2, h / 2 - fs / 2 + 1, phase_name(p), fs - 2, t.palette.foreground, align=CENTER, bold=true), + @ui.text(w / 2, h / 2 + fs / 2 + 4, illumination(p).to_string() + "% lit", fs - 3, t.palette.foreground_muted, align=CENTER), + ] +} + +///| +test "known dates" { + // New moon 2000-01-06, full moon 2000-01-21, new moon 2024-01-11. + assert_true(phase(2000, 1, 6) < 0.05 || phase(2000, 1, 6) > 0.95) + assert_eq(phase_name(phase(2000, 1, 21)), "Full Moon") + assert_eq(illumination(phase(2024, 1, 11)) < 5, true) + assert_eq(julian_day(2000, 1, 1), 2451545) +} + +///| +test "illumination extremes" { + assert_eq(illumination(0.0), 0) + assert_eq(illumination(0.5), 100) + assert_eq(illumination(0.25), 50) +} diff --git a/lib/moon/moon.pkg b/lib/moon/moon.pkg new file mode 100644 index 0000000..fb2c30a --- /dev/null +++ b/lib/moon/moon.pkg @@ -0,0 +1,6 @@ +import { + "moonbitlang/core/math" @math, + "moonplasma/desktop/interface/moonplasma/desktop/types" @types, + "moonplasma/desktop/interface/moonplasma/desktop/theme" @theme, + "moonplasma/desktop/lib/ui" @ui, +} diff --git a/lib/moon/pkg.generated.mbti b/lib/moon/pkg.generated.mbti new file mode 100644 index 0000000..9492b81 --- /dev/null +++ b/lib/moon/pkg.generated.mbti @@ -0,0 +1,32 @@ +// Generated using `moon info`, DON'T EDIT IT +package "moonplasma/desktop/lib/moon" + +import { + "moonplasma/desktop/interface/moonplasma/desktop/theme", + "moonplasma/desktop/interface/moonplasma/desktop/types", +} + +// Values +pub fn disc_info() -> (String, String, Int32, Int32, Int32) + +pub fn illumination(Double) -> Int32 + +pub fn julian_day(Int32, Int32, Int32) -> Int32 + +pub fn phase(Int32, Int32, Int32) -> Double + +pub fn phase_name(Double) -> String + +pub fn render_disc(@types.Size, @theme.Tokens, Double) -> Array[@types.DrawOp] + +pub fn render_text(@types.Size, @theme.Tokens, Double) -> Array[@types.DrawOp] + +pub fn text_info() -> (String, String, Int32, Int32, Int32) + +// Errors + +// Types and methods + +// Type aliases + +// Traits diff --git a/lib/timefmt/pkg.generated.mbti b/lib/timefmt/pkg.generated.mbti index 6eab8f3..35ad6c8 100644 --- a/lib/timefmt/pkg.generated.mbti +++ b/lib/timefmt/pkg.generated.mbti @@ -8,6 +8,8 @@ pub fn date_line(Int32, Int32, Int32) -> String pub fn hhmm(Int32, Int32) -> String +pub fn hhmm12(Int32, Int32) -> String + pub fn hhmmss(Int32, Int32, Int32) -> String pub fn month_short(Int32) -> String diff --git a/lib/wm/pkg.generated.mbti b/lib/wm/pkg.generated.mbti index a112657..241e088 100644 --- a/lib/wm/pkg.generated.mbti +++ b/lib/wm/pkg.generated.mbti @@ -8,7 +8,9 @@ import { // Values pub fn clamp_int(Int32, Int32, Int32) -> Int32 -pub fn compute_bsp_rects(BspNode, Rect, Int32) -> Array[(UInt64, Rect)] +pub fn compute_bsp_rects(BspNode, Rect, Int32, vgap? : Int32) -> Array[(UInt64, Rect)] + +pub fn compute_split_handles(BspNode, Rect, Int32, Int32) -> Array[SplitHandle] pub fn compute_work_area(Rect, excl_top? : Int32, excl_right? : Int32, excl_bottom? : Int32, excl_left? : Int32) -> Rect @@ -76,6 +78,13 @@ pub(all) struct Size { h : Int32 } +pub(all) struct SplitHandle { + path : Array[Bool] + horizontal : Bool + rect : Rect + area : Rect +} + pub(all) struct WindowRecord { id : UInt64 app_id : String @@ -131,6 +140,7 @@ pub(all) struct WmState { mut drag : DragSession? } pub fn WmState::close_window(Self, UInt64, Rect) -> Array[WmAction] +pub fn WmState::drag_split(Self, SplitHandle, Int32, Int32, Rect) -> Array[WmAction] pub fn WmState::end_drag(Self) -> Unit pub fn WmState::handle_request(Self, UInt64, WindowRequest, Rect) -> Array[WmAction] pub fn WmState::hit_test(Self, Int32, Int32, Rect?) -> InputHit @@ -138,6 +148,7 @@ pub fn WmState::new(inner_gap? : Int32, outer_gap? : Int32, titlebar_h? : Int32, pub fn WmState::open_window(Self, WindowRecord, Rect) -> Array[WmAction] pub fn WmState::relayout(Self, UInt32, Rect) -> Array[WmAction] pub fn WmState::set_layout_mode(Self, LayoutMode, Rect) -> Array[WmAction] +pub fn WmState::split_handles(Self, Rect) -> Array[SplitHandle] pub fn WmState::stacking_order(Self) -> Array[UInt64] pub fn WmState::start_drag(Self, UInt64, DragMode, Int32, Int32) -> Bool pub fn WmState::sync_windows(Self, Rect, Array[WindowRecord]) -> Array[WmAction] diff --git a/lib/wm/wm.mbt b/lib/wm/wm.mbt index 2f07657..39e92ee 100644 --- a/lib/wm/wm.mbt +++ b/lib/wm/wm.mbt @@ -457,8 +457,10 @@ pub fn WmState::relayout( w: if rect.w < min_w { min_w } else { rect.w }, h: if rect.h < min_h { min_h } else { rect.h }, } - win.geometry = clamped - actions.push(SetGeometry(id, clamped)) + // A maximized tiled window covers the whole padded work area. + let g = if win.maximized { padded } else { clamped } + win.geometry = g + actions.push(SetGeometry(id, g)) } None => () } @@ -801,6 +803,18 @@ pub fn WmState::stacking_order(self : WmState) -> Array[UInt64] { } collect_tree(ws.tree, order, ws.fullscreen, self.windows) + // Maximized tiled windows are drawn above their neighbours. + let below : Array[UInt64] = [] + let above : Array[UInt64] = [] + for id in order { + match self.windows.get(id) { + Some(w) => if w.maximized { above.push(id) } else { below.push(id) } + None => below.push(id) + } + } + order.clear() + order.append(below) + order.append(above) for id in ws.floating { if ws.fullscreen != Some(id) { match self.windows.get(id) { diff --git a/pixi.lock b/pixi.lock new file mode 100644 index 0000000..fddddae --- /dev/null +++ b/pixi.lock @@ -0,0 +1,75 @@ +version: 7 +platforms: +- name: linux-64 + virtual-packages: + - __unix=0=0 + - __linux=4.18 + - __glibc=2.28 + - __archspec=0=x86_64 +environments: + default: + channels: + - url: https://prefix.dev/scns/ + - url: https://conda.anaconda.org/conda-forge/ + packages: + linux-64: + - conda: https://conda.anaconda.org/conda-forge/linux-64/just-0.10.4-habb4d0f_0.tar.bz2 + - conda: https://prefix.dev/scns/linux-64/_libgcc_mutex-0.1-scns_forge.tar.bz2 + - conda: https://prefix.dev/scns/linux-64/_openmp_mutex-4.5-2_gnu.tar.bz2 + - conda: https://prefix.dev/scns/linux-64/libgcc-ng-11.2.0-h5593d30_1000.tar.bz2 + - conda: https://prefix.dev/scns/linux-64/libgomp-11.2.0-h5593d30_1000.tar.bz2 + - conda: https://prefix.dev/scns/linux-64/tinycc-0.9.27-pl5321h57f0786_0.conda +packages: +- conda: https://conda.anaconda.org/conda-forge/linux-64/just-0.10.4-habb4d0f_0.tar.bz2 + sha256: 2da7d79edbe5aac86b731c8b5bea9760bd334a87a2d8117959de7a7a46b5d1fc + md5: b3f069cfa06ea8ffa874d49621ad5b6d + depends: + - libgcc-ng >=9.4.0 + license: CC0-1.0 + run_exports: {} + size: 1078485 + timestamp: 1638124980753 +- conda: https://prefix.dev/scns/linux-64/_libgcc_mutex-0.1-scns_forge.tar.bz2 + sha256: 15caf304cf0d222cdc9c6f8145e3cb5e00106363d041805ff0777c1811baf28a + license: None + size: 4427 + timestamp: 1676009793381 +- conda: https://prefix.dev/scns/linux-64/_openmp_mutex-4.5-2_gnu.tar.bz2 + build_number: 1000 + sha256: cd1bc9bdac74d348a5ae562e0a1a260084530fcf50cfbde11f0e366876c01496 + depends: + - __glibc >=2.17,<3.0.a0 + - _libgcc_mutex 0.1 scns_forge + - libgomp >=7.5.0 + constrains: + - openmp_impl 9999 + license: BSD-3-Clause + size: 6060792 + timestamp: 1710847729439 +- conda: https://prefix.dev/scns/linux-64/libgcc-ng-11.2.0-h5593d30_1000.tar.bz2 + sha256: 73093301e58054319b0416c947fd31541ae9c3c474d3b0561c9b843a4eccbcb0 + depends: + - _libgcc_mutex 0.1 scns_forge + - _openmp_mutex >=4.5 + constrains: + - libgomp 11.2.0 h5593d30_1000 + license: GPL-3.0-only WITH GCC-exception-3.1 + size: 6957156 + timestamp: 1710847747666 +- conda: https://prefix.dev/scns/linux-64/libgomp-11.2.0-h5593d30_1000.tar.bz2 + sha256: 7d874391201845c730d4f37cc8bf5c478c302d9beec73cfacc4896f919593acc + depends: + - _libgcc_mutex 0.1 scns_forge + license: GPL-3.0-only WITH GCC-exception-3.1 + size: 6488970 + timestamp: 1710847698293 +- conda: https://prefix.dev/scns/linux-64/tinycc-0.9.27-pl5321h57f0786_0.conda + sha256: 41ed2a42c53e369870e24691b4515a0067ab4f9986928327b1cd17a71af38774 + md5: c5c9a3716649df5e1b52a6cb438b2d84 + depends: + - __glibc >=2.17,<3.0.a0 + - libgcc-ng >=11 + license: LGPL-2.1-or-later + run_exports: {} + size: 2932996 + timestamp: 1785949887223 diff --git a/pixi.toml b/pixi.toml new file mode 100644 index 0000000..168d4b6 --- /dev/null +++ b/pixi.toml @@ -0,0 +1,8 @@ +[workspace] +name = "moon-plasma" +channels = ["https://prefix.dev/scns", "conda-forge"] +platforms = ["linux-64"] + +[dependencies] +just = "*" +tinycc = "*" diff --git a/scripts/build-modules.sh b/scripts/build-modules.sh new file mode 100755 index 0000000..76b7ec8 --- /dev/null +++ b/scripts/build-modules.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Build the panel's wasm modules (every *-widget component in scripts/components.txt) +# into build/components/.wasm, the directory the compositor loads its panel from. +# Same steps as scripts/build.sh minus the jco/JS-host transpile, so it needs only +# moon and wasm-tools. +# scripts/build-modules.sh [name ...] +set -euo pipefail +ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT" +export PATH="$ROOT/.tools/bin:$HOME/.moon/bin:$PATH" +for t in moon wasm-tools; do + command -v "$t" >/dev/null || { echo "error: $t not found" >&2; exit 1; } +done +want=("$@") +mkdir -p build/components +moon build --target wasm --release 2>&1 | grep -E '^Error' -A8 || true +[ "${PIPESTATUS[0]}" -eq 0 ] || { echo "error: moon build failed" >&2; exit 1; } +n=0 +while read -r name world; do + case "$name" in ''|'#'*) continue;; esac + case "$world" in *-widget) ;; *) continue;; esac + if [ ${#want[@]} -gt 0 ] && [[ ! " ${want[*]} " =~ " $name " ]]; then continue; fi + core="_build/wasm/release/build/components/$name/gen/gen.wasm" + [ -f "$core" ] || { echo "error: $core missing" >&2; exit 1; } + out="build/components/$name.wasm" + wasm-tools component embed wit "$core" --world "$world" --encoding utf16 -o "build/components/$name.embed.wasm" + wasm-tools component new "build/components/$name.embed.wasm" -o "$out" + rm -f "build/components/$name.embed.wasm" + wasm-tools validate --features component-model "$out" + wasm-tools component targets --world "$world" wit "$out" >/dev/null + imports="$(wasm-tools component wit "$out" | sed -n 's/^ import moonplasma:desktop\/\([a-z-]*\)@.*;/\1/p' | grep -v '^types$' | sort | paste -sd, - || true)" + exports="$(wasm-tools component wit "$out" | sed -n 's/^ export moonplasma:desktop\/\([a-z-]*\)@.*;/\1/p' | sort | paste -sd, -)" + printf '{"name":"%s","world":"%s","imports":[%s],"exports":[%s]}\n' "$name" "$world" \ + "$(echo "$imports" | sed 's/\([a-z-]\+\)/"\1"/g')" "$(echo "$exports" | sed 's/\([a-z-]\+\)/"\1"/g')" \ + > "build/components/$name.meta.json" + printf ' %-16s %-22s %7s bytes imports=[%s]\n' "$name" "$world" "$(stat -c %s "$out")" "$imports" + n=$((n + 1)) +done < scripts/components.txt +echo "built $n module(s) into build/components/" diff --git a/scripts/components.txt b/scripts/components.txt index 08cedf9..688272a 100644 --- a/scripts/components.txt +++ b/scripts/components.txt @@ -3,3 +3,11 @@ clock-digital clock-widget clock-binary clock-widget launcher launcher-widget shell shell +pulse pulse-widget +clock-digital12 clock-widget +moon-disc clock-widget +moon-text clock-widget +tasks taskbar-widget +layout layout-widget +inspector inspector-widget +module-manager module-manager-widget diff --git a/scripts/tcc/tcc b/scripts/tcc/tcc index faa0596..604fa50 100755 --- a/scripts/tcc/tcc +++ b/scripts/tcc/tcc @@ -11,4 +11,10 @@ args=() for a in "$@"; do [ "$a" = "-DMOONBIT_NATIVE_NO_SYS_HEADER" ] || args+=("$a") done +# tcc does not link libm by default; the font rasteriser needs it. Add it on link steps only. +link=1 +for a in "${args[@]}"; do + case "$a" in -c|-ar) link=0 ;; esac +done +if [ "$link" = 1 ]; then args+=(-lm); fi exec "$tcc" "${args[@]}" diff --git a/scripts/test.sh b/scripts/test.sh index 4b418e7..64f4d6e 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -36,5 +36,6 @@ step "host integration tests (jco + Node)" (cd host && npm test) step "pure-MoonBit native Wayland compositor + wasi-gfx + e2e tests (compositor/)" -moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/host +XDG_CONFIG_HOME="$(mktemp -d)" MOON_PLASMA_TEST_CONFIG=1 \ + moon test --target native --warn-list -a compositor/renderer compositor/gfx compositor/wasm compositor/host moon build --target native --warn-list -a compositor/bin diff --git a/session/install.py b/session/install.py index 5197784..56ab548 100755 --- a/session/install.py +++ b/session/install.py @@ -8,6 +8,7 @@ Installs: /usr/local/bin/moon-plasma release compositor binary /usr/local/bin/moon-plasma-session session launcher /usr/local/share/moon-plasma/{config,wit}/ files the compositor reads at runtime + /usr/local/share/moon-plasma/modules/*.wasm the panel's wasm modules (build them first: just modules) /usr/share/wayland-sessions/moon-plasma.desktop display-manager entry """ import os, shutil, sys @@ -53,4 +54,17 @@ for d in ("config", "wit"): os.makedirs(share, exist_ok=True) shutil.copytree(os.path.join(root, d), dst) print("installed", dst) +mods = os.path.join(root, "build/components") +dst = os.path.join(share, "modules") +if os.path.isdir(dst): + shutil.rmtree(dst) +os.makedirs(dst, exist_ok=True) +n = 0 +for f in sorted(os.listdir(mods)) if os.path.isdir(mods) else []: + if f.endswith(".wasm"): + shutil.copyfile(os.path.join(mods, f), os.path.join(dst, f)) + n += 1 +if n == 0: + sys.exit("no modules in build/components - run `just modules` first") +print("installed", n, "modules in", dst) print("done: pick 'Moon Plasma' in the session menu of your login screen") diff --git a/wit/capabilities.wit b/wit/capabilities.wit index e3695c5..038ab32 100644 --- a/wit/capabilities.wit +++ b/wit/capabilities.wit @@ -19,3 +19,94 @@ interface app-launch { /// Ask the host to start an application by catalog id. launch: func(id: string) -> result<_, string>; } + +/// Live machine state, sampled by the host about once a second. The widget never +/// opens /proc or /sys itself: it can only see what this interface hands it, and +/// the host can serve it from anything (Linux /proc, a mock, a remote machine). +interface system { + record snapshot { + /// Busy CPU time since the previous sample, 0..1000. + cpu-permille: u32, + mem-used-kib: u64, + mem-total-kib: u64, + /// 0..100, or -1 when the machine has no battery. + battery-percent: s32, + charging: bool, + uptime-secs: u64, + net-rx-bytes-per-sec: u64, + net-tx-bytes-per-sec: u64, + /// 1-minute load average x 100. + load-centi: u32, + } + read: func() -> snapshot; +} + + +/// The window list, as shown by a task bar. `id` is an opaque host handle. +interface windows { + record window-info { + id: u32, + title: string, + /// 1 when the window has keyboard focus. + focused: u32, + /// 1 when the window is minimized (it stays listed so it can be restored). + minimized: u32, + } + list-windows: func() -> list; + /// Focus, raise (and un-minimize) a window. + focus-window: func(id: u32); + + /// Richer, id-stable view for widgets that show more than a task bar (the Pulse widget). + record window-detail { + id: u64, + title: string, + app-id: string, + focused: bool, + } + all: func() -> list; + /// Raise and focus a window (restoring it if minimized). + focus: func(id: u64); + +} + +/// The window manager's layout mode (tiling / monocle / floating). +interface layout-control { + /// Display names, indexed by mode. + layout-modes: func() -> list; + current-layout: func() -> u32; + set-layout: func(mode: u32); +} + +/// The Interface Explorer: hover any system component to see its WIT. +interface inspector { + is-on: func() -> bool; + set-on: func(on: bool); +} + +/// Hot-swap of the system's own wasm modules. A module with this capability +/// is a module manager: it decides what is loaded into the panel. +interface modules { + /// A loadable module found on the module search path. + record module-info { + /// File stem, e.g. "clock-digital". + id: string, + name: string, + path: string, + /// How many instances are loaded in the panel right now. + loaded: u32, + } + /// A module instance currently loaded in the panel, in panel order. + record instance-info { + slot: string, + module: string, + name: string, + } + available: func() -> list; + loaded: func() -> list; + /// Load the module file at `path` into the panel (any number of instances). + load-module: func(path: string); + /// Unload one loaded instance, freeing its panel space. + unload-instance: func(slot: string); + /// Ask the host to show its native file chooser for a .wasm elsewhere on disk. + browse: func(); +} diff --git a/wit/worlds.wit b/wit/worlds.wit index e303e2c..6136ce3 100644 --- a/wit/worlds.wit +++ b/wit/worlds.wit @@ -28,3 +28,34 @@ world shell { export desktop-surface; export panel-layout; } + +/// Desktop Pulse: reads machine state and the window list, and can raise a window. +world pulse-widget { + include widget; + import system; + import windows; +} + +/// Panel task list: needs the window list. +world taskbar-widget { + include widget; + import windows; +} + +/// Layout switcher. +world layout-widget { + include widget; + import layout-control; +} + +/// Interface Explorer toggle. +world inspector-widget { + include widget; + import inspector; +} + +/// Loads and unloads the system's wasm modules; the wasm picker opens this app. +world module-manager-widget { + include widget; + import modules; +}