~pierrec/giox

325c427d9fdc65a6fd70bba44a7d4882263759b6 — pierre 9 months ago e20d066
added new eventx package

Signed-off-by: pierre <pierre.curto@gmail.com>
1 files changed, 53 insertions(+), 0 deletions(-)

A eventx/eventx.go
A eventx/eventx.go => eventx/eventx.go +53 -0
@@ 0,0 1,53 @@
package eventx

import (
	"gioui.org/io/event"
	"gioui.org/layout"
)

// Queue implements an op.Queue that collects all events from a composite
// widget components and make them available when collecting events for that
// composite.
//
// It can be used to catch specific keys in a widget.Editor for instance,
// such as the ESC key to unfocus the editor.
type Queue struct {
	source    event.Queue
	composite event.Tag
	tags      []queueItem
}

type queueItem struct {
	tag    event.Tag
	events []event.Event
}

// Init returns a context suitable for composite widget events collection.
func (q *Queue) Init(gtx layout.Context, composite event.Tag) layout.Context {
	q.source = gtx.Queue
	q.composite = composite
	gtx.Queue = q
	return gtx
}

// Events returns events for the tag. If the tag is the composite widget,
// then its events are completed with all of the events from its components.
func (q *Queue) Events(tag event.Tag) []event.Event {
	evs := q.source.Events(tag)
	if tag == q.composite {
		// Return all events for the composite registered tags and clear them.
		for i, item := range q.tags {
			evs = append(evs, item.events...)
			q.tags[i].events = nil
		}
		return evs
	}
	for i, item := range q.tags {
		if item.tag == tag {
			q.tags[i].events = evs
			return evs
		}
	}
	q.tags = append(q.tags, queueItem{tag: tag, events: evs})
	return evs
}