mobilegles

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mobilegles

The renderer behind MeUI: an SDL3 + OpenGL batch renderer for shapes, text and images, with a software fallback for headless rendering.

It is a pure-Go module. Calls into SDL3 and OpenGL go through purego, so the desktop build works with CGO_ENABLED=0; cgo is only needed for the mobile cross-builds.

import "github.com/sixnineone/mobilegles"

resources/fonts/ holds the embedded Roboto faces (Apache 2.0). The shaders are in shaders/. cmd/ contains the renderer's own probes and a demo.

Build

CGO_ENABLED=0 go build ./...
CGO_ENABLED=0 go test ./...

Licence

MIT — see LICENSE. Roboto is Apache 2.0 (see LICENSES/Apache-2.0.txt); other dependency notices are in LICENSES/.

Documentation

Overview

Package mobilegles provides an OpenGL ES 2.0 backend for MeUi using purego.

Package mobilegles provides an OpenGL ES 2.0/3.0 backend for MeUi using purego. This enables mobile platform support without CGO dependencies.

FFI: purego is the binding layer today, but the planned replacement is pureffi (purego's API on go-webgpu/goffi) - architecture decision D7 in meui-migration/design/meui-platform-architecture.md, with the measured trial in MIGRATION.md P6a/P6b. Two consequences for anyone touching this package:

  • pureffi works only under CGO_ENABLED=0, and the race detector needs CGO_ENABLED=1; that is why the switch is deferred rather than done; and
  • do not add a cgo dependency to this module (or to meui) without checking D7 - a third-party cgo package in the graph is what forces that mode.

purego already needs CGO_ENABLED=1 on Android and iOS, and has no Windows Dlopen/Dlsym; that gap is what D7 plans to close.

Index

Constants

View Source
const (
	EGL_DEFAULT_DISPLAY         = 0
	EGL_PLATFORM_X11_KHR        = 0x31D6
	EGL_PLATFORM_X11_SCREEN_EXT = 0x31D6
	EGL_OPENGL_ES_API           = 0x30A0
	EGL_OPENGL_ES2_BIT          = 4
	EGL_WINDOW_BIT              = 4
	EGL_RENDERABLE_TYPE         = 0x3040
	EGL_SURFACE_TYPE            = 0x3033
	EGL_RED_SIZE                = 0x3021
	EGL_GREEN_SIZE              = 0x3022
	EGL_BLUE_SIZE               = 0x3023
	EGL_ALPHA_SIZE              = 0x3024
	EGL_DEPTH_SIZE              = 0x3025
	EGL_NONE                    = 0x3038
	EGL_CONTEXT_CLIENT_VERSION  = 0x3098
	EGL_SUCCESS                 = 0x3000
)
View Source
const (
	GL_VERTEX_SHADER          = 0x8B31
	GL_FRAGMENT_SHADER        = 0x8B30
	GL_TRIANGLES              = 0x0004
	GL_FLOAT                  = 0x1406
	GL_ARRAY_BUFFER           = 0x8892
	GL_ELEMENT_ARRAY_BUFFER   = 0x8893
	GL_UNSIGNED_INT           = 0x1405
	GL_STATIC_DRAW            = 0x88E4
	GL_STREAM_DRAW            = 0x88E0
	GL_COLOR_BUFFER_BIT       = 0x00004000
	GL_SCISSOR_TEST           = 0x0C11
	GL_TEXTURE_2D             = 0x0DE1
	GL_ALPHA                  = 0x1906
	GL_RGBA                   = 0x1908
	GL_UNSIGNED_BYTE          = 0x1401
	GL_LINEAR                 = 0x2601
	GL_LINEAR_MIPMAP_LINEAR   = 0x2703
	GL_CLAMP_TO_EDGE          = 0x812F
	GL_TEXTURE_MIN_FILTER     = 0x2801
	GL_TEXTURE_MAG_FILTER     = 0x2800
	GL_TEXTURE_WRAP_S         = 0x2802
	GL_TEXTURE_WRAP_T         = 0x2803
	GL_DEPTH_TEST             = 0x0B71
	GL_DEPTH_BUFFER_BIT       = 0x00000100
	GL_STENCIL_TEST           = 0x0B90
	GL_STENCIL_BUFFER_BIT     = 0x00000400
	GL_ALWAYS                 = 0x0207
	GL_NOTEQUAL               = 0x0205
	GL_KEEP                   = 0x1E00
	GL_INCR                   = 0x1E02
	GL_LEQUAL                 = 0x0203
	GL_BLEND                  = 0x0BE2
	GL_SRC_ALPHA              = 0x0302
	GL_ONE_MINUS_SRC_ALPHA    = 0x0303
	GL_ONE_MINUS_SRC_COLOR    = 0x0301
	GL_ZERO                   = 0x0000
	GL_SRC_COLOR              = 0x0300
	GL_DST_COLOR              = 0x0306
	GL_ONE                    = 0x0001
	GL_FRAMEBUFFER            = 0x8D40
	GL_COLOR_ATTACHMENT0      = 0x8CE0
	GL_FRAMEBUFFER_COMPLETE   = 0x8CD5
	GL_TIME_ELAPSED           = 0x88BF
	GL_QUERY_RESULT           = 0x8866
	GL_QUERY_RESULT_AVAILABLE = 0x8867
)
View Source
const (
	SDL_HITTEST_NORMAL         uint32 = 0
	SDL_HITTEST_DRAGGABLE      uint32 = 1
	SDL_HITTEST_RESIZE_TOPLEFT uint32 = 2
	// …through SDL_HITTEST_RESIZE_LEFT = 9
	SDL_HITTEST_RESIZE_LEFT uint32 = 9
)

SDL_HitTestResult values (SDL_video.h).

View Source
const (
	EdgeNone  uint32 = 0
	EdgeTop   uint32 = 1 << 0
	EdgeBot   uint32 = 1 << 1
	EdgeLeft  uint32 = 1 << 2
	EdgeRight uint32 = 1 << 3
)

Edge zone masks (window-relative resize borders).

View Source
const (
	// SDL_INIT_VIDEO from SDL3 SDL_init.h (0x20 — 0x2 is not a valid
	// SDL3 subsystem flag; it only "worked" because SDL3 initializes
	// video on demand at window creation).
	SDL3_INIT_VIDEO uint64 = 0x00000020

	// SDL3 window flags — VERIFIED against /usr/include/SDL3/SDL_video.h
	// (SDL2's values differ: 0x4 is OCCLUDED, 0x10 is BORDERLESS!)
	SDL3_WINDOW_OPENGL     uint64 = 0x00000002
	SDL3_WINDOW_OCCLUDED   uint64 = 0x00000004
	SDL3_WINDOW_HIDDEN     uint64 = 0x00000008
	SDL3_WINDOW_BORDERLESS uint64 = 0x00000010
	SDL3_WINDOW_RESIZABLE  uint64 = 0x00000020
	// SDL_WINDOW_TRANSPARENT (SDL_video.h 0x40000000): window with a
	// transparent buffer — required for rounded window corners on
	// X11/XWayland (compositor needed).
	SDL3_WINDOW_TRANSPARENT uint64 = 0x40000000

	// SDL3 event type enum (SDL_EventType) — values verified against
	// /usr/include/SDL3/SDL_events.h. Sequential enums are written out
	// explicitly; NOTE: window events start at 0x202 and keyboard text
	// events differ from SDL2 (TEXT_INPUT=0x303 here, 0x303 was
	// SDL2's TEXT_EDITING-adjacent numbering).
	SDL3_EVENT_QUIT uint32 = 0x100

	// Window events (SDL_EVENT_WINDOW_*)
	SDL3_EVENT_WINDOW_SHOWN                 uint32 = 0x202
	SDL3_EVENT_WINDOW_HIDDEN                uint32 = 0x203
	SDL3_EVENT_WINDOW_EXPOSED               uint32 = 0x204
	SDL3_EVENT_WINDOW_MOVED                 uint32 = 0x205
	SDL3_EVENT_WINDOW_RESIZED               uint32 = 0x206
	SDL3_EVENT_WINDOW_PIXEL_SIZE_CHANGED    uint32 = 0x207
	SDL3_EVENT_WINDOW_METAL_VIEW_RESIZED    uint32 = 0x208
	SDL3_EVENT_WINDOW_MINIMIZED             uint32 = 0x209
	SDL3_EVENT_WINDOW_MAXIMIZED             uint32 = 0x20A
	SDL3_EVENT_WINDOW_RESTORED              uint32 = 0x20B
	SDL3_EVENT_WINDOW_MOUSE_ENTER           uint32 = 0x20C
	SDL3_EVENT_WINDOW_MOUSE_LEAVE           uint32 = 0x20D
	SDL3_EVENT_WINDOW_FOCUS_GAINED          uint32 = 0x20E
	SDL3_EVENT_WINDOW_FOCUS_LOST            uint32 = 0x20F
	SDL3_EVENT_WINDOW_CLOSE_REQUESTED       uint32 = 0x210
	SDL3_EVENT_WINDOW_HIT_TEST              uint32 = 0x211
	SDL3_EVENT_WINDOW_ICCPROF_CHANGED       uint32 = 0x212
	SDL3_EVENT_WINDOW_DISPLAY_CHANGED       uint32 = 0x213
	SDL3_EVENT_WINDOW_DISPLAY_SCALE_CHANGED uint32 = 0x214
	SDL3_EVENT_WINDOW_SAFE_AREA_CHANGED     uint32 = 0x215
	SDL3_EVENT_WINDOW_OCCLUDED              uint32 = 0x216
	SDL3_EVENT_WINDOW_ENTER_FULLSCREEN      uint32 = 0x217
	SDL3_EVENT_WINDOW_LEAVE_FULLSCREEN      uint32 = 0x218
	SDL3_EVENT_WINDOW_DESTROYED             uint32 = 0x219
	SDL3_EVENT_WINDOW_HDR_STATE_CHANGED     uint32 = 0x21A

	// Keyboard events (SDL_EVENT_KEY_*, SDL_EVENT_TEXT_*)
	SDL3_EVENT_KEY_DOWN                uint32 = 0x300
	SDL3_EVENT_KEY_UP                  uint32 = 0x301
	SDL3_EVENT_TEXT_EDITING            uint32 = 0x302 // IME composition in progress
	SDL3_EVENT_TEXT_INPUT              uint32 = 0x303 // committed text
	SDL3_EVENT_KEYMAP_CHANGED          uint32 = 0x304
	SDL3_EVENT_KEYBOARD_ADDED          uint32 = 0x305
	SDL3_EVENT_KEYBOARD_REMOVED        uint32 = 0x306
	SDL3_EVENT_TEXT_EDITING_CANDIDATES uint32 = 0x307
	SDL3_EVENT_SCREEN_KEYBOARD_SHOWN   uint32 = 0x308
	SDL3_EVENT_SCREEN_KEYBOARD_HIDDEN  uint32 = 0x309

	// Mouse events (SDL_EVENT_MOUSE_*)
	SDL3_EVENT_MOUSE_MOTION      uint32 = 0x400
	SDL3_EVENT_MOUSE_BUTTON_DOWN uint32 = 0x401
	SDL3_EVENT_MOUSE_BUTTON_UP   uint32 = 0x402
	SDL3_EVENT_MOUSE_WHEEL       uint32 = 0x403
	SDL3_EVENT_MOUSE_ADDED       uint32 = 0x404
	SDL3_EVENT_MOUSE_REMOVED     uint32 = 0x405

	// Joystick events (SDL_EVENT_JOYSTICK_*)
	SDL3_EVENT_JOYSTICK_AXIS        uint32 = 0x600
	SDL3_EVENT_JOYSTICK_BALL        uint32 = 0x601
	SDL3_EVENT_JOYSTICK_HAT         uint32 = 0x602
	SDL3_EVENT_JOYSTICK_BUTTON_DOWN uint32 = 0x603
	SDL3_EVENT_JOYSTICK_BUTTON_UP   uint32 = 0x604

	// Touch events (SDL_EVENT_FINGER_*)
	SDL3_EVENT_FINGER_DOWN     uint32 = 0x700
	SDL3_EVENT_FINGER_UP       uint32 = 0x701
	SDL3_EVENT_FINGER_MOTION   uint32 = 0x702
	SDL3_EVENT_FINGER_CANCELED uint32 = 0x703

	// Drop events (SDL_EVENT_DROP_*)
	SDL3_EVENT_DROP_FILE     uint32 = 0x1000
	SDL3_EVENT_DROP_TEXT     uint32 = 0x1001
	SDL3_EVENT_DROP_BEGIN    uint32 = 0x1002
	SDL3_EVENT_DROP_COMPLETE uint32 = 0x1003
	SDL3_EVENT_DROP_POSITION uint32 = 0x1004

	// SDL_EVENT_SENSOR_UPDATE (SDL_events.h). Sensors are NOT window events:
	// the pump hands them to the handler installed with SetSensorHandler
	// instead of routing them to a window.
	SDL3_EVENT_SENSOR_UPDATE uint32 = 0x1200

	// SDL3 SDL_GLAttr enum values (VERIFIED against SDL3 headers —
	// SDL2-era guesses silently set GREEN_SIZE/BLUE_SIZE instead!).
	SDL3_GL_CONTEXT_MAJOR_VERSION uint32 = 17
	SDL3_GL_CONTEXT_MINOR_VERSION uint32 = 18
	SDL3_GL_CONTEXT_PROFILE_MASK  uint32 = 20 // SDL_GL_CONTEXT_PROFILE_MASK

	// SDL_GLprofile (SDL_video.h): the value for SDL_GL_CONTEXT_PROFILE_MASK.
	// Android has OpenGL ES only, so it must ask for the ES profile; the
	// desktop path leaves the default (desktop GL). int32 because that is the
	// value type SDL_GL_SetAttribute takes (the attr itself is uint32).
	SDL3_GL_CONTEXT_PROFILE_ES int32 = 0x0004

	// SDL_WINDOW_FULLSCREEN (SDL_video.h). On Android the surface belongs to
	// the activity and SDL's video driver owns the geometry, so the desktop
	// BORDERLESS/RESIZABLE pair is meaningless there.
	SDL3_WINDOW_FULLSCREEN uint64 = 0x0000000000000001

	// SDL_GL attribute names (SDL_GL_Attr enum values)
	SDL3_GL_MULTISAMPLEBUFFERS uint32 = 0xD
	SDL3_GL_MULTISAMPLESAMPLES uint32 = 0xE
)
View Source
const (
	SDL3_KMOD_LSHIFT uint16 = 0x001
	SDL3_KMOD_RSHIFT uint16 = 0x002
	SDL3_KMOD_LCTRL  uint16 = 0x040
	SDL3_KMOD_RCTRL  uint16 = 0x080
	SDL3_KMOD_LALT   uint16 = 0x100
	SDL3_KMOD_RALT   uint16 = 0x200
	SDL3_KMOD_LGUI   uint16 = 0x400
	SDL3_KMOD_RGUI   uint16 = 0x800
	// The LOCKS. Not held-key modifiers: CapsLock stays on until pressed again, and NumLock decides
	// whether the keypad's 1 is a '1' or an End. They are separate bits in SDL3's SDL_Keymod and they
	// were missing here, so a keypad key could not be interpreted at all.
	SDL3_KMOD_NUM    uint16 = 0x1000
	SDL3_KMOD_CAPS   uint16 = 0x2000
	SDL3_KMOD_SCROLL uint16 = 0x4000
)

SDL3 SDL_Keymod bit values.

View Source
const (
	SDL3_SCANCODE_A            int32 = 4
	SDL3_SCANCODE_B            int32 = 5
	SDL3_SCANCODE_C            int32 = 6
	SDL3_SCANCODE_D            int32 = 7
	SDL3_SCANCODE_E            int32 = 8
	SDL3_SCANCODE_F            int32 = 9
	SDL3_SCANCODE_G            int32 = 10
	SDL3_SCANCODE_H            int32 = 11
	SDL3_SCANCODE_I            int32 = 12
	SDL3_SCANCODE_J            int32 = 13
	SDL3_SCANCODE_K            int32 = 14
	SDL3_SCANCODE_L            int32 = 15
	SDL3_SCANCODE_M            int32 = 16
	SDL3_SCANCODE_N            int32 = 17
	SDL3_SCANCODE_O            int32 = 18
	SDL3_SCANCODE_P            int32 = 19
	SDL3_SCANCODE_Q            int32 = 20
	SDL3_SCANCODE_R            int32 = 21
	SDL3_SCANCODE_S            int32 = 22
	SDL3_SCANCODE_T            int32 = 23
	SDL3_SCANCODE_U            int32 = 24
	SDL3_SCANCODE_V            int32 = 25
	SDL3_SCANCODE_W            int32 = 26
	SDL3_SCANCODE_X            int32 = 27
	SDL3_SCANCODE_Y            int32 = 28
	SDL3_SCANCODE_Z            int32 = 29
	SDL3_SCANCODE_0            int32 = 39
	SDL3_SCANCODE_1            int32 = 30
	SDL3_SCANCODE_2            int32 = 31
	SDL3_SCANCODE_3            int32 = 32
	SDL3_SCANCODE_4            int32 = 33
	SDL3_SCANCODE_5            int32 = 34
	SDL3_SCANCODE_6            int32 = 35
	SDL3_SCANCODE_7            int32 = 36
	SDL3_SCANCODE_8            int32 = 37
	SDL3_SCANCODE_9            int32 = 38
	SDL3_SCANCODE_F1           int32 = 58
	SDL3_SCANCODE_F2           int32 = 59
	SDL3_SCANCODE_F3           int32 = 60
	SDL3_SCANCODE_F4           int32 = 61
	SDL3_SCANCODE_F5           int32 = 62
	SDL3_SCANCODE_F6           int32 = 63
	SDL3_SCANCODE_F7           int32 = 64
	SDL3_SCANCODE_F8           int32 = 65
	SDL3_SCANCODE_F9           int32 = 66
	SDL3_SCANCODE_F10          int32 = 67
	SDL3_SCANCODE_F11          int32 = 68
	SDL3_SCANCODE_F12          int32 = 69
	SDL3_SCANCODE_RETURN       int32 = 40
	SDL3_SCANCODE_ESCAPE       int32 = 41
	SDL3_SCANCODE_BACKSPACE    int32 = 42
	SDL3_SCANCODE_TAB          int32 = 43
	SDL3_SCANCODE_SPACE        int32 = 44
	SDL3_SCANCODE_MINUS        int32 = 45
	SDL3_SCANCODE_EQUAL        int32 = 46
	SDL3_SCANCODE_LEFTBRACKET  int32 = 47
	SDL3_SCANCODE_RIGHTBRACKET int32 = 48
	SDL3_SCANCODE_BACKSLASH    int32 = 49
	SDL3_SCANCODE_SEMICOLON    int32 = 51
	SDL3_SCANCODE_APOSTROPHE   int32 = 52
	SDL3_SCANCODE_GRAVE        int32 = 53
	SDL3_SCANCODE_COMMA        int32 = 54
	SDL3_SCANCODE_PERIOD       int32 = 55
	SDL3_SCANCODE_SLASH        int32 = 56
	SDL3_SCANCODE_UP           int32 = 82
	SDL3_SCANCODE_DOWN         int32 = 81
	SDL3_SCANCODE_LEFT         int32 = 80
	SDL3_SCANCODE_RIGHT        int32 = 79
	SDL3_SCANCODE_INSERT       int32 = 73
	SDL3_SCANCODE_HOME         int32 = 74
	SDL3_SCANCODE_PAGEUP       int32 = 75
	SDL3_SCANCODE_DELETE       int32 = 76
	SDL3_SCANCODE_END          int32 = 77
	SDL3_SCANCODE_PAGEDOWN     int32 = 78
	SDL3_SCANCODE_PAUSE        int32 = 72
	SDL3_SCANCODE_KP_1         int32 = 89
	SDL3_SCANCODE_KP_2         int32 = 90
	SDL3_SCANCODE_KP_3         int32 = 91
	SDL3_SCANCODE_KP_4         int32 = 92
	SDL3_SCANCODE_KP_5         int32 = 93
	SDL3_SCANCODE_KP_6         int32 = 94
	SDL3_SCANCODE_KP_7         int32 = 95
	SDL3_SCANCODE_KP_8         int32 = 96
	SDL3_SCANCODE_KP_9         int32 = 97
	SDL3_SCANCODE_KP_0         int32 = 98
	SDL3_SCANCODE_KP_PERIOD    int32 = 99
	SDL3_SCANCODE_KP_DIVIDE    int32 = 84
	SDL3_SCANCODE_KP_MULTIPLY  int32 = 85
	SDL3_SCANCODE_KP_MINUS     int32 = 86
	SDL3_SCANCODE_KP_PLUS      int32 = 87
	SDL3_SCANCODE_KP_ENTER     int32 = 88
	SDL3_SCANCODE_KP_EQUALS    int32 = 103
	SDL3_SCANCODE_KP_COMMA     int32 = 133
	SDL3_SCANCODE_LSHIFT       int32 = 225
	SDL3_SCANCODE_RSHIFT       int32 = 229
	SDL3_SCANCODE_LCTRL        int32 = 224
	SDL3_SCANCODE_RCTRL        int32 = 228
	SDL3_SCANCODE_LALT         int32 = 226
	SDL3_SCANCODE_RALT         int32 = 230
	SDL3_SCANCODE_LGUI         int32 = 227
	SDL3_SCANCODE_RGUI         int32 = 231
)

SDL3 SDL_Scancode values, GENERATED FROM THE INSTALLED HEADERS rather than typed by hand.

Every value here was printed by compiling against /usr/include/SDL3 and running the program, because a hand-typed scancode is exactly the sort of thing that is wrong by one and nobody notices. Regenerate with the probe in MIGRATION.md M47 after an SDL upgrade — a scancode that moves silently changes which key every shortcut in every app is bound to.

View Source
const (
	SDL_INIT_VIDEO               = 0x00000020
	SDL_WINDOW_OPENGL            = 0x00000002
	SDL_WINDOW_SHOWN             = 0x00000004
	SDL_KEYDOWN                  = 0x300
	SDL_KEYUP                    = 0x301
	SDL_MOUSEMOTION              = 0x400
	SDL_MOUSEBUTTONDOWN          = 0x401
	SDL_MOUSEBUTTONUP            = 0x402
	SDL_QUIT                     = 0x100
	SDL_WINDOWEVENT              = 0x200
	SDL_GL_CONTEXT_MAJOR_VERSION = 0x1
	SDL_GL_CONTEXT_MINOR_VERSION = 0x2
	SDL_GL_CONTEXT_PROFILE_MASK  = 0x3
	SDL_GL_CONTEXT_PROFILE_ES    = 0x2
)
View Source
const (
	ButtonLeft   = 1
	ButtonRight  = 2
	ButtonMiddle = 3
)

Mouse buttons

View Source
const (
	ModNone  KeyMod = 0
	ModShift KeyMod = 1 << 0
	ModCtrl  KeyMod = 1 << 1
	ModAlt   KeyMod = 1 << 2
	ModMeta  KeyMod = 1 << 3
	// The KEYPAD, named. The toolkit had NO keypad constants at all, so every keypad key arrived as a bare
	// scancode and no widget could bind one. These are the USB HID usage IDs, which is what SDL3 reports.
	// The keypad DIGITS agree between SDL3 and HID (89-99), which is why they passed through
	// correctly for years. The OPERATORS are not in SDL's scancode set at all, so their HID usages come
	// from the USB HID table — and the first version of these constants was written from memory and was
	// wrong for four of the six: `TestTheWholeKeyboardMapsToDistinctToolkitKeycodes` caught it as four
	// keys collapsing onto one, which is precisely the "the wrong character appeared" symptom.
	KeypadSlash    Keycode = 75  // 0x4B
	KeypadAsterisk Keycode = 85  // 0x55
	KeypadMinus    Keycode = 78  // 0x4E
	KeypadPlus     Keycode = 87  // 0x57
	KeypadEnter    Keycode = 88  // 0x58
	KeypadPercent  Keycode = 104 // 0x68
	KeypadDot      Keycode = 99
	Keypad0        Keycode = 98
	Keypad1        Keycode = 89
	Keypad2        Keycode = 90
	Keypad3        Keycode = 91
	Keypad4        Keycode = 92
	Keypad5        Keycode = 93
	Keypad6        Keycode = 94
	Keypad7        Keycode = 95
	Keypad8        Keycode = 96
	Keypad9        Keycode = 97
	KeypadEquals   Keycode = 103 // 0x67
	KeypadComma    Keycode = 126 // 0x7E

	// The PUNCTUATION of the main row. SDL3 and HID agree on all of them (47-56), so nothing has to be
	// remapped — they simply had no NAME, and a key the toolkit cannot name arrives as KeyUnknown,
	// which no widget can bind (and which is why Ctrl+/ , Ctrl+[ and Ctrl+\ were dead in the editor).
	// These are the USB HID usage IDs, which is what SDL3 reports.
	KeyOpenBracket  Keycode = 47 // [{
	KeyCloseBracket Keycode = 48 // ]}
	KeyBackslash    Keycode = 49 // \|
	KeySemicolon    Keycode = 51 // ;:
	KeyApostrophe   Keycode = 52 // '"
	KeyGrave        Keycode = 53 // `~
	KeyComma        Keycode = 54 // ,<
	KeyPeriod       Keycode = 55 // .>
	KeySlash        Keycode = 56 // /?
	KeyMinus        Keycode = 45 // -_
	KeyEqual        Keycode = 46 // =+

	// The NAVIGATION cluster, named. SDL3 numbers these 73-78 while USB HID numbers them in the 199-214
	// block, so they are the keys where the two schemes diverge — and where the bare pass-through
	// delivered a number that means nothing. A text box's Delete key was arriving as 76.
	KeyInsert   Keycode = 210
	KeyHome     Keycode = 199
	KeyPageUp   Keycode = 211
	KeyDelete   Keycode = 212
	KeyEnd      Keycode = 213
	KeyPageDown Keycode = 214
	KeyPause    Keycode = 215

	// The FUNCTION keys, named. HID F1-F12 are 58-69, which coincides with SDL3's numbering, so these were
	// never wrong — but they were unnamed, so a binding had to write a literal.
	KeyF1  Keycode = 58
	KeyF2  Keycode = 59
	KeyF3  Keycode = 60
	KeyF4  Keycode = 61
	KeyF5  Keycode = 62
	KeyF6  Keycode = 63
	KeyF7  Keycode = 64
	KeyF8  Keycode = 65
	KeyF9  Keycode = 66
	KeyF10 Keycode = 67
	KeyF11 Keycode = 68
	KeyF12 Keycode = 69

	// ModCaps, ModNum and ModScroll are LOCKS, not modifiers: they stay on while other keys are released.
	//
	// They are here because the keypad DEPENDS on them — keypad 1 is '1' with NumLock on and End with it
	// off — and a toolkit that cannot report the lock state cannot tell those two apart. ModCaps was
	// declared here long before anything ever SET it: the pump decoded only the four held modifiers, so
	// the constant was exported, re-exported through platform, and promised a capability the toolkit did
	// not deliver. `TestTheLockKeyStateIsCarried` is what caught that.
	ModCaps   KeyMod = 1 << 4
	ModNum    KeyMod = 1 << 5
	ModScroll KeyMod = 1 << 6
)
View Source
const GL_UNSIGNED_SHORT = 0x1403

GL constant used by the indexed batch path.

View Source
const MaxGradientStops = 16

MaxGradientStops caps a gradient's stops. The ramp is rasterised into a 256-wide LUT row, so more stops than that would not be resolvable anyway.

View Source
const (
	// SDL3 SDL_GLAttr enum value 21 (VERIFIED against SDL3 headers —
	// the SDL2-era value 0x5 is DOUBLEBUFFER in SDL3, so context
	// sharing was NEVER enabled and secondary contexts had no shared
	// programs/VBOs/atlas — all their draws were invalid garbage).
	SDL3_GL_SHARE_WITH_CURRENT_CONTEXT uint32 = 21
)

SDL3_GL_SetAttribute values not needed elsewhere.

View Source
const SDL3_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON"

SDL_HINT_ANDROID_TRAP_BACK_BUTTON: "1" makes the Android back gesture arrive as a key press instead of the system closing the app.

SDL's default is "0" — "Back button will be handled as usual for system" — which means the app is closed and can never participate in its own navigation. With it trapped, the press shows up as SDL_SCANCODE_AC_BACK, which this package turns into EventBack so the window can offer it to the app and close only if nothing handles it.

Harmless on desktop: no SDL backend reads it there.

View Source
const SDL3_HINT_VIDEO_FORCE_EGL = "SDL_VIDEO_FORCE_EGL"

SDL_HINT_VIDEO_FORCE_EGL: "0" selects GLX on X11/XWayland. EGL multi-window MakeCurrent/swap is broken in SDL3 on XWayland (SDL#9072, SDL#10023) — GLX is the classic working pattern.

View Source
const SDL3_PIXELFORMAT_ARGB8888 uint32 = 0x16362004

SDL_PIXELFORMAT_ARGB8888 from SDL3's SDL_pixels.h.

View Source
const SDL3_WINDOW_MAXIMIZED uint64 = 0x0000000000000080

SDL3_WINDOW_MAXIMIZED — SDL_video.h: #define SDL_WINDOW_MAXIMIZED SDL_UINT64_C(0x0000000000000080)

View Source
const SDL3_WINDOW_OCCLUDED_MULTI uint64 = 0x0000000000000004

SDL window flags.

Variables

View Source
var (
	SDL3_StartTextInput   func(win unsafe.Pointer)
	SDL3_PushEvent        func(ev uintptr) int32
	SDL3_StopTextInput    func(win unsafe.Pointer)
	SDL3_SetClipboardText func(text uintptr) int32
	SDL3_GetClipboardText func() uintptr
	SDL3_free             func(ptr uintptr)
)
View Source
var (
	SDL3_GL_SetAttributeMulti     func(attr uint32, value int32)
	SDL3_GetWindowID              func(win unsafe.Pointer) uint32
	SDL3_GL_MakeCurrentMulti      func(win unsafe.Pointer, ctx unsafe.Pointer) bool
	SDL3_GL_SwapWindowMulti       func(win unsafe.Pointer) bool
	SDL3_SetWindowTitleMulti      func(win unsafe.Pointer, title uintptr)
	SDL3_GetWindowSizeMulti       func(win unsafe.Pointer, w, h *int32)
	SDL3_SetWindowSizeMulti       func(win unsafe.Pointer, w, h int32)
	SDL3_SetWindowFullscreenMulti func(win unsafe.Pointer, fullscreen bool) bool
	SDL3_GetErrorMulti            func() uintptr
	SDL3_SetWindowIcon            func(win unsafe.Pointer, icon unsafe.Pointer) bool
	SDL3_CreateSurfaceFrom        func(w, h int32, format uint32, pixels unsafe.Pointer, pitch int32) unsafe.Pointer
	SDL3_DestroySurface           func(surface unsafe.Pointer)
)

SDL3 window functions only used by multi-window paths.

View Source
var (
	SDL3_GL_SetSwapIntervalMulti func(interval int) bool
	SDL3_GetWindowFlagsMulti     func(win unsafe.Pointer) uint64
	SDL3_ShowWindowMulti         func(win unsafe.Pointer)
	SDL3_RaiseWindowMulti        func(win unsafe.Pointer)
	SDL3_SetHintMulti            func(name, value uintptr) bool
)
View Source
var (
	SDL3_MinimizeWindow func(win unsafe.Pointer) bool
	SDL3_MaximizeWindow func(win unsafe.Pointer) bool
	SDL3_RestoreWindow  func(win unsafe.Pointer) bool
)

minimize/restore/maximize entry points for the WindowFrame buttons.

View Source
var (
	SDL3_GetWindowProperties func(win unsafe.Pointer) uint32
	SDL3_GetPointerProperty  func(props uint32, name uintptr, def uintptr) uintptr
)
View Source
var (
	SDL3_Init               func(uint64) int32
	SDL3_Quit               func()
	SDL3_CreateWindow       func(title uintptr, w int32, h int32, flags uint64) unsafe.Pointer
	SDL3_DestroyWindow      func(unsafe.Pointer)
	SDL3_PollEvent          func(event unsafe.Pointer) bool
	SDL3_GL_CreateContext   func(unsafe.Pointer) unsafe.Pointer
	SDL3_GL_MakeCurrent     func(unsafe.Pointer, unsafe.Pointer)
	SDL3_GL_SwapWindow      func(unsafe.Pointer)
	SDL3_GL_SetAttribute    func(uint32, int32)
	SDL3_GL_GetProcAddress  func(name uintptr) uintptr
	SDL3_CreateSystemCursor func(cursorType int32) unsafe.Pointer
	SDL3_SetCursor          func(cursor unsafe.Pointer)
	// SDL_GetModState returns the CURRENT modifier state. A wheel event carries no
	// modifier field of its own (SDL_MouseWheelEvent has none), so this is the only
	// way to know whether shift or ctrl was held when the wheel turned.
	SDL3_GetModState func() uint16
)
View Source
var (
	SDL_Init              func(uint32) int32
	SDL_Quit              func()
	SDL_CreateWindow      func(uintptr, int32, int32, int32, int32, uint32) unsafe.Pointer
	SDL_DestroyWindow     func(unsafe.Pointer)
	SDL_PollEvent         func(unsafe.Pointer) int32
	SDL_GL_CreateContext  func(unsafe.Pointer) unsafe.Pointer
	SDL_GL_MakeCurrent    func(unsafe.Pointer, unsafe.Pointer)
	SDL_GL_SwapWindow     func(unsafe.Pointer)
	SDL_GL_SetAttribute   func(uint32, int32)
	SDL_GL_GetProcAddress func(uintptr) uintptr
)
View Source
var SDL3_GetCurrentVideoDriver func() uintptr

SDL3_GetCurrentVideoDriver reports the active video backend name.

View Source
var SDL3_GetGlobalMouseState func(x, y *float32) uint32

SDL3_GetGlobalMouseState reports the asynchronous desktop-relative cursor position (immune to window-position feedback, unlike the window-relative motion events).

View Source
var SDL3_GetMouseState func(x, y *float32) uint32

SDL3_GetMouseState reports live button state; the hit-test uses it to tell real presses (button down) from cursor-update calls.

View Source
var SDL3_GetTextInputArea func(win unsafe.Pointer, rect unsafe.Pointer, cursor *int32) bool

SDL3_GetTextInputArea is registered with the rest of the SDL3 entry points.

View Source
var SDL3_GetWindowPositionMulti func(win unsafe.Pointer, x, y *int32)
View Source
var SDL3_GetWindowSafeArea func(win unsafe.Pointer, rect unsafe.Pointer) bool

SDL3_GetWindowSafeArea is registered with the rest of the SDL3 entry points.

View Source
var SDL3_GetWindowSizeInPixelsMulti func(win unsafe.Pointer, w, h *int32)
View Source
var SDL3_SetTextInputArea func(win unsafe.Pointer, rect unsafe.Pointer, cursor int32) bool

SDL3_SetTextInputArea is registered with the rest of the SDL3 entry points.

View Source
var (
	SDL3_SetWindowHitTest func(win unsafe.Pointer, callback uintptr, data unsafe.Pointer) bool
)
View Source
var SDL3_SetWindowPositionMulti func(win unsafe.Pointer, x, y int32)

MoveSDLWin places the window's top-left corner (left/top resize).

View Source
var SDL3_ShowWindowFunc func(unsafe.Pointer)

SDL3_ShowWindow makes a window visible

View Source
var SDL3_SyncWindow func(win unsafe.Pointer) bool

MoveResizeSDLWin moves+resizes in one atomic X11 request. Returns false when the atomic path is unavailable (caller falls back to the split MoveSDLWinBy + ResizeWindow path). SDL3_SyncWindow blocks until SDL has finalised pending window state. It is the way out of a lagging size query: SDL can deliver a resize event before its own cached size catches up, and while that is true the probe agrees with the stale cache while the event holds the truth - the state in which a vertical resize leaves the seam's size unchanged and the frame is drawn at the old height.

View Source
var SwapEGL func()

SwapEGL is set by the Android backend to redirect SwapWindow to eglSwapBuffers.

Functions

func AcquireRenderer

func AcquireRenderer()

AcquireRenderer locks the global render pipeline. Call before any batch accumulation and hold through Swap/flush. See renderMu.

func AntialiasPreference

func AntialiasPreference() bool

AntialiasPreference reports the current preference.

func BeginBlur

func BeginBlur()

BeginBlur redirects rendering to the FBO texture for offscreen capture.

func Blur

func Blur(radius float32)

Blur applies a separable Gaussian blur to the current framebuffer contents

func CapHeightPx

func CapHeightPx(f *truetype.Font, size float32) float32

CapHeightPx measures the 'H' cap height in px for a truetype font at the given em size. Returns 0 if it cannot be measured.

func ClearScissor

func ClearScissor()

func ClearScreen

func ClearScreen(col uint32)

func CreateOffscreenFBO

func CreateOffscreenFBO(w, h int32) (uint32, uint32)

func CreateSDLWindowMulti

func CreateSDLWindowMulti(title string, width, height int32) (*sdlWin, error)

CreateSDLWindowMulti opens a new OS window with its own GL context sharing the primary renderer state. Must be called with the GL thread locked (callers run inside InitWindow-style setup on the locked thread). Returns the registry handle.

func CurClipQuad

func CurClipQuad() (float32, float32, float32, float32)

curClipQuad returns the active clip as (minX, minY, maxX, maxY) in GL window coords for stamping into per-vertex clip attributes. CurClipQuad exposes the per-vertex clip stamp for diagnostics — the same value appendWithClip and SDFBatchTexturedQuads put on every vertex. Exported like DefaultReadFBO, for probes that need to see what a draw was stamped with.

func DefaultReadFBO

func DefaultReadFBO() int32

DefaultReadFBO reports the framebuffer binding captured at package init, which the offscreen helpers rebind as "the default framebuffer". It is exposed so a probe can confirm what it actually holds: 0 is each context's own drawable (per-context-correct), while any other value would be a binding captured in some other context and would be wrong to rebind here.

func DeleteOffscreenFBO

func DeleteOffscreenFBO(fbo, tex uint32)

func DescentPx

func DescentPx(f *truetype.Font, size float32) float32

DescentPx returns the font's descent (distance below baseline) in px at the given em size. Prefers hhea metrics (what skia reports to unison); falls back to the global glyph bounding box.

func DestroySDLWin

func DestroySDLWin(h *sdlWin)

DestroySDLWin removes a window from the registry and destroys it. The caller must not use the handle afterwards.

func DrawCircleGL

func DrawCircleGL(cx, cy, radius float32, color Color)

func DrawLineGL

func DrawLineGL(x1, y1, x2, y2 float32, color Color, strokeW float32)

func DrawOvalGL

func DrawOvalGL(x, y, w, h float32, color Color)

func DrawRectGL

func DrawRectGL(x, y, w, h float32, color Color, angle float32)

Drawing helpers for platform backends.

func DrawTexturedQuadsBatch

func DrawTexturedQuadsBatch(verts []float32, texID uint32, color Color, isImage bool)

DrawTexturedQuadsBatch appends textured quads to the frame batch.

func DrawTrianglesBatch

func DrawTrianglesBatch(verts []float32, color Color)

DrawTrianglesBatch appends triangles to the frame batch (for AndroidRenderer).

func DumpRenderState

func DumpRenderState(where string)

DumpRenderState prints the process-global render state that is neither per-context GL state nor covered by InvalidateGLStateCache: the screen-size uniforms, the FBO currently bound, and the clip-discard flag and plane table.

The offscreen pass (RenderOffscreen) runs in the middle of a window's frame and mutates all of these; the window that performed it then looks fine while the windows painted after it break, which points at state consumed at the START of the next frame. Comparing this line across an offscreen pass and the next ClearWithViewport is how that state is found. Gated by MEUI_STATE_TRACE.

func EdgeZone

func EdgeZone(x, y, w, h float32) uint32

EdgeZone classifies a window-relative point against the resize border (6px). Returns an Edge* bitmask, 0 when not on an edge. MUST stay in sync with widgets.FrameEdgeSize (the frame hit-test).

func EffectiveSize

func EffectiveSize(w *Window) (int32, int32)

EffectiveSize returns the size to render and lay out at. Three cases:

  • our requests are newer than the last ack, or very recent: trust the optimistic cache (SDL can only report lagging values mid-drag; adopting them rewinds every frame → jitter/flash);
  • quiet (no requests for >1s): converge to ground truth. The LIVE PROBE is checked FIRST — during drags, ConfigureNotify events are processed later than requests are sent, so the newest-recorded ack can carry a mid-drag size a few px behind the final request while still looking "newer". Adopting it 1s after release reverts the cache below the real window → the post-drag flash strip. SDL's own cache (the probe) is pumped synchronously and is authoritative once quiet. The ack is only used when the probe AGREES with the cache but the ack differs (SDL's cache lagging its own event — the maximize case, where event data was observed fresher than the cache).

External resizes (maximize button, WM actions) issue no request through us, so ground truth is adopted after the quiet period, including missed resize events.

func EmbeddedRobotoFace

func EmbeddedRobotoFace(style string) *truetype.Font

EmbeddedRobotoFace returns the embedded Roboto face for a style suffix ("Light", "Bold", "Bold Italic", …) with "Regular" fallback.

func EndBlur

func EndBlur(radius float32)

EndBlur unbinds the FBO and blurs the result to the screen.

func EraseRoundedCorners

func EraseRoundedCorners(x, y, w, h, radius float32, topOnly bool)

EraseRoundedCorners zeroes the framebuffer alpha outside the rounded rect (x, y, w, h) at the given radius. topOnly extends the shape below the window so only the top corners round. Call after all content for the frame has been batched; the pending batches are flushed first, then the erase quad is drawn with erase blending.

func ErrOffscreenFailed

func ErrOffscreenFailed() error

func FlushBatches

func FlushBatches()

func FontMetricsRatios

func FontMetricsRatios(f *truetype.Font) fontMetricsRatios

FontMetricsRatios returns the hhea-derived ascent/descent ratios for a parsed font (0 values if unknown).

func GLClearDepth

func GLClearDepth()

func GLDepthTest

func GLDepthTest(enabled bool)

func GLDepthWrite

func GLDepthWrite(enabled bool)

func GLInfo

func GLInfo() (vendor, renderer, version string)

GLInfo returns the driver's vendor, renderer and version strings.

func GLXDrawableSize

func GLXDrawableSize() (int32, int32, bool)

GLXDrawableSize reports the size of the GLX drawable current on this thread, as the X server sees it. ok is false when the probe is unavailable (no GLX symbol, no current context, or the server refuses the query) - never silently (0,0,true).

func Gaussian

func Gaussian(x, sigma float32) float32

Gaussian calculates a Gaussian weight for the given distance and sigma

func GaussianWeights

func GaussianWeights(radius int, sigma float32) []float32

GaussianWeights calculates normalized Gaussian weights for blur kernel

func GetClipboardText

func GetClipboardText() string

GetClipboardText reads the system clipboard (SDL3). Empty string when unavailable.

func GetError

func GetError() uint32

GetError returns the current OpenGL error (0 means no error).

func GetGL3ProcAddress

func GetGL3ProcAddress(name string) uintptr

func GetGLProcAddress

func GetGLProcAddress(name string) uintptr

GetGLProcAddress retrieves an OpenGL function pointer from the SDL context

func GlobalAlphaPreference

func GlobalAlphaPreference() float32

GlobalAlphaPreference reports the current alpha multiplier.

func GlobalMousePos

func GlobalMousePos() (float32, float32)

GlobalMousePos returns the desktop-relative cursor position. Used for manual window moves so the drag math can't feed back on itself while the window is moving underneath the cursor.

func HasEGLSupport

func HasEGLSupport() bool

HasEGLSupport returns true if EGL/GLES libraries were loaded successfully

func HasGLSupport

func HasGLSupport() bool

HasGLSupport returns true if desktop OpenGL is available

func Init

func Init() error

Init loads OpenGL ES symbols from the system libraries using purego. This must be called before any GLES functions are used.

func InitEGLForAndroid

func InitEGLForAndroid(window unsafe.Pointer, width, height int32) error

InitEGLForAndroid initializes EGL for an Android ANativeWindow. window is the ANativeWindow pointer passed from JNI. After success, GL function pointers are loaded via eglGetProcAddress.

func InitRenderer

func InitRenderer() error

func InitWindowError

func InitWindowError() error

InitWindowError reports why the platform window could not be created, or nil when it was. It answers for the most recent InitWindow call.

func InvalidateGLStateCache

func InvalidateGLStateCache()

InvalidateGLStateCache resets every cached GL binding after a context switch. GL state is PER-CONTEXT: the caches describe the previous context — a flush after MakeCurrent(otherCtx) would skip re-binding program/VBO/IBO/attribs and draw with this context's defaults (null attrib pointers → driver SIGSEGV).

func KnownCursorNames

func KnownCursorNames() []string

KnownCursorNames returns the logical cursor names this backend maps to a system cursor. meui/platform asserts its constructors against this list.

func LoadGLESFromLib

func LoadGLESFromLib(lib uintptr)

LoadGLESFromLib registers all GLES function pointers from a loaded library handle. Used by platform backends (e.g. Android) to load GL functions after EGL init.

func LoadSystemFont

func LoadSystemFont(path string) (*truetype.Font, error)

func LoadTTFFromBytes

func LoadTTFFromBytes(data []byte) (*truetype.Font, error)

func LoadTTFFromFile

func LoadTTFFromFile(path string) (*truetype.Font, error)

func MakeCurrentSDLWin

func MakeCurrentSDLWin(h *sdlWin) bool

MakeCurrentSDLWin binds a window's GL context on this thread. Falls back to the primary window's context on the legacy path. MakeCurrentSDLWin binds the window's context and reports success. Returns false when the bind failed — callers must NOT draw/swap for the window this frame (mismatched context+drawable hangs XWayland).

func MaxTextureUnits

func MaxTextureUnits() int

MaxTextureUnits reports GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, which bounds how many distinct textures one batch can sample.

func MaxTexturesPerBatch

func MaxTexturesPerBatch() int

MaxTexturesPerBatch reports how many distinct textures one unified batch can sample before it flushes and starts a new sampler-unit table.

func MaxVertexAttribs

func MaxVertexAttribs() int

MaxVertexAttribs reports GL_MAX_VERTEX_ATTRIBS, or 0 when it cannot be read. The unified SDF batch uses 16 attributes, so on a driver reporting fewer the gradient attributes would silently not bind.

func MaximizeSDLWin

func MaximizeSDLWin(h *sdlWin)

func MinimizeSDLWin

func MinimizeSDLWin(h *sdlWin)

MinimizeSDLWin / MaximizeSDLWin / RestoreSDLWin drive the window state from the custom title bar buttons.

func MouseLeftDown

func MouseLeftDown() bool

MouseLeftDown reports whether the left button is currently held. Ground truth for hit-test press detection (motion calls have the button up; a call coinciding with a press has it down). Returns false when SDL is unavailable (tests, tools).

func MoveResizeSDLWin

func MoveResizeSDLWin(w *Window, x, y, width, height int32) bool

MoveResizeSDLWin moves and resizes a window through SDL.

This used to issue XConfigureWindow + XSync directly, which paired origin and size in one request - but the GLX drawable follows the X window LAZILY, so a frame rendered at the new size could land on a surface that had not caught up. With GL's origin at the bottom left that offsets the whole frame vertically by the resize delta, which is the reported corruption on vertical resizes and on maximise. SDL's own calls keep its drawable in step with the window, so the raw-X11 path is gone.

func MoveSDLWinBy

func MoveSDLWinBy(w *Window, x, y int32)

MoveSDLWinBy repositions the window (used by left/top resize so the grabbed corner follows the mouse).

func NoteResizeAck

func NoteResizeAck(w *Window, width, height int32)

NoteResizeAck records a ConfigureNotify-acked size for request/ack matching. It does NOT touch the cached size — EffectiveSize decides.

func PendingBatchVerts

func PendingBatchVerts() int

PendingBatchVerts reports how many vertices are still queued in ANY of the process-global batches (SDF shapes/text/images, triangles, immediate shapes) and therefore not yet submitted to GL.

The batches are process-global and their vertices are stamped with the CURRENT window's projection and clip, so a non-zero count at a frame boundary means work that belongs to the window that just drew: presenting the buffer with a non-empty batch defers that work into whatever frame (usually another window) flushes next. It must be 0 before every Swap.

func PrimarySDLWinHandle

func PrimarySDLWinHandle() *sdlWin

PrimarySDLWinHandle returns the legacy primary window's handle (nil before the first window exists). Multi-window features fall back to it so the first window gets chrome too.

func PrimarySDLWindowPointer

func PrimarySDLWindowPointer() unsafe.Pointer

PrimarySDLWindowPointer returns the raw SDL_Window* for the primary window, or nil when there is none.

The platform adapter needs it to PARENT a native dialog: SDL_ShowOpenFileDialog takes the owning window, and on mobile it is required rather than optional. The handle's own win field is unexported, so this is the accessor.

func ProbeFullClear

func ProbeFullClear(w, h int32) (top, bottom uint32, ok bool)

ProbeFullClear paints the ENTIRE claimed surface (viewport w x h, scissor and stencil off) a distinctive colour, then reads one pixel near the top row and one near the bottom. If a 520x620 window's back buffer is really 520x380, the clear fills only the bottom 380 rows and the read at y=610 is outside it. This separates "the surface is smaller than the window" from "the surface is fine and the fragments are being rejected", which no existing instrument could tell apart because every one of them reads through the same glReadPixels.

func ProcessEvents

func ProcessEvents(win *Window)

ProcessEvents polls all event sources and dispatches events to window state. Only the designated pump owner drives the global SDL queue — with multiple windows each on its own thread, SDL_PollEvent must be called from exactly one place (events are routed by windowID).

func ProcessEventsAndDispatch

func ProcessEventsAndDispatch(win *Window)

ProcessEventsAndDispatch polls event sources and dispatches to window state.

func ProcessSDL3Events

func ProcessSDL3Events(win *Window)

ProcessSDL3Events drains SDL for the legacy single-window path.

func ProcessSDLEvents

func ProcessSDLEvents(win *Window)

func PumpAll

func PumpAll()

PumpAll drains the platform event queue once, routing each event to the window that owns it.

func PumpEvents

func PumpEvents(fallback *Window)

PumpEvents polls the platform event sources and routes each event to the window that owns it (multi-window) or to the given window (legacy). Returns after all pending events are drained.

func QuerySDLWinSize

func QuerySDLWinSize(h *sdlWin) (int32, int32)

QuerySDLWinSize returns the window's TRUE size in screen pixels (display scaling can make it differ from the requested size) and records it on the handle.

func RaiseSDLWindow

func RaiseSDLWindow(h *sdlWin)

RaiseSDLWindow brings the window to the front.

func ReadOffscreenPixels

func ReadOffscreenPixels(fbo uint32, w, h int32) []uint32

func ReadScreenPixels

func ReadScreenPixels(w, h int32) []uint32

ReadScreenPixels reads the default framebuffer (back buffer) as 0xAARRGGBB pixels, bottom-up as GL delivers them. Call while the GL context is current and after FlushBatches() (e.g. inside the draw callback, before the swap).

func ReleaseRenderer

func ReleaseRenderer()

ReleaseRenderer unlocks the global render pipeline.

func RenderOffscreen

func RenderOffscreen(w, h int32, renderFn func()) []uint32

func ResetClipState

func ResetClipState()

ResetClipState clears the Go-side clip mirror at the start of a window's frame. scissorState is process-global and is stamped into every batched vertex (clipMin/clipMax); without a per-frame reset a window's early draws (title bar, panel background) inherit the PREVIOUS window's last clip rect — everything outside it is shader-discarded and edge primitives clip into garbage shapes (observed: window 2 rendered exactly one triangle — the stale rect).

func ResetGLCache

func ResetGLCache()

ResetGLCache resets all cached GL state (call after any external GL code).

func ResetSizeProbe

func ResetSizeProbe()

ResetSizeProbe makes the next SizeProbe print unconditionally, so two reads in one frame (before and after the clear that sets the viewport) can be told apart.

func ResizeSDLWin

func ResizeSDLWin(h *sdlWin, w, hgt int32)

ResizeSDLWin sets a window's pixel size (manual edge-resize drag).

func ResizeWindow

func ResizeWindow(w *Window, width, height int32)

ResizeWindow resizes a mobilegles window's OS surface and updates the logical size.

func RestoreSDLWin

func RestoreSDLWin(h *sdlWin)

func RunHeadlessDemo

func RunHeadlessDemo(win *Window)

RunHeadlessDemo runs the headless demo with simulated input.

func SDFBatchRect

func SDFBatchRect(x, y, w, h, radius float32, color Color, style int32, strokeW, angle float32)

SDFBatchRect appends an axis-aligned rect / rounded rect / circle to the batch. x,y,w,h are SCREEN pixels; radius 0 = sharp box, radius = min(w,h)/2 = circle/oval. Call on the GL thread.

func SDFBatchTexturedQuads

func SDFBatchTexturedQuads(verts []float32, texID uint32, isImage bool)

SDFBatchTexturedQuads appends glyph (mode 1) or image (mode 2) quads to the unified SDF batch. verts holds 4 indexed vertices per quad, 8 floats each: pos2 uv2 color4. Blending is unified to premultiplied (ONE, ONE_MINUS_SRC_ALPHA) — the glyph/image shader paths output premultiplied color, and the SDF shape path premultiplies in the fragment shader, so one batch can interleave shapes, text and images in exact draw order with a single draw call.

func SDFBatchTriangles

func SDFBatchTriangles(verts []float32)

SDFBatchTriangles appends barycentric-AA triangles to the unified batch (mode 3). verts holds 9 floats per vertex: pos2 bary3 color4. Each triangle is padded to a 4-vertex quad so the shared quad index buffer applies: (v0,v1,v2) + degenerate (v1,v3,v2) with v3=v2 — the original triangle rasterizes unchanged and the degenerate half covers nothing.

func SDL3PushEvent

func SDL3PushEvent(buf []byte)

SDL3PushEvent pushes a raw 64-byte SDL3 event into the SDL queue (test/diagnostic injection).

func SDL3_ShowWindow

func SDL3_ShowWindow(window unsafe.Pointer)

func SetAntialiasPreference

func SetAntialiasPreference(on bool)

SetAntialiasPreference sets the antialiasing stamped into subsequently batched primitives. Text and image quads ignore it: they sample a texture and have no edge ramp of their own.

func SetBlendModeCached

func SetBlendModeCached(mode int32)

SetBlendModeCached sets the blend mode only if it has changed.

func SetClipDiscardEnabled

func SetClipDiscardEnabled(on bool)

SetClipDiscardEnabled toggles the batch shaders' per-vertex clip discard. Offscreen rendering turns it off.

func SetClipPlanes

func SetClipPlanes(planes []ClipPlane)

SetClipPlanes replaces the path clip. It is the renderer-side mirror the batched shaders read; the toolkit updates it whenever the effective clip changes.

func SetClipboardText

func SetClipboardText(text string)

SetClipboardText puts text on the system clipboard (SDL3).

func SetCurrentGradient

func SetCurrentGradient(g Gradient)

SetCurrentGradient publishes the gradient for subsequently batched primitives; the zero Gradient means solid colour.

func SetCursorByName

func SetCursorByName(name string)

SetCursorByName applies a system cursor by logical name. Names match the platform.Cursor constructors: "" / "arrow" (default), "text", "pointing", "move", "resizeH", "resizeV", "resizeLD", "resizeRD", "crosshair", "wait", "notAllowed". Unknown names and missing SDL entry points are silent no-ops.

func SetFullscreen

func SetFullscreen(w *Window, fullscreen bool)

SetFullscreen toggles fullscreen on a mobilegles window.

func SetFullscreenSDLWin

func SetFullscreenSDLWin(h *sdlWin, fullscreen bool)

SetFullscreenSDLWin toggles desktop-resolution fullscreen.

func SetGlobalAlphaPreference

func SetGlobalAlphaPreference(a float32)

SetGlobalAlphaPreference sets the alpha multiplier applied to subsequently batched primitives. The legacy immediate paths (gradient rects) ignore it.

func SetRendererFactory

func SetRendererFactory(f func() Renderer)

SetRendererFactory installs the constructor used for the process renderer. Call it before InitRenderer.

func SetSDLWinHitTestHandler

func SetSDLWinHitTestHandler(h *sdlWin, fn frameHitFn)

SetSDLWinHitTestHandler installs a Go classifier for the window's chrome regions. fn returns an SDL_HITTEST_* value.

func SetSDLWinTitle

func SetSDLWinTitle(h *sdlWin, title string)

SetSDLWinTitle updates a window's OS title text.

func SetScissor

func SetScissor(x, y, w, h int32)

func SetScreenSize

func SetScreenSize(w, h float32)

func SetSensorHandler

func SetSensorHandler(fn func(sensorID uint32, values [6]float32))

SetSensorHandler installs the receiver for sensor updates, or clears it with nil. The pump calls it on the UI thread, in the same pass as every other event, so a sensor sample arrives through the same serialized path as input — no polling goroutine and no second thread touching SDL.

func SetSwapInterval0

func SetSwapInterval0()

SetSwapInterval0 sets interval 0 on the currently bound context.

func SetSystemFont

func SetSystemFont(face *truetype.Font)

func SetWindowHitHandler

func SetWindowHitHandler(w *Window, fn func(x, y int32) uint32)

SetWindowHitHandler installs a chrome classifier on a mobilegles Window (convenience over SetSDLWinHitTestHandler). Falls back to the primary window's handle on the legacy single-window path.

func SetWindowSizeSDLWin

func SetWindowSizeSDLWin(w *Window, width, height int32) bool

SetWindowSizeSDLWin asks the OS for a new window SIZE without moving it. The request comes back through SDL_EVENT_WINDOW_RESIZED, so the whole resize path runs — drawable, viewport, projection and the toolkit's EventResize — exactly as it does when a user drags an edge. A host that wants to set a size programmatically (and a test that wants to exercise a real resize without a pointer) needs this; MoveResizeSDLWin also moves.

func Shutdown

func Shutdown()

Shutdown tears down SDL cleanly (window + subsystems). Call after the last window closes — e.g. windowed test harnesses before the process exits. Safe to call when SDL was never initialized.

func SizeProbe

func SizeProbe(w *Window)

func SwapEGLBuffers

func SwapEGLBuffers()

SwapEGLBuffers swaps the EGL buffers (call after rendering)

func SwapSDL3Window

func SwapSDL3Window()

func SwapSDLWin

func SwapSDLWin(h *sdlWin)

SwapSDLWin presents a window's back buffer.

The one XWayland safeguard this needs is swap interval 0: a vsync'd swap waits for the compositor's frame callback, which never arrives for a fully occluded/unmapped window — an infinite block that froze the whole composite loop. Forcing interval 0 on the context (below) removes that hazard at its source.

It deliberately does NOT skip the present when SDL reports the window OCCLUDED. That flag is advisory and on XWayland it is sticky: once the window manager or compositor reports a window covered, it can stay set after the window is uncovered again. Skipping the swap turns the flag into a frozen window: the app keeps clearing and drawing into a back buffer that is never presented, so the window keeps showing its last presented frame, and a later resize exposes the never-presented buffer as undefined memory (garbage from any previous frame) in the newly exposed area. Covering a window with another one is therefore enough to freeze it permanently — reported as "all the other windows stop working and the Analysis window is the only one that works".

func SwapSDLWindow

func SwapSDLWindow()

func SwapWindow

func SwapWindow()

SwapWindow swaps the window buffer (SDL3, SDL2, or EGL).

func SystemTTF

func SystemTTF() *truetype.Font

func TerminateEGL

func TerminateEGL()

TerminateEGL cleans up EGL resources

func ToggleMaximizeSDLWin

func ToggleMaximizeSDLWin(h *sdlWin)

ToggleMaximizeSDLWin maximizes the window, or restores it when it is already maximized (title-bar maximize button behavior).

func UseProgramCached

func UseProgramCached(program uint32)

UseProgramCached calls glUseProgram only if the program has changed.

func VideoDriver

func VideoDriver() string

VideoDriver returns the active SDL video backend ("x11", "wayland", ...) — cached after the first query. Empty when SDL is unavailable (tests, tools).

func WindowMaximized

func WindowMaximized(w *Window) bool

WindowMaximized reports whether the OS window is maximized.

func WindowPos

func WindowPos(w *Window) (int32, int32)

WindowPos returns the window's top-left position in screen coords.

func WindowSize

func WindowSize(w *Window) (int32, int32)

WindowSize returns the window's TRUE current pixel size — ground truth for layout (queried live; resize events can lag/misreport).

Types

type BlendMode

type BlendMode int

BlendMode defines blend modes

const (
	BlendModeNormal BlendMode = iota
	BlendModeMultiply
	BlendModeScreen
	BlendModeOverlay
	BlendModeDarken
	BlendModeLighten
	BlendModeColorDodge
	BlendModeColorBurn
	BlendModeHardLight
	BlendModeSoftLight
	BlendModeDifference
	BlendModeExclusion
	BlendModeHue
	BlendModeSaturation
	BlendModeColor
	BlendModeLuminosity
)

type BlurRenderer

type BlurRenderer struct {
	// contains filtered or unexported fields
}

type Canvas

type Canvas struct {
	// contains filtered or unexported fields
}

Canvas is a simplified drawing surface for OpenGL ES. This is a subset of unison.Canvas methods needed for MeUi.

func NewCanvas

func NewCanvas(width, height float32) *Canvas

NewCanvas creates a new canvas for the given dimensions.

func (*Canvas) Clear

func (c *Canvas) Clear(col uint32)

Clear clears the canvas with a color.

func (*Canvas) ClearWithViewport

func (c *Canvas) ClearWithViewport(col uint32, x, y, w, h int32)

ClearWithViewport clears the canvas with a color and sets viewport

func (*Canvas) ClipBounds

func (c *Canvas) ClipBounds() Rect

ClipBounds returns the current clip bounds.

func (*Canvas) ClipDepth

func (c *Canvas) ClipDepth() int

ClipDepth returns the current clip-stack depth. Debug aid for hunting widgets that push a clip without popping it.

func (*Canvas) ClipPath

func (c *Canvas) ClipPath(path *Path) bool

ClipPath intersects the clip with the interior of path, transformed by the current matrix.

It reports whether the clip is EXACT. Clipping is applied as per-vertex half-planes, which express any convex outline; a concave outline is clipped to its convex hull, and an outline needing more than maxClipPlanes edges is clipped to its bounding rectangle instead. Both fallbacks are supersets of the requested region, so content the caller asked to keep is never hidden — the clip can only ever show a little more than asked, never less — but both report false.

func (*Canvas) ClipRect

func (c *Canvas) ClipRect(r Rect)

ClipRect sets the clipping rectangle using scissor test.

func (*Canvas) DrawArc

func (c *Canvas) DrawArc(x, y, w, h, startAngle, sweepAngle float32, p *Paint)

DrawArc draws an arc within the given oval bounds

func (*Canvas) DrawCircle

func (c *Canvas) DrawCircle(cx, cy, r float32, p *Paint)

DrawCircle draws a filled circle at (cx, cy) with radius r.

func (*Canvas) DrawCirclePath

func (c *Canvas) DrawCirclePath(cx, cy, r float32, p *Paint)

func (*Canvas) DrawColor

func (c *Canvas) DrawColor(col uint32, mode BlendMode)

DrawColor fills the entire canvas with a color using the specified blend mode.

func (*Canvas) DrawImage

func (c *Canvas) DrawImage(img *Image, x, y float32, p *Paint)

DrawImage draws an image at the given position DrawImage draws an image at the given position (no scaling).

func (*Canvas) DrawImageInRect

func (c *Canvas) DrawImageInRect(img *Image, rect Rect, p *Paint)

DrawImageInRect draws an image scaled to fit the given rectangle. Uploads the image as a GL_RGBA texture and renders via textured quads.

func (*Canvas) DrawImageNine

func (c *Canvas) DrawImageNine(img *Image, centerRect Rect, dest Rect, p *Paint)

DrawImageNine draws a 9-patch image. The source image is divided into 9 regions by centerRect (in pixel coordinates). The four corners are drawn at their natural size, edges stretch along one axis, and the center stretches in both directions.

func (*Canvas) DrawLine

func (c *Canvas) DrawLine(x1, y1, x2, y2 float32, p *Paint)

DrawLine draws a line from (x1, y1) to (x2, y2)

func (*Canvas) DrawLineRotated

func (c *Canvas) DrawLineRotated(x, y, length, thickness, angle float32, p *Paint)

DrawLineRotated draws a rotated line starting at (x, y)

func (*Canvas) DrawOval

func (c *Canvas) DrawOval(x, y, w, h float32, p *Paint)

DrawOval draws an oval (ellipse) within the given bounds

func (*Canvas) DrawPath

func (c *Canvas) DrawPath(path *Path, p *Paint)

DrawPath draws a path by splitting into contours, flattening curves, triangulating each contour with earcut, and submitting triangles to the GPU.

func (*Canvas) DrawPoints

func (c *Canvas) DrawPoints(verts []float32, p *Paint)

QuickRejectPath returns true if the path bounds are entirely outside the current clip. DrawPoints renders a batch of points as filled circles.

func (*Canvas) DrawRect

func (c *Canvas) DrawRect(x, y, w, h float32, p *Paint)

DrawRect draws a rectangle at (x, y) with given width and height. Triangulated into 2 triangles and accumulated in the frame batch.

func (*Canvas) DrawRoundedRect

func (c *Canvas) DrawRoundedRect(rect Rect, radiusX, radiusY float32, p *Paint)

DrawRoundedRect draws a rectangle with rounded corners DrawRoundedRect draws a rounded rectangle using a path with corner arcs. Reuses the existing path rendering pipeline for proper edge AA.

func (*Canvas) DrawSimpleString

func (c *Canvas) DrawSimpleString(text string, x, y float32, p *Paint)

DrawSimpleString draws simple text using the system font

func (*Canvas) DrawText

func (c *Canvas) DrawText(text string, x, y float32, font *Font, p *Paint)

DrawText renders text using a bitmap font atlas.

func (*Canvas) DrawTriangleFilled

func (c *Canvas) DrawTriangleFilled(p1, p2, p3 Point, p *Paint)

DrawTriangleFilled fills one triangle. Like every other Canvas entry point it takes LOCAL coordinates and applies the canvas transform itself — the stroke walk's joins pass the same local points it hands to DrawLine, and a triangle that skipped the transform landed a whole view offset away from its own stroke (visible as flecks of cable colour on the canvas).

func (*Canvas) DropShadow

func (c *Canvas) DropShadow(rect Rect, p *Paint, offsetX, offsetY, radius float32)

DropShadow draws a blurred drop shadow using the FBO pipeline. The shadow shape is rendered offset, then blurred, composited back to screen. Call between BeginBlur/EndBlur for the blurred background shape. Uses the 2-pass separable Gaussian blur for smooth edges.

func (*Canvas) GetMatrix

func (c *Canvas) GetMatrix() Matrix

GetMatrix returns the current transform matrix.

func (*Canvas) Height

func (c *Canvas) Height() float32

Height returns the canvas height in pixels.

func (*Canvas) IsClipEmpty

func (c *Canvas) IsClipEmpty() bool

IsClipEmpty returns true if the current clip is empty.

func (*Canvas) QuickRejectRect

func (c *Canvas) QuickRejectRect(rect Rect) bool

QuickRejectRect returns true if the rect is entirely outside the current clip.

func (*Canvas) ResetClip

func (c *Canvas) ResetClip()

ResetClip drops any active clip and returns the canvas to an unclipped state: the clip stack is cleared and the process-global scissor mirror (stamped into every batched vertex) is reset. Used by callers that draw OUTSIDE a content tree — window title bars — so a leaked content clip (a widget's ClipRect without a matching Restore) cannot discard the bar's primitives.

func (*Canvas) Restore

func (c *Canvas) Restore()

Restore restores the state to the most recent Save: the matrix/paint stacks pop one entry and the clip stack pops back to the length recorded at that Save (removing every ClipRect pushed since).

func (*Canvas) RestoreToCount

func (c *Canvas) RestoreToCount(count int)

RestoreToCount restores to a specific save count.

func (*Canvas) Rotate

func (c *Canvas) Rotate(degrees float32)

Rotate rotates the coordinate system (degrees).

func (*Canvas) Save

func (c *Canvas) Save() int

Save saves the current state (matrix, clip).

func (*Canvas) SaveAndRestore

func (c *Canvas) SaveAndRestore(f func(c *Canvas))

SaveAndRestore runs f inside a Save/Restore pair — the transaction form of Save: every state change f makes (clips, transforms) is rolled back when it returns, even on early paths. Prefer this over bare Save/Restore in widget paints; it cannot leak stack entries.

func (*Canvas) Scale

func (c *Canvas) Scale(sx, sy float32)

Scale scales the coordinate system.

func (*Canvas) Skew

func (c *Canvas) Skew(kx, ky float32)

Skew skews the coordinate system (kx, ky in degrees).

func (*Canvas) TransformRect

func (c *Canvas) TransformRect(x, y, w, h float32) (float32, float32, float32, float32)

TransformRect is the public version of transformRect, used by meuishim.

func (*Canvas) Translate

func (c *Canvas) Translate(dx, dy float32)

Translate translates the coordinate system.

func (*Canvas) Width

func (c *Canvas) Width() float32

Width returns the canvas width in pixels. Clip reset bounds derive from it, so a canvas must be recreated when its window resizes.

func (*Canvas) WithClip

func (c *Canvas) WithClip(r Rect, f func(c *Canvas))

WithClip intersects the clip with r (top-down canvas coords) for the duration of f, then restores the previous clip. The transaction form of ClipRect: drawing with a clip can no longer leak stack entries (the historic TextField bug — every paint pushed a clip that was never popped, poisoning everything painted after it).

type ClipPlane

type ClipPlane struct {
	NX, NY, D float32
}

ClipPlane is one half-plane of a convex clip, in DEVICE space (GL window coordinates, y increasing upward). A pixel is kept when

NX*x + NY*y + D >= 0

Planes are always combined by intersection.

func ClipPlanes

func ClipPlanes() []ClipPlane

ClipPlanes returns the current path clip (nil when only the rect applies).

type Color

type Color uint32

Color is ARGB packed color

func RGB

func RGB(r, g, b uint8) Color

RGB creates a Color from RGB values

func RGBA

func RGBA(r, g, b, a uint8) Color

RGBA creates a Color from RGBA values

func (Color) Paint

func (c Color) Paint(_ *Canvas, _ Rect, style int32) *Paint

Paint returns a Paint for this Color. Here to satisfy the Ink interface in the shim so a Color can be used wherever an Ink is expected.

type DesktopRenderer

type DesktopRenderer struct{}

DesktopRenderer implements Renderer using the existing OpenGL globals.

func (*DesktopRenderer) ClearScissor

func (d *DesktopRenderer) ClearScissor()

func (*DesktopRenderer) ClearWithViewport

func (d *DesktopRenderer) ClearWithViewport(col uint32, x, y, w, h int32)

ClearWithViewport clears the surface and sets the viewport. Clears must never be scissored: batch flushes leave the scissor enabled, and on a fresh context the scissor box is stale, which would leave the rest of the buffer showing uninitialized surface garbage.

func (*DesktopRenderer) DrainErrors

func (d *DesktopRenderer) DrainErrors()

func (*DesktopRenderer) DrawCircle

func (d *DesktopRenderer) DrawCircle(cx, cy, radius float32, color Color)

func (*DesktopRenderer) DrawColor

func (d *DesktopRenderer) DrawColor(col uint32, mode BlendMode)

DrawColor fills the whole surface with col using the given blend mode. It is the legacy immediate path (the rect program), kept behind the interface so Canvas owns no GL state of its own.

func (*DesktopRenderer) DrawLine

func (d *DesktopRenderer) DrawLine(x1, y1, x2, y2 float32, color Color, strokeW float32)

func (*DesktopRenderer) DrawOval

func (d *DesktopRenderer) DrawOval(x, y, w, h float32, color Color)

func (*DesktopRenderer) DrawPathFill

func (d *DesktopRenderer) DrawPathFill(tris []float32, color Color, bounds Rect)

func (*DesktopRenderer) DrawRect

func (d *DesktopRenderer) DrawRect(x, y, w, h float32, color Color, angle float32)

func (*DesktopRenderer) DrawRectStyled

func (d *DesktopRenderer) DrawRectStyled(x, y, w, h, radius, strokeW float32, color Color, style int32, angle float32)

func (*DesktopRenderer) DrawTexturedQuads

func (d *DesktopRenderer) DrawTexturedQuads(verts []float32, texID uint32, color Color, isImage bool)

func (*DesktopRenderer) DrawTriangles

func (d *DesktopRenderer) DrawTriangles(verts []float32, color Color)

func (*DesktopRenderer) Flush

func (d *DesktopRenderer) Flush()

func (*DesktopRenderer) Present

func (d *DesktopRenderer) Present()

func (*DesktopRenderer) ScissorState

func (d *DesktopRenderer) ScissorState() (int32, int32, int32, int32, bool)

func (*DesktopRenderer) ScreenSize

func (d *DesktopRenderer) ScreenSize() (float32, float32)

func (*DesktopRenderer) SetBlendMode

func (d *DesktopRenderer) SetBlendMode(mode BlendMode)

SetBlendMode selects how subsequent draws composite. The GL blend state is global while draws are batched, so a mode change is a batch boundary: the pending batch is flushed under the old mode first.

func (*DesktopRenderer) SetScissor

func (d *DesktopRenderer) SetScissor(x, y, w, h int32)

func (*DesktopRenderer) SetScreenSize

func (d *DesktopRenderer) SetScreenSize(w, h float32)

func (*DesktopRenderer) SetViewport

func (d *DesktopRenderer) SetViewport(x, y, w, h int32)

type EGLContext

type EGLContext struct {
	// contains filtered or unexported fields
}

EGLContext holds EGL display, context, and surface

type ErrNotSupported

type ErrNotSupported struct {
	Platform string
}

ErrNotSupported indicates a backend is not available on this platform.

func (*ErrNotSupported) Error

func (e *ErrNotSupported) Error() string

type Event

type Event struct {
	Type EventType

	// Window
	Width, Height int32 // for EventResize

	// Mouse
	X, Y           float32
	DX, DY         float32 // relative motion
	Button         int     // ButtonLeft/Right/Middle
	WheelX, WheelY float32

	// Keyboard
	Key Keycode
	Mod KeyMod
	// Repeat is set on a key-down that the OS generated by auto-repeat, not by a fresh press. It is
	// SEPARATE from the key deliberately: a widget that acts on a key press must not act again every time
	// the user holds it, and a widget that wants the repeats (a text field, a scrub slider) needs to know
	// which is which. Nothing in the tree set this before — platform.Event declared and documented a
	// Repeat field that no pump ever filled.
	Repeat bool
	Rune   rune // decoded character for EventTextInput

	// Text editing (IME composition): the in-progress text, and the IME's selection inside it
	// (byte offsets). TEXT_INPUT is the commit; this is what to show until then.
	Text       string
	CompStart  int
	CompLength int

	// Touch
	TouchID int64
	Touches []Touch

	// Joystick
	JoystickID int
	Axis       int
	Value      float32
	Hat        int

	// Misc
	Files []string
}

Event represents an input event

type EventQueue

type EventQueue struct {
	// contains filtered or unexported fields
}

EventQueue is the central hub for event processing. Sources push events to it; the app polls from it.

func NewEventQueue

func NewEventQueue() *EventQueue

NewEventQueue creates an event queue with a 256-event ring buffer.

func (*EventQueue) Poll

func (q *EventQueue) Poll() Event

Poll returns the next event, or EventNone if the queue is empty.

func (*EventQueue) PollSources

func (q *EventQueue) PollSources()

PollSources drains all registered sources and queues their events.

func (*EventQueue) PushEvent

func (q *EventQueue) PushEvent(e Event)

PushEvent adds a synthetic event (e.g., from tests).

func (*EventQueue) RegisterSource

func (q *EventQueue) RegisterSource(src EventSource)

RegisterSource adds an event source. Sources are polled in registration order.

type EventSource

type EventSource interface {
	Poll() []Event
	Name() string
}

EventSource is the interface for any input device or event producer. Each source produces typed Event values via Poll(). Sources are registered on EventQueue and polled automatically.

type EventType

type EventType int

EventType represents different event types

const (
	EventNone               EventType = iota
	EventQuit                         // window close requested
	EventTextEditing                  // IME composition in progress (not committed)
	EventResize                       // window resized (Width, Height)
	EventMouseDown                    // mouse button pressed
	EventMouseUp                      // mouse button released
	EventMouseMove                    // mouse moved
	EventMouseWheel                   // scroll wheel (WheelX, WheelY)
	EventKeyDown                      // physical key pressed
	EventKeyUp                        // physical key released
	EventTextInput                    // UTF-8 character input (Rune)
	EventTouchDown                    // finger touched screen (TouchID, X, Y)
	EventTouchUp                      // finger lifted
	EventTouchMove                    // finger moved
	EventTouchCancel                  // touch cancelled
	EventBack                         // the OS asked to go back (Android back gesture/button)
	EventJoystickAxis                 // joystick axis (JoystickID, Axis, Value)
	EventJoystickButtonDown           // joystick button pressed
	EventJoystickButtonUp             // joystick button released
	EventJoystickHat                  // joystick hat moved (JoystickID, Hat, Value)
	EventFocusGained                  // window/app gained focus
	EventFocusLost                    // window/app lost focus
	EventAppPause                     // mobile: app backgrounded
	EventAppResume                    // mobile: app foregrounded
	EventFileDrop                     // file dropped on window (Files)
)

type Font

type Font struct {
	// contains filtered or unexported fields
}

Font holds font data for GPU-accelerated text rendering

func NewFont

func NewFont(family string, size float32, face *truetype.Font) *Font

NewFont delegates to NewFontStyled with no synthetic styles.

func NewFontStyled

func NewFontStyled(family string, size float32, face *truetype.Font, fakeBold, fakeItalic bool) *Font

NewFontStyled creates a font, optionally with synthetic bold/italic (rasterized emboldening/shear for faces lacking real companions — Skia-style synthesis). Styled variants get their own atlas.

func SystemFont

func SystemFont() *Font

SystemFont returns the default system font

func (*Font) Baseline

func (f *Font) Baseline() float32

Baseline returns the baseline that vertically centers text optically. Widget code centers with (h - LineHeight)/2 + Baseline; using the font bbox ascent here (bounds.Max.Y ≈ 1.23em — accent headroom over ALL glyphs) pushed every centered label ~3.5px below the box center. The correct value is the line-box midpoint plus half the cap height, with cap height measured from the rasterized 'H' glyph.

func (*Font) Descender

func (f *Font) Descender() float32

func (*Font) Descriptor

func (f *Font) Descriptor() FontDescriptor

Descriptor returns the font descriptor

func (*Font) Face

func (f *Font) Face() *truetype.Font

Face returns the underlying truetype font face

func (*Font) Family

func (f *Font) Family() string

Family returns the font family name

func (*Font) LineHeight

func (f *Font) LineHeight() float32

LineHeight returns the font line height

func (*Font) Size

func (f *Font) Size() float32

Size returns the font size in points

func (*Font) TextWidth

func (f *Font) TextWidth(text string) float32

TextWidth measures with the SAME engine that draws: the glyph atlas. It mirrors DrawText's pen walk exactly (kern + whole-pixel atlas advance per glyph, same skips and same nil fallback) so measurement can never drift from rendering — synthetic styles included, since their advance adjustments live in the atlas itself. Returns the widest line.

type FontDescriptor

type FontDescriptor struct {
	Family string
	Size   float32
}

FontDescriptor describes a font

type FrameStats

type FrameStats struct {
	Primitives int64
	DrawCalls  int64
	Flushes    int64
}

FrameStats is a snapshot of renderer activity counters.

func GetFrameStats

func GetFrameStats() FrameStats

GetFrameStats returns and resets the counters.

type GPUTimer

type GPUTimer struct {
	// contains filtered or unexported fields
}

GPUTimer provides GPU-side timing for profiling shader performance.

func NewGPUTimer

func NewGPUTimer() *GPUTimer

NewGPUTimer creates a new GPU timer query.

func (*GPUTimer) Begin

func (t *GPUTimer) Begin()

Begin starts the GPU timing measurement.

func (*GPUTimer) End

func (t *GPUTimer) End()

End stops the GPU timing measurement.

func (*GPUTimer) Nanoseconds

func (t *GPUTimer) Nanoseconds() int64

Nanoseconds returns the elapsed GPU time in nanoseconds. Returns 0 if the result is not yet available.

type Gradient

type Gradient struct {
	Type       GradientType
	Stops      [MaxGradientStops]GradientStop
	StopCount  int
	Start, End Point
	Center     Point
	Radius     float32
	StartAngle float32
}

Gradient describes a multi-stop colour gradient for fills and strokes.

Linear: ramp runs from Start to End.
Radial: ramp runs from Center out to Radius.
Conic:  ramp sweeps around Center, starting at StartAngle degrees.

Stops are kept sorted by Offset so sampleGradientStops can walk them.

func CurrentGradient

func CurrentGradient() Gradient

CurrentGradient returns the published gradient.

func (*Gradient) SetStops

func (g *Gradient) SetStops(stops []GradientStop)

SetStops replaces the gradient's stops, sorted by offset so the ramp is well defined. Fewer than two stops leaves it a flat fill of the first.

type GradientStop

type GradientStop struct {
	Offset float32
	Color  Color
}

GradientStop is one colour stop at Offset (0..1) along the gradient.

type GradientType

type GradientType int

GradientType defines gradient shape

const (
	GradientNone GradientType = iota
	GradientLinear
	GradientRadial
	GradientConic
)

type Image

type Image struct {
	// contains filtered or unexported fields
}

Image represents an image with texture

func NewImage

func NewImage(rgba []uint32, w, h int32) *Image

NewImage creates a new image from raw ARGB data. Pixels are assumed premultiplied (the case for framebuffer readbacks); use NewImageFromPNG for straight-alpha sources.

func NewImageFromPNG

func NewImageFromPNG(data []byte) (*Image, error)

NewImageFromPNG decodes a PNG from bytes

func (*Image) Dirty

func (img *Image) Dirty() bool

Dirty reports whether the texture is behind the pixel buffer.

func (*Image) Height

func (img *Image) Height() int32

Height returns image height

func (*Image) LogicalSize

func (i *Image) LogicalSize() Size

LogicalSize returns the image's dimensions as a Size. Used by meui for layout.

func (*Image) MarkPixelsDirty

func (img *Image) MarkPixelsDirty()

MarkPixelsDirty flags the CPU pixel buffer as modified so the next draw re-uploads the texture. Safe to call off the GL thread.

func (*Image) Pixels

func (img *Image) Pixels() []uint32

Pixels returns the decoded pixel data

func (*Image) SetPixels

func (img *Image) SetPixels(pix []uint32)

SetPixels replaces the pixel buffer, for a caller that re-renders into the same surface. The buffer must be the same size as the image: this image keeps one texture, and a different extent would be uploaded under the old shape.

func (*Image) TextureID

func (img *Image) TextureID() uint32

TextureID returns the GPU texture handle (0 = not uploaded).

func (*Image) ToPNG

func (img *Image) ToPNG(compressionLevel int) ([]byte, error)

ToPNG encodes the image as a PNG and returns the bytes. compressionLevel: 0 = default, 1-9 = higher compression.

func (*Image) Upload

func (img *Image) Upload()

Upload creates or updates the GPU texture for this image. Must be called from the GL thread (inside LockOSThread). With no GL context loaded (headless unit tests) it is a no-op, leaving texture == 0 so callers fall back instead of panicking.

func (*Image) Width

func (img *Image) Width() int32

Width returns image width

type InstanceData

type InstanceData struct {
	PosX, PosY     float32
	SizeX, SizeY   float32
	Angle          float32
	ColorR, ColorG float32
	ColorB, ColorA float32
	BlendMode      int32
	// contains filtered or unexported fields
}

InstanceData holds per-instance attributes for batched rendering

type KeyMod

type KeyMod int

KeyMod represents modifier key flags

func (KeyMod) AltDown

func (m KeyMod) AltDown() bool

func (KeyMod) ControlDown

func (m KeyMod) ControlDown() bool

func (KeyMod) MetaDown

func (m KeyMod) MetaDown() bool

func (KeyMod) OptionDown

func (m KeyMod) OptionDown() bool

OptionDown is an alias for AltDown. "Option" is the Mac keyboard name for the Alt key; meui code uses both names.

func (KeyMod) ShiftDown

func (m KeyMod) ShiftDown() bool

Modifiers helper methods (unison compatibility).

type Keycode

type Keycode int

Keycode uses USB HID scancode values (subset)

const (
	KeyUnknown    Keycode = 0
	KeyEnter      Keycode = 40
	KeyEscape     Keycode = 41
	KeyBackspace  Keycode = 42
	KeyTab        Keycode = 43
	KeySpace      Keycode = 44
	KeyLeftShift  Keycode = 225
	KeyRightShift Keycode = 229
	KeyLeftCtrl   Keycode = 224
	KeyRightCtrl  Keycode = 228
	KeyLeftAlt    Keycode = 226
	KeyRightAlt   Keycode = 230
	KeyLeftMeta   Keycode = 227
	KeyRightMeta  Keycode = 231
	KeyUp         Keycode = 200
	KeyDown       Keycode = 208
	KeyLeft       Keycode = 203
	KeyRight      Keycode = 205
	KeyA          Keycode = 4
	KeyB          Keycode = 5
	KeyC          Keycode = 6
	KeyD          Keycode = 7
	KeyE          Keycode = 8
	KeyF          Keycode = 9
	KeyG          Keycode = 10
	KeyH          Keycode = 11
	KeyI          Keycode = 12
	KeyJ          Keycode = 13
	KeyK          Keycode = 14
	KeyL          Keycode = 15
	KeyM          Keycode = 16
	KeyN          Keycode = 17
	KeyO          Keycode = 18
	KeyP          Keycode = 19
	KeyQ          Keycode = 20
	KeyR          Keycode = 21
	KeyS          Keycode = 22
	KeyT          Keycode = 23
	KeyU          Keycode = 24
	KeyV          Keycode = 25
	KeyW          Keycode = 26
	KeyX          Keycode = 27
	KeyY          Keycode = 28
	KeyZ          Keycode = 29
	Key0          Keycode = 39
	Key1          Keycode = 30
	Key2          Keycode = 31
	Key3          Keycode = 32
	Key4          Keycode = 33
	Key5          Keycode = 34
	Key6          Keycode = 35
	Key7          Keycode = 36
	Key8          Keycode = 37
	Key9          Keycode = 38
)

type Mat4

type Mat4 [16]float32

Mat4 is a 4x4 column-major matrix for 3D transforms. Layout: [col0, col1, col2, col3] where each col is 4 float32s. Index: row r, col c = m[c*4+r]

func Identity

func Identity() Mat4

Identity returns a 4x4 identity matrix

func LookAt

func LookAt(eye, center, up Vec3) Mat4

LookAt creates a view matrix (camera looking at target)

func Ortho

func Ortho(left, right, bottom, top, near, far float32) Mat4

Ortho creates an orthographic projection matrix

func Perspective

func Perspective(fov, aspect, near, far float32) Mat4

Perspective creates a perspective projection matrix (fov in degrees)

func (Mat4) Inverse

func (m Mat4) Inverse() Mat4

Inverse returns the inverse of a 4x4 matrix using Gauss-Jordan elimination

func (Mat4) Multiply

func (m Mat4) Multiply(b Mat4) Mat4

Multiply returns the matrix product a * b

func (Mat4) Rotate

func (m Mat4) Rotate(angle float32, axis Vec3) Mat4

Rotate returns m * rotation(angle, axis) — angle in degrees, axis normalized

func (Mat4) Scale

func (m Mat4) Scale(v Vec3) Mat4

Scale returns m * scale(sx, sy, sz)

func (Mat4) Transform

func (m Mat4) Transform(v Vec3) Vec3

Transform applies the matrix to a Vec3 (treats as position, w=1)

func (Mat4) Translate

func (m Mat4) Translate(v Vec3) Mat4

Translate returns m * translation(tx, ty, tz)

type Matrix

type Matrix [9]float32

Matrix is a 3x3 affine transformation matrix (row-major) [sx, kx, tx, ky, sy, ty, 0, 0, 1]

func NewMatrix

func NewMatrix() Matrix

NewMatrix creates an identity matrix

func RotateMatrix

func RotateMatrix(degrees float32) Matrix

RotateMatrix creates a rotation matrix (degrees)

func ScaleMatrix

func ScaleMatrix(sx, sy float32) Matrix

ScaleMatrix creates a scale matrix

func SkewMatrix

func SkewMatrix(kx, ky float32) Matrix

SkewMatrix creates a skew matrix (degrees for both axes)

func TranslateMatrix

func TranslateMatrix(tx, ty float32) Matrix

Translate creates a translation matrix

func (Matrix) Concat

func (m Matrix) Concat(other Matrix) Matrix

Concat returns the concatenation of this matrix with another (this * other)

func (Matrix) Multiply

func (m Matrix) Multiply(other Matrix) Matrix

Multiply returns this * other

func (Matrix) Transform

func (m Matrix) Transform(pt Point) Point

Transform transforms a point by this matrix

type Paint

type Paint struct {
	// contains filtered or unexported fields
}

Paint holds drawing style (subset of unison.Paint)

func NewPaint

func NewPaint() *Paint

NewPaint creates a new Paint

func (*Paint) Antialias

func (p *Paint) Antialias() bool

Antialias reports the antialiasing preference (on by default).

func (*Paint) BlendMode

func (p *Paint) BlendMode() BlendMode

BlendMode returns the blend mode

func (*Paint) ClearGradient

func (p *Paint) ClearGradient()

ClearGradient removes any gradient from this paint.

func (*Paint) Color

func (p *Paint) Color() Color

Color returns the paint color

func (*Paint) GlobalAlpha

func (p *Paint) GlobalAlpha() float32

GlobalAlpha returns the alpha multiplier (1 when unset).

func (*Paint) Gradient

func (p *Paint) Gradient() Gradient

Gradient returns the paint's gradient.

func (*Paint) MiterLimit

func (p *Paint) MiterLimit() float32

MiterLimit returns the miter limit (4 when unset).

func (*Paint) SetAntialias

func (p *Paint) SetAntialias(on bool)

SetAntialias turns the SDF pipeline's analytic edge ramp on or off.

func (*Paint) SetBlendMode

func (p *Paint) SetBlendMode(mode BlendMode)

SetBlendMode sets the blend mode

func (*Paint) SetColor

func (p *Paint) SetColor(c Color)

SetColor sets the paint color

func (*Paint) SetConicGradient

func (p *Paint) SetConicGradient(center Point, startAngle float32, stops []GradientStop)

SetConicGradient sets a multi-stop conic gradient sweeping around center from startAngle degrees.

func (*Paint) SetGlobalAlpha

func (p *Paint) SetGlobalAlpha(a float32)

SetGlobalAlpha sets the alpha multiplier applied to everything this paint draws, on top of the colour's own alpha. Values outside 0..1 are clamped; 1 means no modulation.

func (*Paint) SetGradient

func (p *Paint) SetGradient(g Gradient)

SetGradient replaces the paint's gradient wholesale.

func (*Paint) SetLinearGradient

func (p *Paint) SetLinearGradient(start, end Point, stops []GradientStop)

SetLinearGradient sets a multi-stop linear gradient running start→end.

func (*Paint) SetMiterLimit

func (p *Paint) SetMiterLimit(limit float32)

SetMiterLimit sets the miter limit: the longest miter allowed, as a multiple of half the stroke width, before a miter join falls back to a bevel. Values <= 0 mean the conventional default of 4.

func (*Paint) SetRadialGradient

func (p *Paint) SetRadialGradient(center Point, radius float32, stops []GradientStop)

SetRadialGradient sets a multi-stop radial gradient centred at center.

func (*Paint) SetStrokeCap

func (p *Paint) SetStrokeCap(cap StrokeCap)

SetStrokeCap sets the stroke cap

func (*Paint) SetStrokeJoin

func (p *Paint) SetStrokeJoin(join StrokeJoin)

SetStrokeJoin sets the stroke join

func (*Paint) SetStrokeWidth

func (p *Paint) SetStrokeWidth(w float32)

SetStrokeWidth sets the stroke width

func (*Paint) SetStyle

func (p *Paint) SetStyle(style int32)

SetStyle sets the paint style

func (*Paint) StrokeCap

func (p *Paint) StrokeCap() StrokeCap

StrokeCap returns the stroke cap

func (*Paint) StrokeJoin

func (p *Paint) StrokeJoin() StrokeJoin

StrokeJoin returns the stroke join

func (*Paint) StrokeWidth

func (p *Paint) StrokeWidth() float32

StrokeWidth returns the stroke width

func (*Paint) Style

func (p *Paint) Style() PaintStyle

Style returns the paint style

type PaintStyle

type PaintStyle int

PaintStyle defines fill/stroke style

const (
	Fill PaintStyle = iota
	Stroke
	FillStroke
)

type Path

type Path struct {
	// contains filtered or unexported fields
}

Path represents a path with points and verbs

func NewPath

func NewPath() *Path

NewPath creates a new empty path

func (*Path) Bounds

func (p *Path) Bounds() Rect

Bounds returns the path bounds

func (*Path) Close

func (p *Path) Close()

Close closes the current contour

func (*Path) LineTo

func (p *Path) LineTo(pt Point)

LineTo adds a line to the given point

func (*Path) MoveTo

func (p *Path) MoveTo(pt Point)

MoveTo moves to a point (starts new contour)

func (*Path) QuadTo

func (p *Path) QuadTo(ctrl, end Point)

QuadTo adds a quadratic bezier curve

func (*Path) Reset

func (p *Path) Reset()

Reset clears the path

type PathPt

type PathPt struct {
	Verb PathVerb
	Pt   Point
}

PathPt represents a point in a path along with verb

type PathVerb

type PathVerb int

PathVerb represents a path command

const (
	PathMove PathVerb = iota
	PathLine
	PathQuad
	PathCubic
	PathClose
)

type Point

type Point struct {
	X, Y float32
}

Point represents a 2D point (compatible with toolbox/geom.Point)

func NewPoint

func NewPoint(x, y float32) Point

NewPoint creates a new Point

type Rect

type Rect struct {
	X, Y          float32
	Width, Height float32
}

Rect represents a rectangle (compatible with toolbox/geom.Rect)

func NewRect

func NewRect(x, y, w, h float32) Rect

NewRect creates a new Rect

func (Rect) Contains

func (r Rect) Contains(x, y float32) bool

Contains returns true if the point (x, y) is inside the rectangle.

func (Rect) Intersects

func (r Rect) Intersects(other Rect) bool

Intersects returns true if this rectangle overlaps with other.

type RectRenderer

type RectRenderer struct {
	// contains filtered or unexported fields
}

type Renderer

type Renderer interface {
	// Lifecycle
	SetScreenSize(w, h float32)
	ScreenSize() (float32, float32)

	// Frame control
	Present()

	// Surface state
	ClearWithViewport(col uint32, x, y, w, h int32)
	SetViewport(x, y, w, h int32)
	// ScissorState reports the GL scissor box and whether the test is on.
	ScissorState() (x, y, w, h int32, test bool)
	// DrainErrors clears any pending GL error flags.
	DrainErrors()

	// State
	SetBlendMode(mode BlendMode)
	SetScissor(x, y, w, h int32)
	ClearScissor()

	// 2D drawing
	DrawRect(x, y, w, h float32, color Color, angle float32)
	DrawCircle(cx, cy, r float32, color Color)
	DrawOval(x, y, w, h float32, color Color)
	DrawLine(x1, y1, x2, y2 float32, color Color, strokeW float32)
	DrawTriangles(verts []float32, color Color)
	DrawTexturedQuads(verts []float32, texID uint32, color Color, isImage bool)
	// DrawColor fills the whole surface with col, composited with mode.
	DrawColor(col uint32, mode BlendMode)
	// DrawRectStyled is the shaped-rect primitive: fill or stroke, with a
	// corner radius and stroke width. It is the primitive the toolkit's rect
	// drawing actually uses, so it belongs in the contract.
	DrawRectStyled(x, y, w, h, radius, strokeW float32, color Color, style int32, angle float32)
	// Flush emits any pending batched draws, preserving strict draw order.
	Flush()
}

Renderer is the interface that Canvas uses for all GPU operations. Each platform (desktop, Android, iOS) provides its own implementation.

func NewRenderer

func NewRenderer() Renderer

NewRenderer builds the process renderer from the installed factory.

type ShapeRenderer

type ShapeRenderer struct {
	// contains filtered or unexported fields
}

type Size

type Size struct {
	Width, Height float32
}

Size represents width and height

func NewSize

func NewSize(w, h float32) Size

NewSize creates a new Size

type StrokeCap

type StrokeCap int

StrokeCap defines line end style

const (
	StrokeCapButt StrokeCap = iota
	StrokeCapRound
	StrokeCapSquare
)

type StrokeJoin

type StrokeJoin int

StrokeJoin defines line join style

const (
	StrokeJoinMiter StrokeJoin = iota
	StrokeJoinRound
	StrokeJoinBevel
)

type TextRenderer

type TextRenderer struct {
	// contains filtered or unexported fields
}

type Touch

type Touch struct {
	ID       int64
	X, Y     float32
	Pressure float32
}

Touch represents a single touch point

type Vec3

type Vec3 struct {
	X, Y, Z float32
}

Vec3 is a 3D vector/point

func (Vec3) Add

func (v Vec3) Add(o Vec3) Vec3

func (Vec3) Cross

func (v Vec3) Cross(o Vec3) Vec3

func (Vec3) Dot

func (v Vec3) Dot(o Vec3) float32

func (Vec3) Length

func (v Vec3) Length() float32

func (Vec3) Negate

func (v Vec3) Negate() Vec3

func (Vec3) Normalize

func (v Vec3) Normalize() Vec3

func (Vec3) Scale

func (v Vec3) Scale(s float32) Vec3

func (Vec3) Sub

func (v Vec3) Sub(o Vec3) Vec3

type Window

type Window struct {

	// OwnsEventPump: this window's RunFrame drives the global SDL pump
	// (exactly one window per process).
	OwnsEventPump bool
	// contains filtered or unexported fields
}

Window represents a platform window

func GetMainWindow

func GetMainWindow() *Window

GetMainWindow returns the main window instance

func InitWindow

func InitWindow(width, height int32) *Window

InitWindow initializes the main window

func OpenWindowNamed

func OpenWindowNamed(title string, width, height int32) (*Window, error)

OpenWindowNamed opens an ADDITIONAL OS window with its own GL context (sharing the primary renderer state) bound to a fresh mobilegles Window. The renderer must already be initialized (call InitRenderer after the first window exists). Events are routed to this window by SDL windowID; Swap presents this window's buffer.

The window+context are created ON THE PRIMARY'S THREAD via a render task: SDL's share attribute shares with the context current on the CALLING thread, so creation must happen where ctx1 is current. The new context is then bound on THIS (the caller's) thread — its permanent home for the frame loop.

func OpenWindowNamedInline

func OpenWindowNamedInline(title string, width, height int32) (*Window, error)

OpenWindowNamedInline creates an ADDITIONAL window directly on the calling thread, instead of queueing the work onto the primary's task queue and waiting for it the way OpenWindowNamed does.

It must be called on the UI thread, with the primary context current there — which is where App.CreateWindow runs (from main). OpenWindowNamed cannot be used from that thread: it blocks on a task that only that same thread could drain, so it deadlocks. Creating inline also keeps the new context on the UI thread, which is what lets every window be painted from one thread.

func (*Window) Close

func (w *Window) Close()

Close closes the window

func (*Window) Destroy

func (w *Window) Destroy()

Destroy tears down this window's OS surface and GL context and removes it from the registry. Must be called on the window's OWN thread (its context is current there) — i.e., from the window's frame-loop goroutine after the loop exits. A window closed without Destroy leaks its SDL surface and keeps receiving routed events.

func (*Window) Events

func (w *Window) Events() *EventQueue

Events returns the event queue.

func (*Window) Height

func (w *Window) Height() int32

Height returns window height

func (*Window) KeyPressed

func (w *Window) KeyPressed(key int) bool

KeyPressed returns true if the specified key is pressed

func (*Window) MakeCurrent

func (w *Window) MakeCurrent() bool

MakeCurrent binds THIS window's GL context, via osHandle() for the same reason Swap does. Returns false when the bind failed — the caller must skip drawing/swap for this window.

func (*Window) Maximize

func (w *Window) Maximize()

func (*Window) Maximized

func (w *Window) Maximized() bool

Maximized reports whether the OS window is currently maximized.

func (*Window) Minimize

func (w *Window) Minimize()

Minimize/Maximize/Restore drive the OS window state (title-bar buttons).

func (*Window) MouseButtonPressed

func (w *Window) MouseButtonPressed(button int) bool

MouseButtonPressed returns true if the specified mouse button is pressed

func (*Window) MousePos

func (w *Window) MousePos() (float32, float32)

MousePos returns the current mouse position

func (*Window) Poll

func (w *Window) Poll() Event

func (*Window) PollEvents

func (w *Window) PollEvents(handler func(Event)) bool

PollEvents drains all queued events, dispatches to window state, and calls handler for each event. Returns true if any were processed.

func (*Window) PushEvent

func (w *Window) PushEvent(e Event)

PushEvent adds a synthetic event to the window's event queue.

func (*Window) Raise

func (w *Window) Raise()

Raise brings the window to the front of the stacking order.

func (*Window) RegisterTask

func (w *Window) RegisterTask(f func())

RegisterTask queues f to run once on the render thread at the start of the next frame — the safe way to defer work (e.g. opening a new window) out of an event callback.

func (*Window) Restore

func (w *Window) Restore()

func (*Window) RunFrameTasks

func (w *Window) RunFrameTasks()

RunFrameTasks drains per-window deferred tasks and registered event sources — called by render loops that do NOT own the global SDL pump (the dedicated pump goroutine routes SDL events by windowID). RunFrameTasks drains per-window deferred tasks, registered event sources, and — when this window owns the SDL pump — the platform event queue (routed to per-window queues by windowID).

func (*Window) RunPendingTasks

func (w *Window) RunPendingTasks()

RunPendingTasks executes and clears queued render-thread tasks.

func (*Window) SafeArea

func (w *Window) SafeArea() (x, y, width, height int32, ok bool)

SafeArea reports the region of the window that is NOT covered by system UI — a notch, a status bar, a gesture bar, a rounded corner. It is in window coordinates.

ok is false when SDL cannot say (no window, or a platform that does not report one), and the caller must then treat the WHOLE window as safe. That is the right default: insetting on a guess moves content on every device that did not need it.

func (*Window) SetIcon added in v0.1.1

func (w *Window) SetIcon(pixels []uint32, width, height int) bool

SetIcon sets the window icon shown by the window manager and the taskbar. pixels are 0xAARRGGBB, TOP-DOWN, straight (unpremultiplied) alpha, as SDL_PIXELFORMAT_ARGB8888 expects; the caller owns the slice only for the duration of the call (SDL copies the surface).

It returns false when SDL has no window yet or the pixel buffer is short.

func (*Window) SetSize

func (w *Window) SetSize(width, height int32)

SetSize updates the window's logical size (called on resize events so drawing and hit-test geometry track the real OS window size).

func (*Window) SetTextInput

func (w *Window) SetTextInput(active bool, x, y, width, height int32)

SetTextInput turns text input on or off for this window and says where the text is being edited.

area is in window coordinates. A zero area is passed through: on desktop the area is advisory, and on mobile the caller is responsible for having a real one, which is why the seam's callers compute it from the focused widget.

func (*Window) SetTitle

func (w *Window) SetTitle(title string)

SetTitle updates the OS title bar text.

func (*Window) ShouldClose

func (w *Window) ShouldClose() bool

ShouldClose returns whether the window should close

func (*Window) Swap

func (w *Window) Swap()

Swap presents THIS window's back buffer.

It must go through osHandle(), not w.sdl: the PRIMARY window's handle lives in primaryHandle, so testing w.sdl alone sent the primary down the legacy SwapWindow() path, which presents a process-global window rather than its own. In a multi-window session that meant the primary's frames were never presented to the primary's surface — it kept showing one stale frame while other windows presented correctly. (The same nil-w.sdl trap made SetTitle/Raise/window-state no-ops until they were routed through osHandle too.)

func (*Window) TextInputArea

func (w *Window) TextInputArea() (x, y, width, height int32, ok bool)

TextInputArea reports the window's current text-input area as SDL has it, for diagnostics. It returns false when SDL cannot be asked.

func (*Window) ToggleMaximize

func (w *Window) ToggleMaximize()

ToggleMaximize maximizes the window, or restores it when already maximized (title-bar maximize-button semantics).

func (*Window) Width

func (w *Window) Width() int32

Width returns window width

Directories

Path Synopsis
cmd
clipleakprobe command
Command clipleakprobe reproduces the clip/transform state leak recorded as a pre-existing defect in MIGRATION.md ("Known defects carried over", item 1):
Command clipleakprobe reproduces the clip/transform state leak recorded as a pre-existing defect in MIGRATION.md ("Known defects carried over", item 1):
demo command
Command demo is a self-contained visual verification app for the mobilegles renderer module.
Command demo is a self-contained visual verification app for the mobilegles renderer module.
roundrectprobe command
roundrectprobe — does a rotated ROUNDED rect draw its true rotated shape?
roundrectprobe — does a rotated ROUNDED rect draw its true rotated shape?

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址