~whereswaldon/gio-x

854264d921996f4fc02d3857f67db0bb8053158f — Chris Waldon 6 months ago f4217a3
debug: add global helpers with automagic state management

This commit adds two global functions that can use any unique tag to store the
constraint editor state in a map, making it much easier for layout authors to
insert ad-hoc constraint editors into their code.

Signed-off-by: Chris Waldon <christopher.waldon.dev@gmail.com>
1 files changed, 43 insertions(+), 0 deletions(-)

M debug/debug.go
M debug/debug.go => debug/debug.go +43 -0
@@ 4,6 4,7 @@ package debug
import (
	"image"
	"image/color"
	"sync"

	"gioui.org/f32"
	"gioui.org/gesture"


@@ 16,6 17,47 @@ import (
	"gioui.org/unit"
)

var (
	mapLock  sync.RWMutex
	stateMap map[any]*ConstraintEditor
)

func init() {
	mapLock.Lock()
	defer mapLock.Unlock()
	stateMap = make(map[any]*ConstraintEditor)
}

func getTag(tag any) *ConstraintEditor {
	var state *ConstraintEditor
	func() {
		mapLock.RLock()
		defer mapLock.RUnlock()
		state = stateMap[tag]
	}()
	if state == nil {
		mapLock.Lock()
		defer mapLock.Unlock()
		state = &ConstraintEditor{}
		stateMap[tag] = state
	}
	return state
}

// Wrap wraps w with a [debug.ConstraintEditor]. The state for the constraint
// editor is stored automatically using the unique tag provided. Note: the state
// will never be deleted.
func Wrap(tag any, w layout.Widget) layout.Widget {
	return getTag(tag).Wrap(w)
}

// Layout wraps w with a [debug.ConstraintEditor]. The state for the constraint
// editor is stored automatically using the unique tag provided. Note: the state
// will never be deleted.
func Layout(gtx layout.Context, tag any, w layout.Widget) layout.Dimensions {
	return getTag(tag).Layout(gtx, w)
}

// dragBox holds state for a draggable, hoverable rectangle with drag that can
// accumulate.
type dragBox struct {


@@ 30,6 72,7 @@ type dragBox struct {
func (d *dragBox) Add(ops *op.Ops) {
	d.drag.Add(ops)
	d.hover.Add(ops)
	pointer.CursorSouthEastResize.Add(ops)
}

// Update processes events from the queue using the given metric and updates the