Debian Codegraph @

shiny/widget/node/node.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package node provides the structure for a tree of heterogeneous widget nodes.
6 //
7 // Most programmers should not need to import this package, only the top-level
8 // widget package. Only those that write custom widgets need to explicitly
9 // refer to the Node, Embed and related types.
10 //
11 // The Node interface is usually implemented by struct types that embed one of
12 // LeafEmbed, ShellEmbed or ContainerEmbed (all of which themselves embed an
13 // Embed), providing default implementations of all of Node's methods.
14 //
15 // The split between an outer wrapper (Node) interface type and an inner
16 // wrappee (Embed) struct type enables heterogeneous nodes, such as a buttons
17 // and labels, in a widget tree where every node contains common fields such as
18 // position, size and tree structure links (parent, siblings and children).
19 //
20 // In a traditional object-oriented type system, this might be represented by
21 // the Button and Label types both subclassing the Node type. Go does not have
22 // inheritance, so the outer / inner split is composed explicitly. For example,
23 // the concrete Button type is a struct type that embeds an XxxEmbed (such as
24 // LeafEmbed), and the NewButton function sets the inner Embed's Wrapper field
25 // to point back to the outer value.
26 //
27 // There are three layers here (Button embeds LeafEmbed embeds Embed) instead
28 // of two. The intermediate layer exists because there needs to be a place to
29 // provide default implementations of methods like Measure, but that place
30 // shouldn't be the inner-most type (Embed), otherwise it'd be too easy to
31 // write subtly incorrect code like:
32 //
33 // for c := w.FirstChild; c != nil; c = c.NextSibling {
34 // c.Measure(etc) // This should instead be c.Wrapper.Measure(etc).
35 // }
36 //
37 // In any case, most programmers that want to construct a widget tree should
38 // not need to know this detail. It usually suffices to call functions such as
39 // widget.NewButton or widget.NewLabel, and then parent.Insert(button, nil).
40 //
41 // See the example/gallery program for some example code for a custom widget.
42 package node // import "golang.org/x/exp/shiny/widget/node"
43
44 import (
45 "image"
46
47 "golang.org/x/exp/shiny/gesture"
48 "golang.org/x/exp/shiny/screen"
49 "golang.org/x/exp/shiny/widget/theme"
50 "golang.org/x/image/math/f64"
51 "golang.org/x/mobile/event/lifecycle"
52 "golang.org/x/mobile/event/mouse"
53 )
54
55 // EventHandled is whether or not an input event (a key, mouse, touch or
56 // gesture event) was handled by a widget. If it was not handled, the event is
57 // propagated along the widget tree.
58 type EventHandled bool
59
60 const (
61 NotHandled = EventHandled(false)
62 Handled = EventHandled(true)
63 )
64
65 // NoHint means that there is no width or height hint in a Measure call.
66 const NoHint = -1
67
68 // Node is a node in the widget tree.
69 type Node interface {
70 // Wrappee returns the inner (embedded) type that is wrapped by this type.
71 Wrappee() *Embed
72
73 // Insert adds a node c as a child of this node. If nextSibling is nil, c
74 // will be inserted at the end of this node's children. Otherwise, c will
75 // be inserted such that its next sibling is nextSibling.
76 //
77 // It will panic if c already has a parent or siblings.
78 Insert(c, nextSibling Node)
79
80 // Remove removes a node c that is a child of this node. Afterwards, c will
81 // have no parent and no siblings.
82 //
83 // It will panic if c's parent is not this node.
84 Remove(c Node)
85
86 // Measure sets this node's Embed.MeasuredSize to its natural size, taking
87 // its children into account.
88 //
89 // Some nodes' natural height might depend on their imposed width, such as
90 // a text widget word-wrapping its contents. The caller may provide hints
91 // that the parent can override the child's natural size in the width,
92 // height or both directions. A negative value means that there is no hint.
93 // For example, a container might lay out its children to all have the same
94 // width, and could pass that width as the widthHint argument.
95 Measure(t *theme.Theme, widthHint, heightHint int)
96
97 // Layout lays out this node (and its children), setting the Embed.Rect
98 // fields of each child. This node's Embed.Rect field should have
99 // previously been set during the parent node's layout.
100 Layout(t *theme.Theme)
101
102 // Paint paints this node (and its children). Painting is split into two
103 // passes: a base pass and an effects pass. The effects pass is often a
104 // no-op, and the bulk of the work is typically done in the base pass.
105 //
106 // The base pass paints onto an *image.RGBA pixel buffer and ancestor nodes
107 // may choose to re-use the result. For example, re-painting a text widget
108 // after scrolling may copy cached buffers at different offsets, instead of
109 // painting the text's glyphs onto a fresh buffer. Similarly, animating the
110 // scale and opacity of an overlay can re-use the buffer from a previous
111 // base pass.
112 //
113 // The effects pass paints that part of the widget that can not or should
114 // not be cached. For example, the border of a text widget shouldn't move
115 // on the screen when that text widget is scrolled. The effects pass does
116 // not have a destination RGBA pixel buffer, and is limited to what a
117 // screen.Drawer provides: affine-transformed textures and uniform fills.
118 //
119 // TODO: app-specific OpenGL, if available, should be part of the effects
120 // pass. Is that exposed via the screen.Drawer or by another mechanism?
121 //
122 // The Paint method may create base pass RGBA pixel buffers, by calling
123 // ctx.Screen.NewBuffer. Many implementations won't, and instead assume
124 // that PaintBase is recursively triggered by an ancestor node such as a
125 // widget.Sheet. If it does create those RGBA pixel buffers, it is also
126 // responsible for calling PaintBase on this node (and its children). In
127 // any case, the Paint method should then paint any effects. Many widgets
128 // will neither create their own buffers nor have any effects, so their
129 // Paint methods will simply be the default implementation: do nothing except
130 // call Paint on its children. As mentioned above, the bulk of the work is
131 // typically done in PaintBase.
132 //
133 // origin is the parent widget's origin with respect to the ctx.Src2Dst
134 // transformation matrix; this node's Embed.Rect.Add(origin) will be its
135 // position and size in pre-transformed coordinate space.
136 Paint(ctx *PaintContext, origin image.Point) error
137
138 // PaintBase paints the base pass of this node (and its children) onto an
139 // RGBA pixel buffer.
140 //
141 // origin is the parent widget's origin with respect to the ctx.Dst image's
142 // origin; this node's Embed.Rect.Add(origin) will be its position and size
143 // in ctx.Dst's coordinate space.
144 PaintBase(ctx *PaintBaseContext, origin image.Point) error
145
146 // Mark adds the given marks to this node. It calls OnChildMarked on its
147 // parent if new marks were added.
148 Mark(m Marks)
149
150 // OnChildMarked handles a child being given new marks. By default, marks
151 // are propagated up the node tree towards the root. For example, a child
152 // being marked for needing paint will cause the parent being marked for
153 // needing paint.
154 OnChildMarked(child Node, newMarks Marks)
155
156 // OnLifecycleEvent propagates a lifecycle event to a node (and its
157 // children).
158 OnLifecycleEvent(e lifecycle.Event)
159
160 // OnInputEvent handles a key, mouse, touch or gesture event.
161 //
162 // origin is the parent widget's origin with respect to the event origin;
163 // this node's Embed.Rect.Add(origin) will be its position and size in
164 // event coordinate space.
165 OnInputEvent(e interface{}, origin image.Point) EventHandled
166
167 // TODO: other OnXxxEvent methods?
168
169 }
170
171 // PaintContext is the context for the Node.Paint method.
172 type PaintContext struct {
173 Theme *theme.Theme
174 Screen screen.Screen
175 Drawer screen.Drawer
176 Src2Dst f64.Aff3
177
178 // TODO: add a clip rectangle?
179
180 // TODO: add the DrawContext from the lifecycle event?
181 }
182
183 // PaintBaseContext is the context for the Node.PaintBase method.
184 type PaintBaseContext struct {
185 Theme *theme.Theme
186 Dst *image.RGBA
187
188 // TODO: add a clip rectangle? Or rely on the RGBA.SubImage method to pass
189 // smaller Dst images?
190 }
191
192 // LeafEmbed is designed to be embedded in struct types for nodes with no
193 // children.
194 type LeafEmbed struct{ Embed }
195
196 func (m *LeafEmbed) Insert(c, nextSibling Node) {
197 panic("node: Insert called for a leaf parent")
198 }
199
200 func (m *LeafEmbed) Remove(c Node) { m.remove(c) }
201
202 func (m *LeafEmbed) Measure(t *theme.Theme, widthHint, heightHint int) {
203 m.MeasuredSize = image.Point{}
204 }
205
206 func (m *LeafEmbed) Layout(t *theme.Theme) {}
207
208 func (m *LeafEmbed) Paint(ctx *PaintContext, origin image.Point) error {
209 m.Marks.UnmarkNeedsPaint()
210 return nil
211 }
212
213 func (m *LeafEmbed) PaintBase(ctx *PaintBaseContext, origin image.Point) error {
214 m.Marks.UnmarkNeedsPaintBase()
215 return nil
216 }
217
218 func (m *LeafEmbed) OnChildMarked(child Node, newMarks Marks) {}
219
220 func (m *LeafEmbed) OnLifecycleEvent(e lifecycle.Event) {}
221
222 func (m *LeafEmbed) OnInputEvent(e interface{}, origin image.Point) EventHandled { return NotHandled }
223
224 // ShellEmbed is designed to be embedded in struct types for nodes with at most
225 // one child.
226 type ShellEmbed struct{ Embed }
227
228 func (m *ShellEmbed) Insert(c, nextSibling Node) {
229 if m.FirstChild != nil {
230 panic("node: Insert called for a shell parent that already has a child")
231 }
232 m.insert(c, nextSibling)
233 }
234
235 func (m *ShellEmbed) Remove(c Node) { m.remove(c) }
236
237 func (m *ShellEmbed) Measure(t *theme.Theme, widthHint, heightHint int) {
238 if c := m.FirstChild; c != nil {
239 c.Wrapper.Measure(t, widthHint, heightHint)
240 m.MeasuredSize = c.MeasuredSize
241 } else {
242 m.MeasuredSize = image.Point{}
243 }
244 }
245
246 func (m *ShellEmbed) Layout(t *theme.Theme) {
247 if c := m.FirstChild; c != nil {
248 c.Rect = m.Rect.Sub(m.Rect.Min)
249 c.Wrapper.Layout(t)
250 }
251 }
252
253 func (m *ShellEmbed) Paint(ctx *PaintContext, origin image.Point) error {
254 m.Marks.UnmarkNeedsPaint()
255 if c := m.FirstChild; c != nil {
256 return c.Wrapper.Paint(ctx, origin.Add(m.Rect.Min))
257 }
258 return nil
259 }
260
261 func (m *ShellEmbed) PaintBase(ctx *PaintBaseContext, origin image.Point) error {
262 m.Marks.UnmarkNeedsPaintBase()
263 if c := m.FirstChild; c != nil {
264 return c.Wrapper.PaintBase(ctx, origin.Add(m.Rect.Min))
265 }
266 return nil
267 }
268
269 func (m *ShellEmbed) OnChildMarked(child Node, newMarks Marks) {
270 m.Mark(newMarks)
271 }
272
273 func (m *ShellEmbed) OnLifecycleEvent(e lifecycle.Event) {
274 if c := m.FirstChild; c != nil {
275 c.Wrapper.OnLifecycleEvent(e)
276 }
277 }
278
279 func (m *ShellEmbed) OnInputEvent(e interface{}, origin image.Point) EventHandled {
280 if c := m.FirstChild; c != nil {
281 return c.Wrapper.OnInputEvent(e, origin.Add(m.Rect.Min))
282 }
283 return NotHandled
284 }
285
286 // ContainerEmbed is designed to be embedded in struct types for nodes with any
287 // number of children.
288 type ContainerEmbed struct{ Embed }
289
290 func (m *ContainerEmbed) Insert(c, nextSibling Node) { m.insert(c, nextSibling) }
291
292 func (m *ContainerEmbed) Remove(c Node) { m.remove(c) }
293
294 func (m *ContainerEmbed) Measure(t *theme.Theme, widthHint, heightHint int) {
295 mSize := image.Point{}
296 for c := m.FirstChild; c != nil; c = c.NextSibling {
297 c.Wrapper.Measure(t, NoHint, NoHint)
298 if mSize.X < c.MeasuredSize.X {
299 mSize.X = c.MeasuredSize.X
300 }
301 if mSize.Y < c.MeasuredSize.Y {
302 mSize.Y = c.MeasuredSize.Y
303 }
304 }
305 m.MeasuredSize = mSize
306 }
307
308 func (m *ContainerEmbed) Layout(t *theme.Theme) {
309 for c := m.FirstChild; c != nil; c = c.NextSibling {
310 c.Rect = image.Rectangle{Max: c.MeasuredSize}
311 c.Wrapper.Layout(t)
312 }
313 }
314
315 func (m *ContainerEmbed) Paint(ctx *PaintContext, origin image.Point) error {
316 m.Marks.UnmarkNeedsPaint()
317 origin = origin.Add(m.Rect.Min)
318 for c := m.FirstChild; c != nil; c = c.NextSibling {
319 if err := c.Wrapper.Paint(ctx, origin); err != nil {
320 return err
321 }
322 }
323 return nil
324 }
325
326 func (m *ContainerEmbed) PaintBase(ctx *PaintBaseContext, origin image.Point) error {
327 m.Marks.UnmarkNeedsPaintBase()
328 origin = origin.Add(m.Rect.Min)
329 for c := m.FirstChild; c != nil; c = c.NextSibling {
330 if err := c.Wrapper.PaintBase(ctx, origin); err != nil {
331 return err
332 }
333 }
334 return nil
335 }
336
337 func (m *ContainerEmbed) OnChildMarked(child Node, newMarks Marks) {
338 m.Mark(newMarks)
339 }
340
341 func (m *ContainerEmbed) OnLifecycleEvent(e lifecycle.Event) {
342 for c := m.FirstChild; c != nil; c = c.NextSibling {
343 c.Wrapper.OnLifecycleEvent(e)
344 }
345 }
346
347 func (m *ContainerEmbed) OnInputEvent(e interface{}, origin image.Point) EventHandled {
348 origin = origin.Add(m.Rect.Min)
349 var p image.Point
350 switch e := e.(type) {
351 case gesture.Event:
352 p = image.Point{
353 X: int(e.CurrentPos.X) - origin.X,
354 Y: int(e.CurrentPos.Y) - origin.Y,
355 }
356 case mouse.Event:
357 p = image.Point{
358 X: int(e.X) - origin.X,
359 Y: int(e.Y) - origin.Y,
360 }
361 }
362 // Iterate backwards. Later children have priority over earlier children,
363 // as later ones are usually drawn over earlier ones.
364 for c := m.LastChild; c != nil; c = c.PrevSibling {
365 if p.In(c.Rect) && c.Wrapper.OnInputEvent(e, origin) == Handled {
366 return Handled
367 }
368 }
369 return NotHandled
370 }
371
372 // Embed is the common data structure for each node in a widget tree.
373 type Embed struct {
374 // Wrapper is the outer type that wraps (embeds) this type. It should not
375 // be nil.
376 Wrapper Node
377
378 // Parent, FirstChild, LastChild, PrevSibling and NextSibling describe the
379 // widget tree structure.
380 //
381 // These fields are exported to enable walking the node tree, but they
382 // should not be modified directly. Instead, call the Insert and Remove
383 // methods, which keeps the tree structure consistent.
384 Parent, FirstChild, LastChild, PrevSibling, NextSibling *Embed
385
386 // LayoutData is layout-specific data for this node. Its type is determined
387 // by its parent node's type. For example, each child of a Flow may hold a
388 // FlowLayoutData in this field.
389 LayoutData interface{}
390
391 // TODO: add commentary about the Measure / Layout / Paint model, and about
392 // the lifetime of the MeasuredSize and Rect fields, and when user code can
393 // access and/or modify them. At some point a new cycle begins, a call to
394 // measure is necessary, and using MeasuredSize is incorrect (unless you're
395 // trying to recall something about the past).
396
397 // MeasuredSize is the widget's natural size, in pixels, as calculated by
398 // the most recent Measure call.
399 MeasuredSize image.Point
400
401 // Rect is the widget's position and actual (as opposed to natural) size,
402 // in pixels, as calculated by the most recent Layout call on its parent
403 // node. A parent may lay out a child at a size different to its natural
404 // size in order to satisfy a layout constraint, such as a row of buttons
405 // expanding to fill a panel's width.
406 //
407 // The position (Rectangle.Min) is relative to its parent node. This is not
408 // necessarily the same as relative to the screen's, window's or image
409 // buffer's origin.
410 Rect image.Rectangle
411
412 // Marks are a bitfield of node state, such as whether it needs measure,
413 // layout or paint.
414 Marks Marks
415 }
416
417 func (m *Embed) Wrappee() *Embed { return m }
418
419 // TODO: should insert and remove call Mark(MarkNeedsMeasureLayout | MarkNeedsPaint)?
420
421 func (m *Embed) insert(c, nextSibling Node) {
422 n := c.Wrappee()
423 if n.Parent != nil || n.PrevSibling != nil || n.NextSibling != nil {
424 panic("node: Insert called for an attached child")
425 }
426 n.Parent = m
427
428 if nextSibling == nil {
429 last := m.LastChild
430 if last != nil {
431 last.NextSibling = n
432 } else {
433 m.FirstChild = n
434 }
435 m.LastChild = n
436 n.PrevSibling = last
437 return
438 }
439
440 o := nextSibling.Wrappee()
441 if o.Parent != m {
442 panic("node: Insert called for a non-sibling nextSibling node")
443 }
444 if o.PrevSibling == nil {
445 o.PrevSibling = n
446 n.NextSibling = o
447 m.FirstChild = n
448 return
449 }
450
451 o.PrevSibling.NextSibling = n
452 n.PrevSibling = o.PrevSibling
453 n.NextSibling = o
454 o.PrevSibling = n
455 }
456
457 func (m *Embed) remove(c Node) {
458 n := c.Wrappee()
459 if n.Parent != m {
460 panic("node: Remove called for a non-child node")
461 }
462 if m.FirstChild == n {
463 m.FirstChild = n.NextSibling
464 }
465 if n.NextSibling != nil {
466 n.NextSibling.PrevSibling = n.PrevSibling
467 }
468 if m.LastChild == n {
469 m.LastChild = n.PrevSibling
470 }
471 if n.PrevSibling != nil {
472 n.PrevSibling.NextSibling = n.NextSibling
473 }
474 n.Parent = nil
475 n.PrevSibling = nil
476 n.NextSibling = nil
477 }
478
479 func (m *Embed) Mark(marks Marks) {
480 oldMarks := m.Marks
481 m.Marks |= marks
482 changedMarks := m.Marks ^ oldMarks
483 if changedMarks != 0 && m.Parent != nil {
484 m.Parent.Wrapper.OnChildMarked(m.Wrapper, changedMarks)
485 }
486 }
487
488 // Marks are a bitfield of node state, such as whether it needs measure, layout
489 // or paint.
490 type Marks uint32
491
492 const (
493 // MarkNeedsMeasureLayout marks this node as needing Measure and Layout
494 // calls.
495 MarkNeedsMeasureLayout = Marks(1 << 0)
496 // TODO: use this.
497
498 // MarkNeedsPaint marks this node as needing a Paint call.
499 MarkNeedsPaint = Marks(1 << 1)
500
501 // MarkNeedsPaintBase marks this node as needing a PaintBase call.
502 MarkNeedsPaintBase = Marks(1 << 2)
503 )
504
505 func (m Marks) NeedsMeasureLayout() bool { return m&MarkNeedsMeasureLayout != 0 }
506 func (m Marks) NeedsPaint() bool { return m&MarkNeedsPaint != 0 }
507 func (m Marks) NeedsPaintBase() bool { return m&MarkNeedsPaintBase != 0 }
508
509 func (m *Marks) UnmarkNeedsMeasureLayout() { *m &^= MarkNeedsMeasureLayout }
510 func (m *Marks) UnmarkNeedsPaint() { *m &^= MarkNeedsPaint }
511 func (m *Marks) UnmarkNeedsPaintBase() { *m &^= MarkNeedsPaintBase }