### Outlay FlowWrap Layout Example Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates the FlowWrap layout manager which wraps items onto the next row or column when horizontal or vertical space runs out. ```Go // From outlay/grid/main.go import "gioui.org/x/outlay" var ( hWrap = outlay.FlowWrap{Axis: layout.Horizontal, Alignment: layout.End} vGrid = outlay.Flow{Num: 11, Axis: layout.Vertical} ) func outlayExamples(gtx layout.Context, th *material.Theme, numItems int) layout.Dimensions { // Horizontal wrap — items flow left-to-right, wrapping to next row. return hWrap.Layout(gtx, numItems, func(gtx layout.Context, i int) layout.Dimensions { return material.Body1(th, fmt.Sprintf("item %d", i)).Layout(gtx) }) // For a fixed-column grid (11 per column), use vGrid.Layout(...) } ``` -------------------------------- ### Color Picker and MuxState Example Source: https://context7.com/~eliasnaur/gio-example/llms.txt Implements a color picker UI and manages multiple color targets using MuxState. Updates the selected color and allows selection from predefined targets. ```Go // From colorpicker/main.go import "gioui.org/x/colorpicker" var ( picker colorpicker.State muxState colorpicker.MuxState current = color.NRGBA{R: 255, G: 128, B: 75, A: 255} ) func colorPickerExample(gtx C, th *material.Theme) D { picker.SetColor(current) muxState = colorpicker.NewMuxState( colorpicker.MuxOption{Label: "current", Value: ¤t}, colorpicker.MuxOption{Label: "background", Value: &th.Palette.Bg}, ) if picker.Update(gtx) { current = picker.Color() } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(colorpicker.PickerStyle{ Label: "Pick a colour", Theme: th, State: &picker, MonospaceFace: "Go Mono", }.Layout), layout.Rigid(colorpicker.Mux(th, &muxState, "Target:").Layout), ) } ``` -------------------------------- ### Handle Pointer Events with pointer.Filter Source: https://context7.com/~eliasnaur/gio-example/llms.txt Register a clip area for pointer events and poll for different kinds of pointer events like Press, Release, and Drag. This example demonstrates drawing a rectangle based on user interaction. ```Go // From galaxy/main.go import ( "gioui.org/io/event" "gioui.org/io/pointer" "gioui.org/op/clip" ) var selected image.Rectangle func pointerHandlerExample(gtx C) D { for { ev, ok := gtx.Event(pointer.Filter{ Target: &selected, Kinds: pointer.Press | pointer.Release | pointer.Drag, }) if !ok { break } if pe, ok := ev.(pointer.Event); ok { pt := image.Pt(int(pe.Position.X), int(pe.Position.Y)) switch pe.Kind { case pointer.Press: selected.Min, selected.Max = pt, pt case pointer.Drag: selected.Max = pt case pointer.Release: fmt.Printf("selected rectangle: %v\n", selected) } } } // Register the clip area so it receives events. pr := clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops) event.Op(gtx.Ops, &selected) pr.Pop() return D{Size: gtx.Constraints.Max} } ``` -------------------------------- ### Apply Affine Transformations with op.Affine Source: https://context7.com/~eliasnaur/gio-example/llms.txt Push a 2D affine transformation onto the op stack to apply translate, rotate, and scale operations. The transformation affects all subsequent drawing calls until popped. This example animates these transformations. ```Go // From kitchen/kitchen.go — transformedKitchen import ( "gioui.org/f32" "gioui.org/op" ) func animatedTransform(gtx layout.Context, dt float32) { angle := dt * 0.1 scale := max(1.0-dt*0.5, 0.5) offset := min(dt*50, 200) tr := f32.Affine2D{} tr = tr.Rotate(f32.Pt(300, 20), -angle) tr = tr.Scale(f32.Pt(300, 20), f32.Pt(scale, scale)) tr = tr.Offset(f32.Pt(0, offset)) op.Affine(tr).Add(gtx.Ops) // All subsequent drawing calls in this frame are transformed. // Request another frame so the animation continues. gtx.Execute(op.InvalidateCmd{}) } ``` -------------------------------- ### Configure Gio Window Options Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates how to configure window properties like title and size using `app.Window.Option`. Custom renderers can also be enabled. ```go package main import ( "gioui.org/app" "gioui.org/unit" ) func configureWindow() { w := new(app.Window) // Set title and size before the loop starts. w.Option( app.Title("My Application"), app.Size(unit.Dp(480), unit.Dp(320)), ) // Enable a custom renderer (e.g., for raw OpenGL access). w.Option(app.CustomRenderer(true)) // Force the window to redraw on the next frame. w.Invalidate() } ``` -------------------------------- ### Minimal Gio Window Source: https://context7.com/~eliasnaur/gio-example/llms.txt Creates a basic Gio window, initializes a Material theme with Go Fonts, and renders a centered label. This is the simplest complete Gio program. ```go package main import ( "image/color" "log" "os" "gioui.org/app" "gioui.org/font/gofont" "gioui.org/op" "gioui.org/text" "gioui.org/widget/material" ) func main() { go func() { w := new(app.Window) if err := loop(w); err != nil { log.Fatal(err) } os.Exit(0) }() app.Main() // blocks; must be called from the main goroutine } func loop(w *app.Window) error { th := material.NewTheme() th.Shaper = text.NewShaper(text.WithCollection(gofont.Collection())) var ops op.Ops for { switch e := w.Event().(type) { case app.DestroyEvent: return e.Err case app.FrameEvent: gtx := app.NewContext(&ops, e) l := material.H1(th, "Hello, Gio") l.Color = color.NRGBA{R: 127, G: 0, B: 0, A: 255} l.Alignment = text.Middle l.Layout(gtx) e.Frame(gtx.Ops) // submit the frame } } } ``` -------------------------------- ### Material Theme and Typography Widgets Source: https://context7.com/~eliasnaur/gio-example/llms.txt Shows how to create a Material Design theme and use typography widgets like H1-H6, Body1, and Caption. These widgets return `material.LabelStyle` for layout. ```go package main import ( "gioui.org/app" "gioui.org/font/gofont" "gioui.org/layout" "gioui.org/op" "gioui.org/text" "gioui.org/widget/material" ) func loop(w *app.Window) error { th := material.NewTheme() th.Shaper = text.NewShaper(text.WithCollection(gofont.Collection())) var ops op.Ops for { switch e := w.Event().(type) { case app.DestroyEvent: return e.Err case app.FrameEvent: gtx := app.NewContext(&ops, e) layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(material.H3(th, "Section Title").Layout), layout.Rigid(material.Body1(th, "Normal body text.").Layout), layout.Rigid(material.Caption(th, "Small caption text.").Layout), ) e.Frame(gtx.Ops) } } } ``` -------------------------------- ### Save Screenshot with Headless Rendering Source: https://context7.com/~eliasnaur/gio-example/llms.txt Creates an off-screen GPU context for rendering and captures it as a PNG image. Requires setting up layout context and theme. ```go // From kitchen/kitchen.go — saveScreenshot import ( "image/png" "gioui.org/gpu/headless" ) func saveScreenshot(filename string) error { const scale = 1.5 sz := image.Point{X: int(800 * scale), Y: int(600 * scale)} w, err := headless.NewWindow(sz.X, sz.Y) if err != nil { return err } gtx := layout.Context{ Ops: new(op.Ops), Metric: unit.Metric{PxPerDp: scale, PxPerSp: scale}, Constraints: layout.Exact(sz), } th := material.NewTheme() th.Shaper = text.NewShaper(text.WithCollection(gofont.Collection())) // Render any widget tree into gtx. material.H1(th, "Screenshot").Layout(gtx) w.Frame(gtx.Ops) img := image.NewRGBA(image.Rectangle{Max: sz}) if err := w.Screenshot(img); err != nil { return err } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { return err } return os.WriteFile(filename, buf.Bytes(), 0o666) // Output: screenshot.png saved to disk } ``` -------------------------------- ### Cross-Platform File Dialogs with Explorer Source: https://context7.com/~eliasnaur/gio-example/llms.txt Provides cross-platform file dialogs for choosing files to read or create/save. Uses `ChooseFile` for read dialogs and `CreateFile` for write dialogs. ```go // From explorer/main.go import "gioui.org/x/explorer" func explorerExample(w *app.Window) { expl := explorer.NewExplorer(w) // In the event loop, forward every event so the explorer can intercept OS callbacks. // expl.ListenEvents(e) // Open an image file (runs in a goroutine to avoid blocking the UI). go func() { file, err := expl.ChooseFile("png", "jpeg", "jpg") if err != nil { log.Printf("open cancelled or failed: %v", err) return } defer file.Close() if f, ok := file.(*explorer.File); ok { log.Printf("URI: %s", f.URI()) } img, format, err := image.Decode(file) _ = img; _ = format; _ = err }() // Save a file. go func() { file, err := expl.CreateFile("output.png") if err != nil { return } defer file.Close() png.Encode(file, someImage) }() // Re-open the last file using its URI string. go func() { file, err := expl.ReadFile("content://...previously-returned-uri...") if err != nil { return } defer file.Close() }() } ``` -------------------------------- ### Material Buttons and Icon Buttons Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates the usage of `material.Button` and `material.IconButton`. Call `btn.Clicked(gtx)` to consume click events. Custom backgrounds can be applied to buttons. ```go var ( button = new(widget.Clickable) greenButton = new(widget.Clickable) iconButton = new(widget.Clickable) green = true icon *widget.Icon ) func kitchenButtons(gtx layout.Context, th *material.Theme) layout.Dimensions { // Create an icon from a Material Design icon vector. // widget.NewIcon returns an error only if the icon data is invalid. ic, _ := widget.NewIcon(icons.ContentAdd) icon = ic return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(func(gtx C) D { return layout.UniformInset(unit.Dp(8)).Layout(gtx, material.IconButton(th, iconButton, icon, "Add").Layout) }), layout.Rigid(func(gtx C) D { // Toggle green/blue label on click. for button.Clicked(gtx) { green = !green } return material.Button(th, button, "Click me!").Layout(gtx) }), layout.Rigid(func(gtx C) D { // Custom background color. btn := material.Button(th, greenButton, "Green") if green { btn.Background = color.NRGBA{A: 0xff, R: 0x9e, G: 0x9d, B: 0x24} } return btn.Layout(gtx) }), ) } ``` -------------------------------- ### Material Checkbox and Switch Source: https://context7.com/~eliasnaur/gio-example/llms.txt Shows how to implement checkboxes and switches using `widget.Bool`. The state of the switch can be used to conditionally disable other widgets. ```go var ( checkbox = new(widget.Bool) swtch = new(widget.Bool) ) func controlWidgets(gtx C, th *material.Theme) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(material.CheckBox(th, checkbox, "Enable transform").Layout), layout.Rigid(func(gtx C) D { return layout.Inset{Left: unit.Dp(16)}.Layout(gtx, material.Switch(th, swtch, "Toggle").Layout) }), layout.Rigid(func(gtx C) D { // Disable a button when switch is off. if !swtch.Value { gtx = gtx.Disabled() } return material.Button(th, new(widget.Clickable), "Enabled when on").Layout(gtx) }), ) } ``` -------------------------------- ### Multi-Window Management with Application Struct Source: https://context7.com/~eliasnaur/gio-example/llms.txt Manages multiple Gio windows using a shared `Application` struct and `context.Context` for coordinated shutdown. Each window runs in its own goroutine. ```go // From multiwindow/main.go type Application struct { Context context.Context Shutdown func() active sync.WaitGroup } func NewApplication(ctx context.Context) *Application { ctx, cancel := context.WithCancel(ctx) return &Application{Context: ctx, Shutdown: cancel} } // NewWindow launches a titled window running the given View in a goroutine. func (a *Application) NewWindow(title string, view View, opts ...app.Option) { a.active.Add(1) go func() { defer a.active.Done() w := &Window{App: a, Window: new(app.Window)} w.Window.Option(append(opts, app.Title(title))...) view.Run(w) }() } func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() go func() { a := NewApplication(ctx) a.NewWindow("Log", NewLog()) a.NewWindow("Letters", NewLetters(log)) a.Wait() // block until all windows are closed os.Exit(0) }() app.Main() } ``` -------------------------------- ### Handle Keyboard Events with key.Filter Source: https://context7.com/~eliasnaur/gio-example/llms.txt Register a clip area as an event target to receive keyboard events. Poll for specific key events like Escape to trigger actions, such as closing the window. ```Go // From 7gui/counter/main.go import ( "gioui.org/io/event" "gioui.org/io/key" "gioui.org/op/clip" ) func keyHandlerExample(gtx layout.Context, w *app.Window) { // Make the entire window area an event target. area := clip.Rect{Max: gtx.Constraints.Max}.Push(gtx.Ops) event.Op(gtx.Ops, w) for { ev, ok := gtx.Event(key.Filter{Name: key.NameEscape}) if !ok { break } if ke, ok := ev.(key.Event); ok && ke.Name == key.NameEscape { w.Perform(system.ActionClose) } } area.Pop() } ``` -------------------------------- ### Animated Tabs with Slide Transition Source: https://context7.com/~eliasnaur/gio-example/llms.txt Implements animated tab transitions using a custom Slider struct that interpolates between widget trees. Clicking tabs triggers slide animations. ```go // From tabs/slider.go type Slider struct { Duration time.Duration push int // ... internal state ... } func (s *Slider) PushLeft() { s.push = 1 } // new content enters from right func (s *Slider) PushRight() { s.push = -1 } // new content enters from left // Usage (from tabs/tabs.go): var ( tabs Tabs slider Slider ) func drawTabs(gtx C, th *material.Theme) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { // Tab bar — clicking a tab calls slider.PushLeft() or PushRight(). return tabs.list.Layout(gtx, len(tabs.tabs), func(gtx C, i int) D { t := &tabs.tabs[i] if t.btn.Clicked(gtx) { if tabs.selected < i { slider.PushLeft() } else { slider.PushRight() } tabs.selected = i } return material.Clickable(gtx, &t.btn, func(gtx C) D { return layout.UniformInset(unit.Dp(12)).Layout(gtx, material.H6(th, t.Title).Layout) }) }) }), layout.Flexed(1, func(gtx C) D { // Slider wraps the content area to animate between tabs. return slider.Layout(gtx, func(gtx C) D { return material.H1(th, fmt.Sprintf("Tab #%d", tabs.selected+1)).Layout(gtx) }) }), ) } ``` -------------------------------- ### Integrating Gio with GLFW for Custom OpenGL Rendering Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates integrating Gio into an existing GLFW window loop for custom OpenGL rendering. Gio's rendering is composited onto the OpenGL framebuffer. ```go // From glfw/main.go — integrating Gio into a GLFW render loop func main() { runtime.LockOSThread() // required by OpenGL threading model glfw.Init() defer glfw.Terminate() glfw.WindowHint(glfw.SRGBCapable, glfw.True) window, _ := glfw.CreateWindow(800, 600, "Gio + GLFW", nil, nil) window.MakeContextCurrent() gl.Init() var queue input.Router var ops op.Ops th := material.NewTheme() th.Shaper = text.NewShaper(text.WithCollection(gofont.Collection())) gpuCtx, _ := gpu.New(gpu.OpenGL{ES: false, Shared: true}) defer gpuCtx.Release() registerCallbacks(window, &queue) // bridge GLFW callbacks → input.Router for !window.ShouldClose() { glfw.PollEvents() scale, _ := window.GetContentScale() width, height := window.GetFramebufferSize() sz := image.Point{X: width, Y: height} ops.Reset() gtx := layout.Context{ Ops: &ops, Now: time.Now(), Source: queue.Source(), Metric: unit.Metric{PxPerDp: scale, PxPerSp: scale}, Constraints: layout.Exact(sz), } drawOpenGL() // raw GL calls below Gio layout.Center.Layout(gtx, material.Button(th, &button, "Button").Layout) gpuCtx.Frame(gtx.Ops, gpu.OpenGLRenderTarget{}, sz) // composite Gio onto GL framebuffer queue.Frame(gtx.Ops) window.SwapBuffers() } } ``` -------------------------------- ### Material Editor Widgets Source: https://context7.com/~eliasnaur/gio-example/llms.txt Shows how to use `material.Editor` for single-line and multi-line text input. For single-line editors with submission, set `SingleLine: true` and `Submit: true`, then read `widget.SubmitEvent` via `editor.Update(gtx)`. ```go var ( editor = new(widget.Editor) lineEditor = &widget.Editor{SingleLine: true, Submit: true} ) func editorExample(gtx layout.Context, th *material.Theme) layout.Dimensions { // Poll submit events from the single-line editor. for { e, ok := lineEditor.Update(gtx) if !ok { break } if e, ok := e.(widget.SubmitEvent); ok { fmt.Println("submitted:", e.Text) lineEditor.SetText("") } } return layout.Flex{Axis: layout.Vertical}.Layout(gtx, // Multi-line editor capped at 200 dp tall. layout.Rigid(func(gtx C) D { gtx.Constraints.Max.Y = gtx.Dp(unit.Dp(200)) return material.Editor(th, editor, "Type here...").Layout(gtx) }), // Single-line editor with a visible border. layout.Rigid(func(gtx C) D { border := widget.Border{ Color: color.NRGBA{A: 0xff}, CornerRadius: unit.Dp(8), Width: unit.Dp(2), } return border.Layout(gtx, func(gtx C) D { return layout.UniformInset(unit.Dp(8)).Layout(gtx, material.Editor(th, lineEditor, "Press Enter to submit").Layout) }) }), ) } ``` -------------------------------- ### Bidirectional Text Handling in Editor Source: https://context7.com/~eliasnaur/gio-example/llms.txt Shows how `widget.Editor` natively handles Unicode bidirectional text. Alignment can be set, and LTR/RTL content can be mixed. ```go // From bidi/bidi.go func bidiExample(gtx C, th *material.Theme) D { var ed widget.Editor ed.SetText("Hello أهلا my good friend صديقي الجيد bidirectional text نص ثنائي الاتجاه.") ed.Alignment = text.Middle // Focus the editor programmatically on first frame. gtx.Execute(key.FocusCmd{Tag: &ed}) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { med := material.Editor(th, &ed, "") med.TextSize = material.H3(th, "").TextSize return med.Layout(gtx) }), layout.Rigid(func(gtx C) D { start, end := ed.Selection() return material.Body1(th, fmt.Sprintf("Selection: %d–%d", start, end)).Layout(gtx) }), ) } ``` -------------------------------- ### Use Paint Operations for Drawing Source: https://context7.com/~eliasnaur/gio-example/llms.txt Utilize Gio's drawing primitives like `paint.FillShape`, `paint.LinearGradientOp`, and `paint.PushOpacity` to record paint operations. These operations are then executed by Gio's renderer. ```Go // From kitchen/kitchen.go and opacity/main.go import ( "gioui.org/op/clip" "gioui.org/op/paint" "gioui.org/f32" ) func paintExamples(gtx layout.Context) { dr := image.Rectangle{Max: gtx.Constraints.Min} // Solid fill. paint.FillShape(gtx.Ops, color.NRGBA{R: 0xff, A: 0xff}, clip.Rect(dr).Op()) // Linear gradient (green → blue). paint.LinearGradientOp{ Stop1: layout.FPt(dr.Min), Stop2: layout.FPt(dr.Max), Color1: color.NRGBA{G: 0xff, A: 0xff}, Color2: color.NRGBA{B: 0xff, A: 0xff}, }.Add(gtx.Ops) defer clip.Rect(dr).Push(gtx.Ops).Pop() paint.PaintOp{}.Add(gtx.Ops) // Opacity layer — multiply all alpha of children by 0.5. defer paint.PushOpacity(gtx.Ops, 0.5).Pop() // Children drawn here are at 50% opacity. } ``` -------------------------------- ### Flex Layout: Arranging children along an axis Source: https://context7.com/~eliasnaur/gio-example/llms.txt layout.Flex arranges children along a specified axis. layout.Rigid uses natural size, while layout.Flexed distributes remaining space proportionally. ```go // From 7gui/counter/main.go func flexExample(gtx layout.Context, th *material.Theme) layout.Dimensions { return layout.Flex{ Axis: layout.Horizontal, Alignment: layout.Middle, }.Layout(gtx, // Fixed-size label occupying half the width. layout.Flexed(1, func(gtx layout.Context) layout.Dimensions { return layout.Center.Layout(gtx, material.Body1(th, "Count: 42").Layout) }), // Spacer between children. layout.Rigid(layout.Spacer{Width: unit.Dp(10)}.Layout), // Button occupying the other half. layout.Flexed(1, func(gtx layout.Context) layout.Dimensions { return material.Button(th, new(widget.Clickable), "Increment").Layout(gtx) }), ) } ``` -------------------------------- ### Progress Indicators: ProgressBar, ProgressCircle, Loader Source: https://context7.com/~eliasnaur/gio-example/llms.txt These widgets display progress using a float32 value between 0 and 1. Loader is an indeterminate spinner. ```go // From kitchen/kitchen.go var progress = float32(0) func progressWidgets(gtx C, th *material.Theme) D { return layout.Flex{Axis: layout.Vertical}.Layout(gtx, // Horizontal progress bar. layout.Rigid(material.ProgressBar(th, progress).Layout), // Circular progress indicator inside a flex row. layout.Rigid(func(gtx C) D { return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Rigid(material.ProgressCircle(th, progress).Layout), layout.Rigid(func(gtx C) D { return layout.Inset{Left: unit.Dp(16)}.Layout(gtx, // Indeterminate spinner. material.Loader(th).Layout) }), ) }), ) } ``` -------------------------------- ### Asynchronous Timer with UI Invalidation Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates running background work in a goroutine and updating the UI by calling `w.Invalidate()` when state changes. Uses a channel to signal updates. ```go // From 7gui/timer/timer.go type Timer struct { Updated chan struct{} // UI listens on this channel mu sync.Mutex start time.Time now time.Time duration time.Duration } func NewTimer(initialDuration time.Duration) *Timer { return &Timer{ Updated: make(chan struct{}), duration: initialDuration, } } // Start launches the ticker goroutine; returns a cancel func. func (t *Timer) Start() context.CancelFunc { now := time.Now() t.now, t.start = now, now done := make(chan struct{}) go t.run(done) return func() { close(done) } } // In the UI goroutine: func (ui *UI) Run(w *app.Window) error { closeTimer := ui.Timer.Start() defer closeTimer() go func() { for range ui.Timer.Updated { w.Invalidate() // trigger a repaint } }() // ... normal event loop ... } ``` -------------------------------- ### Virtualized Scrollable Grid Layout Source: https://context7.com/~eliasnaur/gio-example/llms.txt Renders a virtualized 2D grid where only visible cells are drawn. Supports independent row/column sizing and custom cell painting. ```Go // From color-grid/colorgrid.go and fps-table/table.go import "gioui.org/x/component" var grid component.GridState func gridExample(gtx C, th *material.Theme) D { sideLength := 1000 cellSize := unit.Dp(10) return component.Grid(th, &grid).Layout(gtx, sideLength, sideLength, // Size function: same dp for every row/column. func(axis layout.Axis, index, constraint int) int { return gtx.Dp(cellSize) }, // Cell painter. func(gtx C, row, col int) D { c := color.NRGBA{ R: uint8(3 * row), G: uint8(5 * col), B: uint8(row * col), A: 255, } paint.FillShape(gtx.Ops, c, clip.Rect{Max: gtx.Constraints.Max}.Op()) return D{Size: gtx.Constraints.Max} }, ) } ``` -------------------------------- ### Scrollable List: Virtual scrolling with Material scrollbar Source: https://context7.com/~eliasnaur/gio-example/llms.txt layout.List handles virtual scrolling, widget.List manages scroll state, and material.List adds a Material-styled scrollbar. ```go // From gophers/ui.go and kitchen/kitchen.go var list = &widget.List{ List: layout.List{Axis: layout.Vertical}, } func scrollableList(gtx layout.Context, th *material.Theme, items []string) layout.Dimensions { return material.List(th, list).Layout(gtx, len(items), func(gtx C, i int) D { return layout.UniformInset(unit.Dp(12)).Layout(gtx, material.Body1(th, items[i]).Layout) }) } // Expected output: a vertically scrollable list with a Material scrollbar. ``` -------------------------------- ### Conway's Game of Life UI Loop Source: https://context7.com/~eliasnaur/gio-example/llms.txt Manages the UI event loop and game state updates for Conway's Game of Life. It uses a timed goroutine to advance the simulation and requests repaints asynchronously. ```go func (ui *UI) Run(w *app.Window) error { var ops op.Ops advanceBoard := time.NewTicker(time.Second / 3) defer advanceBoard.Stop() events := make(chan event.Event) acks := make(chan struct{}) go func() { for { ev := w.Event() events <- ev <-acks if _, ok := ev.(app.DestroyEvent); ok { return } } }() for { select { case e := <-events: switch e := e.(type) { case app.FrameEvent: gtx := app.NewContext(&ops, e) ui.Layout(gtx) e.Frame(gtx.Ops) case app.DestroyEvent: acks <- struct{}{} return e.Err } acks <- struct{}{} case <-advanceBoard.C: ui.Board.Advance() // update game state w.Invalidate() // request repaint } } } ``` -------------------------------- ### Stack Layout: Overlapping children Source: https://context7.com/~eliasnaur/gio-example/llms.txt layout.Stack draws children on top of each other. layout.Expanded stretches to fill, while layout.Stacked uses natural size. ```go // Pattern from gophers/ui.go func stackExample(gtx layout.Context, th *material.Theme) layout.Dimensions { return layout.Stack{Alignment: layout.SE}.Layout(gtx, // Background fills entire area. layout.Expanded(func(gtx C) D { paint.Fill(gtx.Ops, color.NRGBA{R: 0xf2, G: 0xf2, B: 0xf2, A: 0xff}) return layout.Dimensions{Size: gtx.Constraints.Max} }), // Content scrollable list. layout.Expanded(func(gtx C) D { return material.Body1(th, "Content here").Layout(gtx) }), // Floating action button pinned to SE corner. layout.Stacked(func(gtx C) D { return layout.UniformInset(unit.Dp(16)).Layout(gtx, func(gtx C) D { ic, _ := widget.NewIcon(icons.ContentSend) return material.IconButton(th, new(widget.Clickable), ic, "FAB").Layout(gtx) }) }), ) } ``` -------------------------------- ### Material Radio Buttons Source: https://context7.com/~eliasnaur/gio-example/llms.txt Demonstrates the use of `material.RadioButton` with `widget.Enum` to manage a group of radio buttons. The selected value can be checked against the group's `Value` property. ```go var ( radioButtonsGroup = new(widget.Enum) ) func radioButtons(gtx C, th *material.Theme) D { return layout.Flex{}.Layout(gtx, layout.Rigid(material.RadioButton(th, radioButtonsGroup, "r1", "Option 1").Layout), layout.Rigid(material.RadioButton(th, radioButtonsGroup, "r2", "Option 2").Layout), layout.Rigid(material.RadioButton(th, radioButtonsGroup, "r3", "Option 3").Layout), ) // Read selected value: radioButtonsGroup.Value == "r1" | "r2" | "r3" } ``` -------------------------------- ### Render Markdown to Rich Text Spans Source: https://context7.com/~eliasnaur/gio-example/llms.txt Converts Markdown bytes to richtext.SpanStyle for interactive layout. Handles rich text interactions like clicking on URLs. ```Go // From markdown/main.go import ( "gioui.org/x/markdown" "gioui.org/x/richtext" "github.com/inkeliz/giohyperlink" ) type UI struct { Renderer *markdown.Renderer Editor widget.Editor TextState richtext.InteractiveText cache []richtext.SpanStyle } func (ui *UI) Update(gtx C) { // Re-render markdown when the editor content changes. for { ev, ok := ui.Editor.Update(gtx) if !ok { break } if _, ok := ev.(widget.ChangeEvent); ok { ui.cache, _ = ui.Renderer.Render([]byte(ui.Editor.Text())) } } // Handle rich text interactions. for { span, event, ok := ui.TextState.Update(gtx) if !ok { break } if event.Type == richtext.Click { if url, ok := span.Get(markdown.MetadataURL).(string); ok { giohyperlink.Open(url) // open URL in system browser } } } } func (ui *UI) layoutRendered(gtx C) D { return richtext.Text(&ui.TextState, ui.Theme.Shaper, ui.cache...).Layout(gtx) } ``` -------------------------------- ### Slider Widget: Float value and Material Slider Source: https://context7.com/~eliasnaur/gio-example/llms.txt widget.Float stores a value between 0 and 1, and material.Slider renders it as a draggable track. Call float.Update(gtx) to detect user changes. ```go // From 7gui/timer/main.go and kitchen/kitchen.go var duration widget.Float func sliderExample(gtx C, th *material.Theme) D { // Detect changes during this frame. if duration.Update(gtx) { fmt.Printf("slider changed to %.2f\n", duration.Value) } return layout.Flex{Alignment: layout.Middle}.Layout(gtx, layout.Flexed(1, material.Slider(th, &duration).Layout), layout.Rigid(func(gtx C) D { return layout.UniformInset(unit.Dp(8)).Layout(gtx, material.Body1(th, fmt.Sprintf("%.2f", duration.Value)).Layout) }), ) } ``` -------------------------------- ### Galaxy N-Body Simulation Star Rendering Source: https://context7.com/~eliasnaur/gio-example/llms.txt Renders a single star in the Galaxy N-Body simulation. It scales the star's position within the viewport and colors it based on its speed. ```go // Star.Layout renders one simulated star at its scaled position. func (s Star) Layout(gtx layout.Context, view *viewport) layout.Dimensions { if view != nil { // Skip stars outside the current viewport. if s.X < view.offset.X || s.X > view.offset.X+view.size.X { return D{} } // Re-scale X,Y to [0,1] within the viewport. s.X = (s.X - view.offset.X) / view.size.X s.Y = (s.Y - view.offset.Y) / view.size.Y } px := gtx.Dp(s.Size) rr := px / 2 x := s.X*float32(gtx.Constraints.Max.X) - float32(rr) y := s.Y*float32(gtx.Constraints.Max.Y) - float32(rr) defer op.Affine(f32.Affine2D{}.Offset(f32.Pt(x, y))).Push(gtx.Ops).Pop() // Color encodes speed: red=slow, blue=fast. fill := color.NRGBA{R: 255 - uint8(255*s.Speed), B: uint8(255*s.Speed), A: 50} rect := image.Rectangle{Max: image.Pt(px, px)} paint.FillShape(gtx.Ops, fill, clip.UniformRRect(rect, rr).Op(gtx.Ops)) return D{} } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.