diff --git a/app/painter.go b/app/painter.go index 47cc87670..20cd6c450 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1432,6 +1432,7 @@ func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, Multiline: hit.Multiline, ReadOnly: hit.ReadOnly, Secure: hit.Secure, NavigationKeys: hit.NavigationKeys, TextBounds: text.Bounds, FontSize: text.Size, FontWeight: text.Weight, TextColor: text.Color, Alignment: text.Alignment, + TextScroll: text.Scroll, HideNativeOverlays: hit.HideNativeOverlays, } return context, text.Placement, index diff --git a/app/text_geometry.go b/app/text_geometry.go index 72f06da6d..ceaa96b7e 100644 --- a/app/text_geometry.go +++ b/app/text_geometry.go @@ -24,6 +24,9 @@ type textGeometry struct { alignment gfx.Alignment value string // the field's value shown string // what is drawn: the value, or one bullet per rune + // scroll is how far a field that paints its own line moved it left, so a point in + // the window is measured against the glyphs where they were drawn. + scroll float32 } // focusedTextGeometry is the geometry of the focused field, false when no field with text @@ -44,7 +47,7 @@ func (painter *painter) focusedTextGeometry() (textGeometry, bool) { geometry := textGeometry{ canvas: painter.canvas, placement: placement, bounds: context.TextBounds, style: gfx.TextStyle{Size: context.FontSize, Weight: context.FontWeight}, - alignment: context.Alignment, value: value, shown: value, + alignment: context.Alignment, value: value, shown: value, scroll: context.TextScroll, } if placement == nil && (context.TextBounds.Width <= 0 || context.TextBounds.Height <= 0 || context.FontSize <= 0) { return textGeometry{}, false @@ -98,7 +101,7 @@ func (geometry textGeometry) RangeRects(dst []gfx.Rect, start, end int) []gfx.Re } func (geometry textGeometry) origin() float32 { - return geometry.canvas.LabelOrigin(geometry.shown, geometry.bounds, geometry.style, geometry.alignment) + return geometry.canvas.LabelOrigin(geometry.shown, geometry.bounds, geometry.style, geometry.alignment) - geometry.scroll } // byteOffsetOfRune is the byte offset of rune index in value, clamped to its ends. diff --git a/base/color.go b/base/color.go index 7a2eb5146..0e03fc90d 100644 --- a/base/color.go +++ b/base/color.go @@ -60,6 +60,7 @@ func (b Box) TabStop(on bool) Box { type ColorPickerState struct { open, restoreFocus, applied bool showAlpha bool + live bool draft ColorPickerValue hexEditor text.Editor hex Field @@ -100,6 +101,28 @@ func (s *ColorPickerState) Applied() bool { return applied } +// Live reports whether edits update the bound color immediately. +func (s *ColorPickerState) Live() bool { return s.live } + +// Live makes a ColorPicker update its bound color as it is edited, without +// Clear, Cancel or Apply buttons. Escape and outside clicks close the panel +// without reverting edits. Bind a draft when the application owns Save/Cancel. +func (b Box) Live(on bool) Box { + if extra := b.pickerExtra(); extra != nil { + extra.picker.live = on + } + return b +} + +func (s *ColorPickerState) commitLive() { + if s.live && s.open && !s.invalid && s.target != nil { + color := s.draft.Color() + if *s.target != color { + *s.target, s.applied = color, true + } + } +} + // colorPickerLook is how a ColorPicker looks, set by its Box methods. type ColorPickerLook struct { Label string @@ -247,6 +270,7 @@ func (s *ColorPickerState) SetDraftValue(v ColorPickerValue) { } s.seen, s.invalid = value, false s.Summary = Summary(v) + s.commitLive() } func Summary(v ColorPickerValue) string { @@ -304,5 +328,6 @@ func (s *ColorPickerState) syncHex() { if valid { s.draft = s.draft.WithColor(color) s.Summary = Summary(s.draft) + s.commitLive() } } diff --git a/base/field.go b/base/field.go index 47cfe86ab..6a8020e30 100644 --- a/base/field.go +++ b/base/field.go @@ -76,6 +76,10 @@ type Field struct { // blink is the phase of the caret when the field paints it itself, which a fixed-pitch // field does (see Box.Mono): the platform draws the caret of the others. blink CaretBlink + // scroll keeps a value longer than the field in view of its caret, which the field + // must do itself: it paints its own line (HideEditorText), so the platform editor + // that would have scrolled it draws nothing. + scroll InputScroll // seen is the text as the field was last declared, and changed whether that // declaration found it edited since the one before (Box.Changed). seen string @@ -346,6 +350,7 @@ func (field *Field) Snapshot(f *Frame, ID gfx.ID, Label, placeholder string) Inp // canvas line, which moves the value when the field gains the keyboard. HideEditorText: true, Blink: &field.blink, + Scroll: &field.scroll, } // Where the caret, the selection and the composition are: what a field that paints them // itself needs, and what the platform's own presentation of them does without. diff --git a/base/fields.go b/base/fields.go index de3d2e477..8c37be679 100644 --- a/base/fields.go +++ b/base/fields.go @@ -55,4 +55,10 @@ type InputSnapshot struct { // Blink is the phase of the caret a field paints itself (see InputTextStyle.Mono and // HideEditorText): the caret is drawn only while it is lit. Nil keeps it lit. Blink *CaretBlink + // Scroll keeps a value too long for the field's line in view of its caret, when the + // component paints the line itself (see HideEditorText and InputTextStyle.Mono). A + // field that lets the platform editor paint its text does not need it: the platform + // scrolls the line for its own caret. Nil leaves the line where it is, which is where + // a value that fits stays. + Scroll *InputScroll } diff --git a/base/input_scroll.go b/base/input_scroll.go new file mode 100644 index 000000000..427d5db50 --- /dev/null +++ b/base/input_scroll.go @@ -0,0 +1,51 @@ +package base + +// InputScroll is the horizontal offset of one single-line field's painted line: how +// far the text of a value too long for the field is moved left so that the caret +// stays in view, as a native single-line editor does. The zero value starts at the +// left edge, which is the whole story for a value that fits. +// +// It is held by the field, next to the text it belongs to, and read during the paint +// that draws the field's own glyphs (see InputSnapshot.Scroll): a component that +// paints the text itself must move it with the caret, because the platform editor +// that would have scrolled it draws nothing. It is not safe for concurrent use, and +// one InputScroll serves one field. +type InputScroll struct { + offset float32 +} + +// Follow returns the offset to paint the line with, for a line textWidth wide whose +// caret stands caretX from the line's start, inside a field width across. The offset +// moves only as far as it must: a caret that is still in view leaves the text where +// it is, so typing at the end does not slide the line under a caret that has not +// reached the edge, and End shows the tail of a long value while Home comes back to +// its start. width of zero or less paints nothing, and an offset that no longer +// fits (a shorter value, a wider field) is brought back into range. +func (s *InputScroll) Follow(caretX, textWidth, width float32) float32 { + if width <= 0 { + s.offset = 0 + return 0 + } + // The caret is a stroke one pixel wide, so the room the line has to show its + // glyphs is the field less that stroke: a caret at the right edge is visible. + visible := max(width-1, 1) + most := max(textWidth-visible, 0) + offset := min(max(s.offset, 0), most) + if caretX-offset > visible { + offset = caretX - visible + } else if caretX < offset { + offset = caretX + } + offset = min(max(offset, 0), most) + s.offset = offset + return offset +} + +// Rest puts the line back at the field's start, as a field that loses its value does +// not want the next one scrolled by the last one's caret. +func (s *InputScroll) Rest() { s.offset = 0 } + +// Offset reports how far the line is painted left of the field's start, as the last +// Follow left it. A field reads it for what it must do itself, such as reporting +// where its text sits to the platform. +func (s *InputScroll) Offset() float32 { return s.offset } diff --git a/base/list.go b/base/list.go index 6c40cde31..f27fea8fe 100644 --- a/base/list.go +++ b/base/list.go @@ -218,7 +218,9 @@ func (s *ListState) HasFocus() bool { // list has not laid out is placed at the average height of the rows it has, so the // request stays for the paints that show the rows around the target and measure // them, and goes once the offset no longer moves; the list asks for those paints -// itself, and lets the request go if anything else moves the list first. +// itself, and lets the request go if anything else moves the list first. On a list +// that follows its end, a row away from the end leaves the end, as a scroll by the +// user does; ScrollToEnd follows it again. func (s *ListState) ScrollTo(row int, align ListAlign) { kind := listScrollStart switch align { @@ -910,7 +912,9 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( id := p.ID(at) // Follow is declared on the area the List returns, after its rows: whether the area // keeps to its end is what the paint before left it, as ScrollState.Pinned says. - pinned := c.f.Scrolls.get(id).pinned() + // ScrollArea forgets whether it follows until that declaration, so it is kept here. + prev := c.f.Scrolls.get(id) + pinned, followed := prev.pinned(), prev.follow area := c.f.ScrollArea(id) p.SetNode(area.i, at) in := &state.list @@ -918,11 +922,17 @@ func (p *Page) ListArea(c C, state *ListState, n int, horizontal bool, row func( state.resize(n) scroll := c.f.Exts[c.f.Nodes[area.i].Ext].scrollState in.Scroll = scroll + // The request settles against the follow the paint before declared: a ScrollTo + // away from the end of a following list leaves the end, as a scroll by the user + // does, instead of the Follow(true) after the rows pulling the list back to it. + scroll.follow = followed if state.applyScrollRequest(c.f) { // The area was declared at the offset it had; the layout reads the node, so it // takes the requested one too, which the rows are placed for below (as ScrollAt). c.f.Nodes[area.i].Scroll = scroll.Offset + pinned = scroll.pinned() } + scroll.follow = false viewport := scroll.Viewport if viewport <= 0 { viewport = c.f.bounds.Height diff --git a/base/menu_state.go b/base/menu_state.go index 12c15c419..d89629442 100644 --- a/base/menu_state.go +++ b/base/menu_state.go @@ -289,7 +289,7 @@ func (scroll *MenuScroll) Dragging() bool { return scroll.Held } func (scroll *MenuScroll) Drag(event gfx.PointerEvent) bool { switch event.Kind { case gfx.PointerDown: - if scroll.BarID.IsZero() || event.Target != scroll.BarID || scroll.MaxValue <= 0 { + if scroll.BarID.IsZero() || event.Target != scroll.BarID || scroll.MaxValue <= 0 || event.Button > gfx.PointerButtonPrimary { return false } at := scroll.BarTop + (scroll.View-scroll.Thumb)*scroll.Offset/scroll.MaxValue diff --git a/base/scroll.go b/base/scroll.go index 0b61c5500..4ebda0b74 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -363,11 +363,11 @@ func (s *ScrollState) relax(canvas *gfx.Canvas) { // Key applies the keyboard's scrolling to the area, from the content and viewport // of its last layout: Left and Right move a Sideways area by step, Up and Down -// vertically by step, PageUp and PageDown by a viewport, and Home and End to the -// start and the end. A step of zero or less is 32 pixels, one line. It reports a -// recognized key as handled even when the area was already at that end, so the -// caller stops there rather than looking for another area, and Repaint only when -// the offsets moved. +// vertically by step, PageUp and PageDown by gfx.ScrollPage of the viewport, and +// Home and End to the start and the end. A step of zero or less is 32 pixels, +// one line. It reports a recognized key as handled even when the area was +// already at that end, so the caller stops there rather than looking for another +// area, and Repaint only when the offsets moved. // // It is for a page that gives the keyboard to the area itself, as one does to a // terminal or a log beside a control: a List and a Table scroll with the arrow @@ -379,7 +379,7 @@ func (s *ScrollState) Key(event gfx.KeyEvent, step float32) gfx.EventResult { if step <= 0 { step = 32 } - page := max(s.Viewport*0.9, step) + page := max(gfx.ScrollPage(s.Viewport), step) before, beforeX := s.Offset, s.OffsetX switch event.Key { case gfx.KeyLeft: diff --git a/base/scroll_test.go b/base/scroll_test.go index f183d14a6..5f333e5da 100644 --- a/base/scroll_test.go +++ b/base/scroll_test.go @@ -292,7 +292,7 @@ func TestScrollPaintsOnWholeLogicalPixels(t *testing.T) { } // ScrollState.Key is the keyboard's counterpart of Wheel: a page that owns an -// area's focus moves it with the arrow keys, a viewport at a time with PageUp and +// area's focus moves it with the arrow keys, a page at a time with PageUp and // PageDown, and to either end with Home and End, never past them. func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { var view View @@ -304,7 +304,7 @@ func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { }{ {gfx.KeyDown, 32}, {gfx.KeyUp, 0}, - {gfx.KeyPageDown, 90}, + {gfx.KeyPageDown, gfx.ScrollPage(state.Viewport)}, {gfx.KeyPageUp, 0}, {gfx.KeyEnd, 200}, {gfx.KeyHome, 0}, @@ -324,8 +324,8 @@ func TestScrollStateKeyScrollsWithinItsContent(t *testing.T) { if result := state.Key(gfx.KeyEvent{Key: gfx.KeyDown, Release: true}, 32); result.Handled || state.Offset != 0 { t.Errorf("a key release moved the area to %v, handled %v", state.Offset, result.Handled) } - if result := state.Key(gfx.KeyEvent{Key: gfx.KeyPageDown}, 32); result.Handled && state.Offset != 90 { - t.Errorf("a zero step paged to %v, want 90", state.Offset) + if result := state.Key(gfx.KeyEvent{Key: gfx.KeyPageDown}, 32); result.Handled && state.Offset != gfx.ScrollPage(state.Viewport) { + t.Errorf("a zero step paged to %v, want %v", state.Offset, gfx.ScrollPage(state.Viewport)) } state.ScrollTo(state.Max()) if result := state.Key(gfx.KeyEvent{Key: gfx.KeyDown}, 32); !result.Handled || result.Repaint { @@ -369,19 +369,21 @@ func TestAWheelPageMovesTheAreasOwnPage(t *testing.T) { state := view.ScrollState(listID) window := gfx.Size{Width: 800, Height: 1000} // The system asks for a screen per notch: the event's delta is a screen of - // the window, and the area moves a screen of its own instead. + // the window, and the area moves a page of its own instead, short of its + // whole viewport so the edge it leaves stays in view. if result := state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}); !result.Handled { t.Fatal("a page notch was not handled") } - if state.Offset != 100 { - t.Fatalf("one page notch moved the area to %v, want its own page 100, not the window's", state.Offset) + page := state.Offset + if page <= state.Viewport/2 || page >= state.Viewport { + t.Fatalf("one page notch moved the area %v of its %v viewport, want most of it with an overlap, not the window's", page, state.Viewport) } state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}) - if state.Offset != 200 { - t.Fatalf("the second page notch left the area at %v, want 200", state.Offset) + if state.Offset != 2*page { + t.Fatalf("the second page notch left the area at %v, want %v", state.Offset, 2*page) } state.Wheel(gfx.ScrollEvent{DeltaY: -1000, Pages: -1, Viewport: window}) - if state.Offset != 100 { - t.Fatalf("a page notch up left the area at %v, want 100", state.Offset) + if state.Offset != page { + t.Fatalf("a page notch up left the area at %v, want %v", state.Offset, page) } } diff --git a/cmd/viva/templates/carousel.go.txt b/cmd/viva/templates/carousel.go.txt index e4a801a59..76f3abac5 100644 --- a/cmd/viva/templates/carousel.go.txt +++ b/cmd/viva/templates/carousel.go.txt @@ -1,6 +1,9 @@ package {{PACKAGE}} -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // carouselControlOffset is the 16px between the viewport and a button (-left-12 // puts a size-8 button 48px out). @@ -61,6 +64,7 @@ type Carousel struct { contentExtent float32 offset float32 orientation CarouselOrientation + direction Direction previousID gfx.ID previousLabel string nextID gfx.ID @@ -88,6 +92,17 @@ func (carousel Carousel) Vertical() Carousel { return carousel } +// Direction sets the reading direction of a horizontal carousel. The zero +// value is LTR. Under RTL the content reads right to left: the first slide +// sits at the viewport's right edge and the offset reveals slides on its left, +// the previous control stands on the right of the viewport and the next one on +// the left, and a vertical carousel ignores it, since the block axis has no +// reading direction. +func (carousel Carousel) Direction(direction Direction) Carousel { + carousel.direction = direction + return carousel +} + // Controls assigns stable previous and next action IDs and accessible labels. func (carousel Carousel) Controls(previousID gfx.ID, previousLabel string, nextID gfx.ID, nextLabel string) Carousel { carousel.previousID = previousID @@ -104,19 +119,43 @@ func (carousel Carousel) Label(label string) Carousel { } // CarouselStepForKey is the carousel region's keyboard movement: Left/Up go to -// the previous slide, Right/Down to the next, and Home/End to the ends. The -// caller owns the index and does not move past either end. -func CarouselStepForKey(key gfx.Key, index, count int, direction Direction) (int, bool) { +// the previous slide, Right/Down to the next, and Home/End to the ends. In a +// horizontal carousel Left and Right follow the reading direction, as the +// framework's other horizontal roving keys do (TabsKeyDown, CalendarFocusForKey): +// an RTL carousel reads Left as the next slide and Right as the previous one. A +// vertical carousel ignores the direction, as Carousel.Direction says, so its +// Left and Right keep the previous and next meaning. The caller owns the index +// and does not move past either end. +func CarouselStepForKey(key gfx.Key, index, count int, orientation CarouselOrientation, direction Direction) (int, bool) { if count <= 0 || index < 0 || index >= count { return index, false } + rtl := direction.IsRTL() && orientation == CarouselHorizontal switch key { - case gfx.KeyLeft, gfx.KeyUp: + case gfx.KeyLeft: + step := -1 + if rtl { + step = 1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyRight: + step := 1 + if rtl { + step = -1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyUp: if index > 0 { return index - 1, true } return index, true - case gfx.KeyRight, gfx.KeyDown: + case gfx.KeyDown: if index < count-1 { return index + 1, true } @@ -170,8 +209,7 @@ func (carousel Carousel) Geometry() CarouselGeometry { } geometry := CarouselGeometry{ Bounds: viewport, Viewport: viewport, - Content: gfx.Rect{X: viewport.X - offset, Y: viewport.Y, Width: contentExtent, Height: viewport.Height}, - Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, + Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, CanPrevious: !carousel.disabled && itemCount > 0 && index > 0, CanNext: !carousel.disabled && itemCount > 0 && index+1 < itemCount, } @@ -188,20 +226,36 @@ func (carousel Carousel) Geometry() CarouselGeometry { } return geometry } + // LTR content grows to the right and the offset moves it left; RTL content + // grows to the left from the viewport's right edge and the offset moves it + // right, so the logical [offset, offset+viewportExtent] window of the + // content shows through the viewport either way. + contentX := viewport.X - offset + if base.WritingDirection(carousel.direction).IsRTL() { + contentX = viewport.X + offset + viewport.Width - contentExtent + } + geometry.Content = gfx.Rect{X: contentX, Y: viewport.Y, Width: contentExtent, Height: viewport.Height} + // The previous control stands at the content's inline start and the next one + // at its inline end: left and right in LTR, right and left in RTL. + previousX, nextX := viewport.X-carouselControlOffset-controlSize, viewport.X+viewport.Width+carouselControlOffset + if base.WritingDirection(carousel.direction).IsRTL() { + previousX, nextX = nextX, previousX + } geometry.PreviousButton = gfx.Rect{ - X: viewport.X - carouselControlOffset - controlSize, - Y: viewport.Y + (viewport.Height-controlSize)/2, + X: previousX, Y: viewport.Y + (viewport.Height-controlSize)/2, Width: controlSize, Height: controlSize, } geometry.NextButton = gfx.Rect{ - X: viewport.X + viewport.Width + carouselControlOffset, Y: geometry.PreviousButton.Y, + X: nextX, Y: geometry.PreviousButton.Y, Width: controlSize, Height: controlSize, } return geometry } // ItemGeometry translates one caller-supplied slide offset and extent along -// the carousel axis. It does not retain, measure, or virtualize the item. +// the carousel axis, placing it at the reading direction's edge of the content: +// its left edge in LTR and its right edge in RTL. It does not retain, measure, +// or virtualize the item. func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) CarouselItemGeometry { geometry := carousel.Geometry() contentOffset = carouselFiniteNonNegative(contentOffset) @@ -210,6 +264,9 @@ func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) X: geometry.Content.X + contentOffset, Y: geometry.Content.Y, Width: extent, Height: geometry.Viewport.Height, } + if base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical { + bounds.X = geometry.Content.X + geometry.Content.Width - contentOffset - extent + } if carousel.orientation == CarouselVertical { bounds = gfx.Rect{ X: geometry.Content.X, Y: geometry.Content.Y + contentOffset, @@ -274,6 +331,9 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, border.Alpha *= 0.50 } carousel.canvas.RoundedBorder(bounds, radius, 1, border, background) + // The arrow points along the reading direction: back toward the previous + // slide's edge and forward toward the next one's, mirrored under RTL. + rtl := base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical icon := &carouselArrowRight switch { case carousel.orientation == CarouselVertical && previous: @@ -281,7 +341,17 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, case carousel.orientation == CarouselVertical: icon = &carouselArrowDown case previous: - icon = &carouselArrowLeft + if rtl { + icon = &carouselArrowRight + } else { + icon = &carouselArrowLeft + } + default: + if rtl { + icon = &carouselArrowLeft + } else { + icon = &carouselArrowRight + } } paintChevronSized(carousel.canvas, icon, bounds, 16, foreground) carousel.canvas.HitWithOptions(id, bounds, label, gfx.HitOptions{ diff --git a/cmd/viva/templates/color_picker.go.txt b/cmd/viva/templates/color_picker.go.txt index 2b7579886..568afdc3f 100644 --- a/cmd/viva/templates/color_picker.go.txt +++ b/cmd/viva/templates/color_picker.go.txt @@ -29,6 +29,7 @@ type ColorPickerOptions struct { Open, Empty, Disabled, ShowAlpha bool // RoundTrigger renders a circular swatch. TriggerIcon can identify a custom // color action independently of its selected color. + Live bool RoundTrigger bool TriggerIcon *gfx.Icon Viewport gfx.Rect @@ -172,16 +173,19 @@ func (picker ColorPicker) Paint() ColorPickerLayout { alphaHeight = 16 + gap } fixed := float32(16) + 3*gap + 2*control + alphaHeight + errorHeight + if o.Live { + fixed -= control + gap + } overhead := 2*theme.Metrics.PadSurface + popoverHeaderHeight(theme.Metrics, 0) + popoverBodyGap(theme.Metrics) + 16 planeHeight := min(float32(160), max(0, o.Viewport.Height-fixed-overhead)) popover := BeginPopover(c, theme, o.Viewport, picker.bounds, PopoverOptions{ - Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: true, + Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: !o.Live, Instant: o.Live, Align: PopoverAlignEnd, SideOffset: 6, ContentSize: gfx.Size{Width: 280}, BodyHeight: planeHeight + fixed, InitialFocusID: o.IDs.Saturation, }) body := popover.Begin(labels.Color, "").Body defer popover.End() - if !o.Scope.IsZero() { + if !o.Scope.IsZero() && !o.Live { c.TrapFocus(o.Scope) } l.Content = body @@ -225,6 +229,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { c.Label(o.Error, gfx.Rect{X: body.X, Y: y, Width: body.Width, Height: errorHeight - gap}, gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Danger}) y += errorHeight } + if o.Live { + return l + } width := max(0, (body.Width-2*gap)/3) BeginButton(c, theme, o.IDs.Clear, gfx.Rect{X: body.X, Y: y, Width: width, Height: control}).Ghost(labels.Clear) BeginButton(c, theme, o.IDs.Cancel, gfx.Rect{X: body.X + width + gap, Y: y, Width: width, Height: control}).Outline(labels.Cancel) diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 4abfaa507..978586476 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -977,6 +977,16 @@ func (menu *menuSurface) end() { if !scroll.BarID.IsZero() { menu.canvas.HitWithOptions(scroll.BarID, gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 2 - menuBarWidth, Y: menu.top, Width: menuBarWidth, Height: view}, "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) + // A press the pointer pass delivers to the bar drags the thumb: the + // press was taken here, so the runtime captured it and the moves + // follow wherever the pointer goes. Without this ask the bar + // hit-tests and paints its thumb, but nothing ever drags it. A move + // the pointer merely hovers with is not a drag and stays hover. + if event, ok := menu.canvas.PointerOn(scroll.BarID); ok && + ((event.Kind == gfx.PointerDown && event.Button <= gfx.PointerButtonPrimary) || (scroll.Dragging() && event.Kind != gfx.PointerDown)) { + scroll.Drag(event) + menu.canvas.Consume() + } } menu.popOverlay() menu.popClip() diff --git a/cmd/viva/templates/input.go.txt b/cmd/viva/templates/input.go.txt index cd2dc536e..1b33faf91 100644 --- a/cmd/viva/templates/input.go.txt +++ b/cmd/viva/templates/input.go.txt @@ -93,8 +93,9 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. if selfPainted && focused && snapshot.ShowCaret && snapshot.Blink != nil { snapshot.ShowCaret = snapshot.Blink.Lit(canvas, snapshot.Caret) } + var scroll float32 if !snapshot.PlatformEditing && content.Width > 0 && content.Height > 0 { - inputPaintText(canvas, theme, content, snapshot, focused) + scroll = inputPaintText(canvas, theme, content, snapshot, focused) } if snapshot.ID.IsZero() { return @@ -106,22 +107,37 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. platformInk = gfx.Color{} } lineTop, lineHeight := inputLineBox(content, size) + // The line is told to the platform where it is painted: a field that scrolled it to + // keep its caret in view hands over that offset, so the pointer that lands in the + // field and the input method's window follow the glyphs the component drew. It is a + // separate value from TextBounds, which a native editor lays its own line out in and + // scrolls for its own caret; moving that box instead would scroll the line twice. textBounds := gfx.Rect{X: content.X, Y: lineTop, Width: content.Width, Height: lineHeight} canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, Invalid: snapshot.Invalid, NavigationKeys: snapshot.NavigationKeys, TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, + TextScroll: snapScrollText(scroll), HideNativeOverlays: selfPainted, }) } +// snapScrollText rounds a line's scroll to whole pixels, so the geometry the pointer is +// mapped through does not shift by a fraction of one on every paint. +func snapScrollText(scroll float32) float32 { + if scroll <= 0 { + return 0 + } + return float32(int(scroll + 0.5)) +} + // inputPaintText paints the value (or the placeholder) of a single-line field // with its selection, composition and caret. A Secure field shows one bullet per // character, and the offsets of the snapshot, which index the real text, are // mapped onto the bullets. InputGroup paints its embedded single-line control // through the same function, so the two cannot drift apart. -func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) { +func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) float32 { display := snapshot.DisplayValue if display == "" { display = snapshot.Value @@ -137,10 +153,10 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } - inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) + return inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } -func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) { +func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) float32 { textStyle := snapshot.Text.TextStyle(&theme) fontSize, ink := textStyle.Size, textStyle.Color color := ink @@ -159,9 +175,15 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color + // A value longer than the field is moved left so its caret stays in view, as a + // native single-line field scrolls it. Only a field that paints its own line needs + // this: the platform editor scrolls the line it paints for its own caret. + scroll := inputFollowScroll(canvas, bounds, value, textStyle, snapshot, placeholderShown) + line := bounds + line.X -= scroll // The caret, selection and composition share the glyphs' origin and follow // the visual order of mixed text (a selection may be several stretches). - origin := canvas.LabelOrigin(value, bounds, style, snapshot.Alignment) + origin := canvas.LabelOrigin(value, line, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -200,10 +222,12 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // The line is centered in the field like the caret and the selection, but its // box is the text's line box (20px at the 14px body size), not the taller // band the caret and selection fill: accessibility and parity report label - // bounds, and those should describe the glyph line the field draws. + // bounds, and those should describe the glyph line the field draws. It is moved + // with the caret, on the same offset the caret and selection take. lineTop, lineHeight := inputLineBox(bounds, fontSize) - line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.LabelAligned(value, line, style, snapshot.Alignment) + glyphs := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} + glyphs.X -= scroll + canvas.LabelAligned(value, glyphs, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -215,10 +239,32 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.LabelAligned(value, line, selected, snapshot.Alignment) + canvas.LabelAligned(value, glyphs, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() + return scroll +} + +// inputFollowScroll is how far the line of a field that paints its own text is moved +// left to keep the caret in view, and asks the field's InputScroll to work it out. +// A field that leaves the line to the platform editor keeps it where it is: that +// editor scrolls its own caret, and moving the glyphs under it would put the two out +// of step. +func inputFollowScroll(canvas *gfx.Canvas, bounds gfx.Rect, value string, style gfx.TextStyle, snapshot InputSnapshot, placeholderShown bool) float32 { + if snapshot.Scroll == nil || !inputSelfPainted(snapshot) || placeholderShown || bounds.Width <= 0 { + return 0 + } + caret := inputBoundary(value, snapshot.Caret) + caretX := canvas.TextCaretStyle(value, style, caret) + return snapshot.Scroll.Follow(caretX, canvas.TextWidthStyle(value, style), bounds.Width) +} + +// inputSelfPainted reports whether the component draws the field's text itself, so the +// platform editor is only where input arrives (see InputSnapshot.HideEditorText and +// InputTextStyle.Mono). +func inputSelfPainted(snapshot InputSnapshot) bool { + return snapshot.Text.Mono || snapshot.HideEditorText } // fillInputSelections paints the bands of the field's selections and returns diff --git a/cmd/viva/templates/message_scroller.go.txt b/cmd/viva/templates/message_scroller.go.txt index 4483a4c67..436f82f99 100644 --- a/cmd/viva/templates/message_scroller.go.txt +++ b/cmd/viva/templates/message_scroller.go.txt @@ -444,10 +444,15 @@ func (state *MessageScrollState) AnchorTurn(top float32) { // Prepended tells the state that height of content was inserted above what it was // showing, older history loaded while the reader looks at the transcript. The offset // moves by the same amount at the next Resolve so the rows on screen stay where they -// are. A transcript that follows its end needs no correction. +// are. A transcript that follows its end needs no correction. While an anchored turn +// holds the viewport, the anchor moves with the insert: the turn sits below the +// history that was loaded, so its content-space top moves down by the same height. func (state *MessageScrollState) Prepended(height float32) { if height > 0 && height == height { state.shift += height + if state.anchoring { + state.anchorTop += height + } } } diff --git a/components/carousel.go b/components/carousel.go index 7a33e6bc2..f540b9572 100644 --- a/components/carousel.go +++ b/components/carousel.go @@ -1,6 +1,9 @@ package components -import "github.com/vivaui/viva/gfx" +import ( + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) // carouselControlOffset is the 16px between the viewport and a button (-left-12 // puts a size-8 button 48px out). @@ -61,6 +64,7 @@ type Carousel struct { contentExtent float32 offset float32 orientation CarouselOrientation + direction Direction previousID gfx.ID previousLabel string nextID gfx.ID @@ -88,6 +92,17 @@ func (carousel Carousel) Vertical() Carousel { return carousel } +// Direction sets the reading direction of a horizontal carousel. The zero +// value is LTR. Under RTL the content reads right to left: the first slide +// sits at the viewport's right edge and the offset reveals slides on its left, +// the previous control stands on the right of the viewport and the next one on +// the left, and a vertical carousel ignores it, since the block axis has no +// reading direction. +func (carousel Carousel) Direction(direction Direction) Carousel { + carousel.direction = direction + return carousel +} + // Controls assigns stable previous and next action IDs and accessible labels. func (carousel Carousel) Controls(previousID gfx.ID, previousLabel string, nextID gfx.ID, nextLabel string) Carousel { carousel.previousID = previousID @@ -104,19 +119,43 @@ func (carousel Carousel) Label(label string) Carousel { } // CarouselStepForKey is the carousel region's keyboard movement: Left/Up go to -// the previous slide, Right/Down to the next, and Home/End to the ends. The -// caller owns the index and does not move past either end. -func CarouselStepForKey(key gfx.Key, index, count int, direction Direction) (int, bool) { +// the previous slide, Right/Down to the next, and Home/End to the ends. In a +// horizontal carousel Left and Right follow the reading direction, as the +// framework's other horizontal roving keys do (TabsKeyDown, CalendarFocusForKey): +// an RTL carousel reads Left as the next slide and Right as the previous one. A +// vertical carousel ignores the direction, as Carousel.Direction says, so its +// Left and Right keep the previous and next meaning. The caller owns the index +// and does not move past either end. +func CarouselStepForKey(key gfx.Key, index, count int, orientation CarouselOrientation, direction Direction) (int, bool) { if count <= 0 || index < 0 || index >= count { return index, false } + rtl := direction.IsRTL() && orientation == CarouselHorizontal switch key { - case gfx.KeyLeft, gfx.KeyUp: + case gfx.KeyLeft: + step := -1 + if rtl { + step = 1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyRight: + step := 1 + if rtl { + step = -1 + } + if next := index + step; next >= 0 && next < count { + return next, true + } + return index, true + case gfx.KeyUp: if index > 0 { return index - 1, true } return index, true - case gfx.KeyRight, gfx.KeyDown: + case gfx.KeyDown: if index < count-1 { return index + 1, true } @@ -170,8 +209,7 @@ func (carousel Carousel) Geometry() CarouselGeometry { } geometry := CarouselGeometry{ Bounds: viewport, Viewport: viewport, - Content: gfx.Rect{X: viewport.X - offset, Y: viewport.Y, Width: contentExtent, Height: viewport.Height}, - Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, + Offset: offset, MaxOffset: maximum, Index: index, ItemCount: itemCount, CanPrevious: !carousel.disabled && itemCount > 0 && index > 0, CanNext: !carousel.disabled && itemCount > 0 && index+1 < itemCount, } @@ -188,20 +226,36 @@ func (carousel Carousel) Geometry() CarouselGeometry { } return geometry } + // LTR content grows to the right and the offset moves it left; RTL content + // grows to the left from the viewport's right edge and the offset moves it + // right, so the logical [offset, offset+viewportExtent] window of the + // content shows through the viewport either way. + contentX := viewport.X - offset + if base.WritingDirection(carousel.direction).IsRTL() { + contentX = viewport.X + offset + viewport.Width - contentExtent + } + geometry.Content = gfx.Rect{X: contentX, Y: viewport.Y, Width: contentExtent, Height: viewport.Height} + // The previous control stands at the content's inline start and the next one + // at its inline end: left and right in LTR, right and left in RTL. + previousX, nextX := viewport.X-carouselControlOffset-controlSize, viewport.X+viewport.Width+carouselControlOffset + if base.WritingDirection(carousel.direction).IsRTL() { + previousX, nextX = nextX, previousX + } geometry.PreviousButton = gfx.Rect{ - X: viewport.X - carouselControlOffset - controlSize, - Y: viewport.Y + (viewport.Height-controlSize)/2, + X: previousX, Y: viewport.Y + (viewport.Height-controlSize)/2, Width: controlSize, Height: controlSize, } geometry.NextButton = gfx.Rect{ - X: viewport.X + viewport.Width + carouselControlOffset, Y: geometry.PreviousButton.Y, + X: nextX, Y: geometry.PreviousButton.Y, Width: controlSize, Height: controlSize, } return geometry } // ItemGeometry translates one caller-supplied slide offset and extent along -// the carousel axis. It does not retain, measure, or virtualize the item. +// the carousel axis, placing it at the reading direction's edge of the content: +// its left edge in LTR and its right edge in RTL. It does not retain, measure, +// or virtualize the item. func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) CarouselItemGeometry { geometry := carousel.Geometry() contentOffset = carouselFiniteNonNegative(contentOffset) @@ -210,6 +264,9 @@ func (carousel Carousel) ItemGeometry(index int, contentOffset, extent float32) X: geometry.Content.X + contentOffset, Y: geometry.Content.Y, Width: extent, Height: geometry.Viewport.Height, } + if base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical { + bounds.X = geometry.Content.X + geometry.Content.Width - contentOffset - extent + } if carousel.orientation == CarouselVertical { bounds = gfx.Rect{ X: geometry.Content.X, Y: geometry.Content.Y + contentOffset, @@ -274,6 +331,9 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, border.Alpha *= 0.50 } carousel.canvas.RoundedBorder(bounds, radius, 1, border, background) + // The arrow points along the reading direction: back toward the previous + // slide's edge and forward toward the next one's, mirrored under RTL. + rtl := base.WritingDirection(carousel.direction).IsRTL() && carousel.orientation != CarouselVertical icon := &carouselArrowRight switch { case carousel.orientation == CarouselVertical && previous: @@ -281,7 +341,17 @@ func (carousel Carousel) paintControl(bounds gfx.Rect, id gfx.ID, label string, case carousel.orientation == CarouselVertical: icon = &carouselArrowDown case previous: - icon = &carouselArrowLeft + if rtl { + icon = &carouselArrowRight + } else { + icon = &carouselArrowLeft + } + default: + if rtl { + icon = &carouselArrowLeft + } else { + icon = &carouselArrowRight + } } paintChevronSized(carousel.canvas, icon, bounds, 16, foreground) carousel.canvas.HitWithOptions(id, bounds, label, gfx.HitOptions{ diff --git a/components/carousel_test.go b/components/carousel_test.go index 158ec10e2..7e1c38727 100644 --- a/components/carousel_test.go +++ b/components/carousel_test.go @@ -22,6 +22,55 @@ func TestCarouselHorizontalGeometryClampsIndexOffsetAndItems(t *testing.T) { } } +// An RTL carousel mirrors the layout: the first slide sits at the viewport's +// right edge, the offset reveals slides on its left, the previous control +// stands on the right of the viewport and the next one on the left, and the +// arrows point back the other way. The selected slide still fills the viewport. +func TestCarouselRTLGeometryMirrorsTheReadingDirection(t *testing.T) { + var canvas gfx.Canvas + carousel := BeginCarousel(&canvas, gfx.LightTheme(), gfx.Rect{X: 100, Y: 40, Width: 300, Height: 180}, 3, 1). + Content(900, 300).Direction(RTL).Controls(gfx.Item(41), "Previous slide", gfx.Item(42), "Next slide") + geometry := carousel.BeginContent() + // Offset 300 shows the second slide: its content window [300, 600) lands on + // the viewport [100, 400), and the content's right edge — the first slide's + // inline start — stands 300 past the viewport's right edge, at x=700. + if geometry.Content.X != 100+300+300-900 || geometry.Content.Width != 900 { + t.Fatalf("RTL content = %+v, want X %v", geometry.Content, 100+300+300-900) + } + first := carousel.ItemGeometry(0, 0, 300) + if first.Bounds.X != 400 || first.Bounds.X+first.Bounds.Width != 700 || first.Visible { + t.Fatalf("RTL first slide = %+v, want it outside the right edge at [400, 700)", first.Bounds) + } + second := carousel.ItemGeometry(1, 300, 300) + if second.Bounds != geometry.Viewport || !second.Visible || !second.Selected { + t.Fatalf("RTL selected slide = %+v viewport=%+v", second.Bounds, geometry.Viewport) + } + third := carousel.ItemGeometry(2, 600, 300) + if third.Bounds.X != -200 || third.Visible { + t.Fatalf("RTL last slide = %+v, want it outside the left edge at [-200, 100)", third.Bounds) + } + // The controls swap sides: previous on the right of the viewport, next on + // the left, and each arrow points back toward its own slide. + if geometry.PreviousButton.X != geometry.Viewport.X+geometry.Viewport.Width+carouselControlOffset { + t.Fatalf("RTL previous button = %+v, want it right of the viewport", geometry.PreviousButton) + } + if geometry.NextButton.X+geometry.NextButton.Width+carouselControlOffset != geometry.Viewport.X { + t.Fatalf("RTL next button = %+v, want it left of the viewport", geometry.NextButton) + } + carousel.EndContent() + hits := canvas.Hits() + if len(hits) != 2 || hits[0].Bounds != geometry.PreviousButton || hits[1].Bounds != geometry.NextButton { + t.Fatalf("RTL control hits = %+v geometry=%+v", hits, geometry) + } + // Vertical keeps its own axis: the direction does not move anything. + vertical := BeginCarousel(nil, gfx.LightTheme(), gfx.Rect{X: 50, Y: 60, Width: 180, Height: 240}, 3, 1). + Content(900, 300).Vertical().Direction(RTL) + verticalGeometry := vertical.Geometry() + if verticalGeometry.Content.Y != 60-300 || verticalGeometry.PreviousButton.X != 50+(180-verticalGeometry.PreviousButton.Width)/2 { + t.Fatalf("RTL vertical carousel = %+v", verticalGeometry) + } +} + func TestCarouselVerticalGeometryAndClipping(t *testing.T) { var canvas gfx.Canvas carousel := BeginCarousel(&canvas, gfx.LightTheme(), gfx.Rect{X: 50, Y: 60, Width: 180, Height: 240}, 4, 1). @@ -87,19 +136,58 @@ func TestCarouselDeterministicStreamAndNoRepeatedPaintAllocations(t *testing.T) // The carousel region moves one slide with the arrows and to the ends with // Home/End, without wrapping. func TestCarouselStepForKey(t *testing.T) { - if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, LTR); !ok || next != 1 { + if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, CarouselHorizontal, LTR); !ok || next != 1 { t.Fatalf("Right = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyLeft, 0, 3, LTR); !ok || next != 0 { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 0, 3, CarouselHorizontal, LTR); !ok || next != 0 { t.Fatalf("Left at start = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, LTR); !ok || next != 2 { + if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, CarouselHorizontal, LTR); !ok || next != 2 { t.Fatalf("End = %v, %v", next, ok) } - if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, LTR); !ok || next != 0 { + if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, CarouselHorizontal, LTR); !ok || next != 0 { t.Fatalf("Home = %v, %v", next, ok) } - if _, ok := CarouselStepForKey(gfx.KeyEnter, 0, 3, LTR); ok { + if _, ok := CarouselStepForKey(gfx.KeyEnter, 0, 3, CarouselHorizontal, LTR); ok { t.Fatal("Enter is not a carousel movement") } } + +// An RTL carousel reads right to left: Left shows the next slide and Right the +// previous one, while the vertical keys and the ends keep their meaning. +func TestCarouselStepForKeyFollowsTheReadingDirection(t *testing.T) { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 1, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Left = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 1, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Right = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyLeft, 2, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Left at the last slide = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 0, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Right at the first slide = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyUp, 1, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Up = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyDown, 1, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL Down = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyHome, 2, 3, CarouselHorizontal, RTL); !ok || next != 0 { + t.Fatalf("RTL Home = %v, %v", next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyEnd, 0, 3, CarouselHorizontal, RTL); !ok || next != 2 { + t.Fatalf("RTL End = %v, %v", next, ok) + } + // A vertical carousel ignores the direction: Left and Right keep the previous + // and next meaning whichever direction the caller passes. + for _, direction := range []Direction{LTR, RTL} { + if next, ok := CarouselStepForKey(gfx.KeyLeft, 1, 3, CarouselVertical, direction); !ok || next != 0 { + t.Fatalf("vertical %v Left = %v, %v", direction, next, ok) + } + if next, ok := CarouselStepForKey(gfx.KeyRight, 1, 3, CarouselVertical, direction); !ok || next != 2 { + t.Fatalf("vertical %v Right = %v, %v", direction, next, ok) + } + } +} diff --git a/components/color_picker.go b/components/color_picker.go index 635ab34d5..05aed8a86 100644 --- a/components/color_picker.go +++ b/components/color_picker.go @@ -29,6 +29,7 @@ type ColorPickerOptions struct { Open, Empty, Disabled, ShowAlpha bool // RoundTrigger renders a circular swatch. TriggerIcon can identify a custom // color action independently of its selected color. + Live bool RoundTrigger bool TriggerIcon *gfx.Icon Viewport gfx.Rect @@ -172,16 +173,19 @@ func (picker ColorPicker) Paint() ColorPickerLayout { alphaHeight = 16 + gap } fixed := float32(16) + 3*gap + 2*control + alphaHeight + errorHeight + if o.Live { + fixed -= control + gap + } overhead := 2*theme.Metrics.PadSurface + popoverHeaderHeight(theme.Metrics, 0) + popoverBodyGap(theme.Metrics) + 16 planeHeight := min(float32(160), max(0, o.Viewport.Height-fixed-overhead)) popover := BeginPopover(c, theme, o.Viewport, picker.bounds, PopoverOptions{ - Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: true, + Layer: o.Layer, Scope: o.Scope, DismissID: o.IDs.Dismiss, AnchorDismiss: true, ConsumeOutsidePress: !o.Live, Instant: o.Live, Align: PopoverAlignEnd, SideOffset: 6, ContentSize: gfx.Size{Width: 280}, BodyHeight: planeHeight + fixed, InitialFocusID: o.IDs.Saturation, }) body := popover.Begin(labels.Color, "").Body defer popover.End() - if !o.Scope.IsZero() { + if !o.Scope.IsZero() && !o.Live { c.TrapFocus(o.Scope) } l.Content = body @@ -225,6 +229,9 @@ func (picker ColorPicker) Paint() ColorPickerLayout { c.Label(o.Error, gfx.Rect{X: body.X, Y: y, Width: body.Width, Height: errorHeight - gap}, gfx.TextStyle{Size: theme.Metrics.FontSizeS, Color: theme.Danger}) y += errorHeight } + if o.Live { + return l + } width := max(0, (body.Width-2*gap)/3) BeginButton(c, theme, o.IDs.Clear, gfx.Rect{X: body.X, Y: y, Width: width, Height: control}).Ghost(labels.Clear) BeginButton(c, theme, o.IDs.Cancel, gfx.Rect{X: body.X + width + gap, Y: y, Width: width, Height: control}).Outline(labels.Cancel) diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index fc1798308..7cd0ce7c4 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -977,6 +977,16 @@ func (menu *menuSurface) end() { if !scroll.BarID.IsZero() { menu.canvas.HitWithOptions(scroll.BarID, gfx.Rect{X: menu.bounds.X + menu.bounds.Width - 2 - menuBarWidth, Y: menu.top, Width: menuBarWidth, Height: view}, "Scroll", gfx.HitOptions{Role: gfx.RoleSlider, SkipFocus: true}) + // A press the pointer pass delivers to the bar drags the thumb: the + // press was taken here, so the runtime captured it and the moves + // follow wherever the pointer goes. Without this ask the bar + // hit-tests and paints its thumb, but nothing ever drags it. A move + // the pointer merely hovers with is not a drag and stays hover. + if event, ok := menu.canvas.PointerOn(scroll.BarID); ok && + ((event.Kind == gfx.PointerDown && event.Button <= gfx.PointerButtonPrimary) || (scroll.Dragging() && event.Kind != gfx.PointerDown)) { + scroll.Drag(event) + menu.canvas.Consume() + } } menu.popOverlay() menu.popClip() diff --git a/components/dropdown_menu_test.go b/components/dropdown_menu_test.go index 56e9cd585..3868e753f 100644 --- a/components/dropdown_menu_test.go +++ b/components/dropdown_menu_test.go @@ -399,6 +399,9 @@ func TestMenuScrollbarIsDraggableAndRowsLeaveItRoom(t *testing.T) { if scroll.Dragging() || scroll.Drag(gfx.PointerEvent{Kind: gfx.PointerMove, Y: 0}) { t.Fatal("moving after release still dragged") } + if scroll.Drag(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, Target: scroll.BarID, Y: bar.Y + 2}) || scroll.Dragging() { + t.Fatal("a secondary press started a scrollbar drag") + } // Without a BarID nothing but the rows is declared. plain := MenuScroll{} if _, ok := scrollingMenu(&plain, &canvas, 8, nil)[gfx.Item(9)]; ok || len(nonBlockHits(canvas.Hits())) != 3 { @@ -406,6 +409,89 @@ func TestMenuScrollbarIsDraggableAndRowsLeaveItRoom(t *testing.T) { } } +// The drag goes through the runtime's pointer event pass: the paint asks the +// canvas for the events aimed at the bar, a press on it starts a drag the held +// moves follow, the release ends it, and every event of the press was consumed +// instead of left to become a click. A move the pointer hovers with is neither +// delivered to the drag nor consumed. +func TestMenuScrollbarDragsThroughThePointerEventPass(t *testing.T) { + scroll := MenuScroll{BarID: gfx.Item(9)} + var canvas gfx.Canvas + paint := func(canvas *gfx.Canvas, size gfx.Size) { + menu := BeginDropdownMenu(canvas, gfx.DarkTheme(), gfx.Rect{X: 10, Y: 20, Width: 160, Height: 104}, DropdownMenuOptions{Layer: 7, Scope: gfx.Item(42), Scroll: &scroll}) + for index := range 8 { + menu.AddItem(DropdownMenuItem{ID: gfx.Item(100 + index), Label: "Item"}) + } + menu.End() + } + paint(&canvas, gfx.Size{}) + hits := map[gfx.ID]gfx.Rect{} + for _, hit := range canvas.Hits() { + hits[hit.ID] = hit.Bounds + } + bar, ok := hits[scroll.BarID] + if !ok { + t.Fatal("a scrolling menu with a BarID declares no scrollbar hit") + } + if !canvas.ListensForPointer() { + t.Fatal("a menu with a scrollbar did not ask for pointer events") + } + drag := func(kind gfx.PointerEventKind, y float32) bool { + return canvas.DeliverPointer(gfx.PointerEvent{Kind: kind, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: y, Target: scroll.BarID, Captured: kind != gfx.PointerDown}, gfx.Size{Width: 200, Height: 200}, paint) + } + if !drag(gfx.PointerDown, bar.Y+2) || !scroll.Dragging() { + t.Fatal("pressing the thumb neither started a drag nor was consumed") + } + if !drag(gfx.PointerMove, bar.Y+bar.Height+500) || scroll.Offset != scroll.Max() { + t.Fatalf("the held drag left the offset at %v of %v", scroll.Offset, scroll.Max()) + } + if !drag(gfx.PointerUp, bar.Y+bar.Height+500) || scroll.Dragging() { + t.Fatal("the release did not end the drag") + } + if drag(gfx.PointerMove, bar.Y+2) { + t.Fatal("a move the pointer hovers with was delivered to the drag") + } + if canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonSecondary, X: bar.X + 2, Y: bar.Y + 2, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) || scroll.Dragging() { + t.Fatal("a secondary press started or consumed a scrollbar drag") + } +} + +func TestMenuScrollbarDragPassAllocatesNothing(t *testing.T) { + scroll := MenuScroll{BarID: gfx.Item(9)} + var canvas gfx.Canvas + paint := func(canvas *gfx.Canvas, size gfx.Size) { + menu := BeginDropdownMenu(canvas, gfx.DarkTheme(), gfx.Rect{X: 10, Y: 20, Width: 160, Height: 104}, DropdownMenuOptions{Layer: 7, Scope: gfx.Item(42), Scroll: &scroll}) + for index := range 8 { + menu.AddItem(DropdownMenuItem{ID: gfx.Item(100 + index), Label: "Item"}) + } + menu.End() + } + paint(&canvas, gfx.Size{}) + hits := canvas.Hits() + var bar gfx.Rect + for _, hit := range hits { + if hit.ID == scroll.BarID { + bar = hit.Bounds + } + } + if bar.Height == 0 { + t.Fatal("a scrolling menu with a BarID declares no scrollbar hit") + } + if !canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: bar.Y + 2, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) { + t.Fatal("pressing the thumb was not delivered") + } + event := gfx.PointerEvent{Kind: gfx.PointerMove, Button: gfx.PointerButtonPrimary, X: bar.X + 2, Y: bar.Y + 8, Target: scroll.BarID, Captured: true} + if !canvas.DeliverPointer(event, gfx.Size{Width: 200, Height: 200}, paint) { + t.Fatal("the held drag was not delivered") + } + if allocations := testing.AllocsPerRun(100, func() { + canvas.DeliverPointer(event, gfx.Size{Width: 200, Height: 200}, paint) + }); allocations != 0 { + t.Fatalf("a drag pass over the scrollbar allocated %v times", allocations) + } + canvas.DeliverPointer(gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, Target: scroll.BarID}, gfx.Size{Width: 200, Height: 200}, paint) +} + func TestScrollingMenuAllocatesNothingOncePainted(t *testing.T) { scroll := MenuScroll{BarID: gfx.Item(9)} var canvas gfx.Canvas diff --git a/components/input.go b/components/input.go index 56734cb94..a3d19a58f 100644 --- a/components/input.go +++ b/components/input.go @@ -93,8 +93,9 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. if selfPainted && focused && snapshot.ShowCaret && snapshot.Blink != nil { snapshot.ShowCaret = snapshot.Blink.Lit(canvas, snapshot.Caret) } + var scroll float32 if !snapshot.PlatformEditing && content.Width > 0 && content.Height > 0 { - inputPaintText(canvas, theme, content, snapshot, focused) + scroll = inputPaintText(canvas, theme, content, snapshot, focused) } if snapshot.ID.IsZero() { return @@ -106,22 +107,37 @@ func paintInputContent(canvas *gfx.Canvas, theme gfx.Theme, bounds, content gfx. platformInk = gfx.Color{} } lineTop, lineHeight := inputLineBox(content, size) + // The line is told to the platform where it is painted: a field that scrolled it to + // keep its caret in view hands over that offset, so the pointer that lands in the + // field and the input method's window follow the glyphs the component drew. It is a + // separate value from TextBounds, which a native editor lays its own line out in and + // scrolls for its own caret; moving that box instead would scroll the line twice. textBounds := gfx.Rect{X: content.X, Y: lineTop, Width: content.Width, Height: lineHeight} canvas.HitWithOptions(snapshot.ID, bounds, snapshot.Label, gfx.HitOptions{ Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText, Value: snapshot.Value, Hint: snapshot.Hint, Disabled: snapshot.Disabled, ReadOnly: snapshot.ReadOnly, Secure: snapshot.Secure, Invalid: snapshot.Invalid, NavigationKeys: snapshot.NavigationKeys, TextBounds: textBounds, TextSize: size, TextWeight: weight, TextColor: platformInk, TextAlignment: snapshot.Alignment, + TextScroll: snapScrollText(scroll), HideNativeOverlays: selfPainted, }) } +// snapScrollText rounds a line's scroll to whole pixels, so the geometry the pointer is +// mapped through does not shift by a fraction of one on every paint. +func snapScrollText(scroll float32) float32 { + if scroll <= 0 { + return 0 + } + return float32(int(scroll + 0.5)) +} + // inputPaintText paints the value (or the placeholder) of a single-line field // with its selection, composition and caret. A Secure field shows one bullet per // character, and the offsets of the snapshot, which index the real text, are // mapped onto the bullets. InputGroup paints its embedded single-line control // through the same function, so the two cannot drift apart. -func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) { +func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snapshot InputSnapshot, focused bool) float32 { display := snapshot.DisplayValue if display == "" { display = snapshot.Value @@ -137,10 +153,10 @@ func inputPaintText(canvas *gfx.Canvas, theme gfx.Theme, content gfx.Rect, snaps snapshot.CompositionStart = inputMaskOffset(snapshot.Value, snapshot.CompositionStart) snapshot.CompositionEnd = inputMaskOffset(snapshot.Value, snapshot.CompositionEnd) } - inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) + return inputPaintLine(canvas, theme, content, display, snapshot.Placeholder, snapshot, focused) } -func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) { +func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholder string, snapshot InputSnapshot, focused bool) float32 { textStyle := snapshot.Text.TextStyle(&theme) fontSize, ink := textStyle.Size, textStyle.Color color := ink @@ -159,9 +175,15 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, placeholderShown := snapshot.Value == "" && snapshot.DisplayValue == "" style := textStyle style.Color = color + // A value longer than the field is moved left so its caret stays in view, as a + // native single-line field scrolls it. Only a field that paints its own line needs + // this: the platform editor scrolls the line it paints for its own caret. + scroll := inputFollowScroll(canvas, bounds, value, textStyle, snapshot, placeholderShown) + line := bounds + line.X -= scroll // The caret, selection and composition share the glyphs' origin and follow // the visual order of mixed text (a selection may be several stretches). - origin := canvas.LabelOrigin(value, bounds, style, snapshot.Alignment) + origin := canvas.LabelOrigin(value, line, style, snapshot.Alignment) var ranges [4]gfx.Rect selectionStart, selectionEnd := inputRange(value, snapshot.SelectionStart, snapshot.SelectionEnd) var selections []gfx.Rect @@ -200,10 +222,12 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, // The line is centered in the field like the caret and the selection, but its // box is the text's line box (20px at the 14px body size), not the taller // band the caret and selection fill: accessibility and parity report label - // bounds, and those should describe the glyph line the field draws. + // bounds, and those should describe the glyph line the field draws. It is moved + // with the caret, on the same offset the caret and selection take. lineTop, lineHeight := inputLineBox(bounds, fontSize) - line := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} - canvas.LabelAligned(value, line, style, snapshot.Alignment) + glyphs := gfx.Rect{X: bounds.X, Y: lineTop, Width: bounds.Width, Height: lineHeight} + glyphs.X -= scroll + canvas.LabelAligned(value, glyphs, style, snapshot.Alignment) for _, selection := range selections { if selection.Width <= 0 { continue @@ -215,10 +239,32 @@ func inputPaintLine(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, value, } selected := textStyle selected.Color = selectedColor - canvas.LabelAligned(value, line, selected, snapshot.Alignment) + canvas.LabelAligned(value, glyphs, selected, snapshot.Alignment) canvas.Unclip() } canvas.Unclip() + return scroll +} + +// inputFollowScroll is how far the line of a field that paints its own text is moved +// left to keep the caret in view, and asks the field's InputScroll to work it out. +// A field that leaves the line to the platform editor keeps it where it is: that +// editor scrolls its own caret, and moving the glyphs under it would put the two out +// of step. +func inputFollowScroll(canvas *gfx.Canvas, bounds gfx.Rect, value string, style gfx.TextStyle, snapshot InputSnapshot, placeholderShown bool) float32 { + if snapshot.Scroll == nil || !inputSelfPainted(snapshot) || placeholderShown || bounds.Width <= 0 { + return 0 + } + caret := inputBoundary(value, snapshot.Caret) + caretX := canvas.TextCaretStyle(value, style, caret) + return snapshot.Scroll.Follow(caretX, canvas.TextWidthStyle(value, style), bounds.Width) +} + +// inputSelfPainted reports whether the component draws the field's text itself, so the +// platform editor is only where input arrives (see InputSnapshot.HideEditorText and +// InputTextStyle.Mono). +func inputSelfPainted(snapshot InputSnapshot) bool { + return snapshot.Text.Mono || snapshot.HideEditorText } // fillInputSelections paints the bands of the field's selections and returns diff --git a/components/input_scroll_test.go b/components/input_scroll_test.go new file mode 100644 index 000000000..61ac7c93f --- /dev/null +++ b/components/input_scroll_test.go @@ -0,0 +1,178 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" +) + +// fixedWidth measures every rune one cell wide, so a test can say where a caret of a +// long value must land without depending on a font. +func fixedWidth(cell float32) *gfx.Canvas { + canvas := &gfx.Canvas{} + canvas.SetMeasurer(func(value string, size, weight float32) float32 { + return float32(len([]rune(value))) * cell + }) + return canvas +} + +// caretRect is the caret the field painted: the ink rectangle one pixel wide. +func caretRect(canvas *gfx.Canvas, ink gfx.Color) (gfx.Rectangle, bool) { + var caret gfx.Rectangle + found := false + for _, rectangle := range canvas.Rectangles() { + if rectangle.Bounds.Width == 1 && rectangle.Color == ink { + caret, found = rectangle, true + } + } + return caret, found +} + +// A single-line field that paints its own text must scroll it, as a native one does: +// before this, a value longer than the field kept its start in view however far the +// caret moved, so everything typed past the edge was invisible. +func TestInputScrollsItsOwnLineToKeepTheCaretInView(t *testing.T) { + const cell = 10 + theme := gfx.LightTheme() + ink := theme.Foreground + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" // 20 cells, twice the field + scroll := new(base.InputScroll) + caret := len(value) + + // The caret at the end of the value: the tail must be in view. + canvas := fixedWidth(cell) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: caret, HideEditorText: true, Scroll: scroll, + }) + painted, ok := caretRect(canvas, ink) + if !ok { + t.Fatal("the field painted no caret") + } + if right := painted.Bounds.X + painted.Bounds.Width; right > bounds.X+bounds.Width { + t.Fatalf("the caret at the end of a long value is painted at %v, past the field's right edge %v", painted.Bounds.X, bounds.X+bounds.Width) + } + if painted.Bounds.X < bounds.X { + t.Fatalf("the caret at the end is painted at %v, left of the field", painted.Bounds.X) + } + + // The line itself moved: the glyphs are no longer drawn from the field's start. + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + break + } + } + if label.Bounds.X >= bounds.X { + t.Fatalf("the glyphs still start at %v: a long value did not scroll", label.Bounds.X) + } + + // Home comes back: the caret at the start puts the line back at the field's start. + canvas = fixedWidth(cell) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: 0, HideEditorText: true, Scroll: scroll, + }) + painted, ok = caretRect(canvas, ink) + if !ok { + t.Fatal("the field painted no caret after Home") + } + if painted.Bounds.X != bounds.X { + t.Fatalf("the caret at the start is painted at %v, want the field's start %v", painted.Bounds.X, bounds.X) + } + if got := scroll.Offset(); got != 0 { + t.Fatalf("the line is scrolled %v with the caret at the start, want 0", got) + } +} + +// The scroll follows the caret only as far as it must: a caret still inside the field +// leaves the text where it is, so typing at the end does not slide the line under a +// caret that has not reached the edge. +func TestInputScrollLeavesTheLineInPlaceWhileTheCaretFits(t *testing.T) { + const cell = 10 + scroll := new(base.InputScroll) + width := float32(100) + // A caret at 40 of a 50-wide value, in a 100-wide field: everything fits. + if got := scroll.Follow(40, 50, width); got != 0 { + t.Fatalf("a value that fits is scrolled by %v, want 0", got) + } + // The caret reaches the right edge: the text moves just enough to show it. + if got := scroll.Follow(140, 150, width); got != 140-99 { + t.Fatalf("a caret at the edge leaves the text scrolled by %v, want %v", got, 140-99) + } + // A shorter field start brings the line back: the offset is kept in range. + if got := scroll.Follow(0, 150, width); got != 0 { + t.Fatalf("the caret at the start leaves the text scrolled by %v, want 0", got) + } + // A value that no longer overflows pulls the line back too. + if got := scroll.Follow(10, 20, width); got != 0 { + t.Fatalf("a value that fits again leaves the text scrolled by %v, want 0", got) + } +} + +// A field the platform editor paints scrolls its own line: moving the glyphs under it as +// well would scroll the caret twice. +func TestInputPlatformPaintedLineIsNotScrolled(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" + scroll := new(base.InputScroll) + canvas := fixedWidth(10) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: len(value), PlatformEditing: true, Scroll: scroll, + }) + if got := scroll.Offset(); got != 0 { + t.Fatalf("a platform-painted field scrolled its line by %v, want 0", got) + } + var label gfx.Text + for _, text := range canvas.Texts() { + if text.Value == value { + label = text + } + } + if label.Bounds.X != bounds.X { + t.Fatalf("the platform's line starts at %v, want the field's start %v", label.Bounds.X, bounds.X) + } +} + +// The scroll the component paints with is told to the platform, so a press lands where +// the glyphs are and the input method's window follows the caret. +func TestInputScrollIsDeclaredToThePlatform(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 0, Y: 0, Width: 100, Height: 32} + value := "0123456789abcdefghij" + scroll := new(base.InputScroll) + canvas := fixedWidth(10) + PaintInputContent(canvas, theme, bounds, bounds, InputSnapshot{ + ID: gfx.Item(1), Label: "Filter", Value: value, Focused: true, ShowCaret: true, + Caret: len(value), HideEditorText: true, Scroll: scroll, + }) + hits := canvas.Hits() + if len(hits) != 1 { + t.Fatalf("hits = %d, want 1", len(hits)) + } + text := hitTextAt(canvas, 0) + if want := float32(len(value)*10 - 99); text.Scroll != want { + t.Fatalf("the platform is told the line is scrolled by %v, want %v", text.Scroll, want) + } + if text.Bounds.X != bounds.X || text.Bounds.Width != bounds.Width { + t.Fatalf("the platform's text box is %+v, want the field's own %+v", text.Bounds, bounds) + } +} + +func TestInputScrollOffsetIsBoundedByTheLine(t *testing.T) { + scroll := new(base.InputScroll) + // A negative or zero width paints nothing and scrolls nothing. + if got := scroll.Follow(500, 900, 0); got != 0 { + t.Fatalf("a field with no width scrolls by %v, want 0", got) + } + // The line is never scrolled past its own end. + got := scroll.Follow(1000, 120, 100) + if most := float32(120 - 99); got != most { + t.Fatalf("the line scrolls by %v, want its most %v", got, most) + } +} diff --git a/components/message_scroller.go b/components/message_scroller.go index cfecf32af..3fa75418f 100644 --- a/components/message_scroller.go +++ b/components/message_scroller.go @@ -444,10 +444,15 @@ func (state *MessageScrollState) AnchorTurn(top float32) { // Prepended tells the state that height of content was inserted above what it was // showing, older history loaded while the reader looks at the transcript. The offset // moves by the same amount at the next Resolve so the rows on screen stay where they -// are. A transcript that follows its end needs no correction. +// are. A transcript that follows its end needs no correction. While an anchored turn +// holds the viewport, the anchor moves with the insert: the turn sits below the +// history that was loaded, so its content-space top moves down by the same height. func (state *MessageScrollState) Prepended(height float32) { if height > 0 && height == height { state.shift += height + if state.anchoring { + state.anchorTop += height + } } } diff --git a/components/message_scroller_test.go b/components/message_scroller_test.go index 0802ba0b2..3a5aa29dc 100644 --- a/components/message_scroller_test.go +++ b/components/message_scroller_test.go @@ -167,6 +167,29 @@ func TestMessageScrollStateAnchorsATurnThenHandsOverToTheLiveEdge(t *testing.T) } } +// Loading older history while a turn is anchored keeps the anchored message +// where it sits on screen: its content-space top moves down with the insert. +func TestMessageScrollStatePrependsWhileATurnIsAnchored(t *testing.T) { + state := MessageScrollState{PreviousPeek: MessageScrollPreviousPeek} + state.AnchorTurn(250) + if got := state.Resolve(100, 500); got != 186 { + t.Fatalf("anchored offset = %v, want 186", got) + } + state.Prepended(120) + if got := state.Resolve(100, 620); got != 306 { + t.Fatalf("anchored offset after prepending 120 above = %v, want 306 (the turn kept in place)", got) + } + // An anchor the reader released before the Resolve keeps the plain shift. + scrolled := MessageScrollState{PreviousPeek: MessageScrollPreviousPeek} + scrolled.AnchorTurn(250) + scrolled.Resolve(100, 500) + scrolled.ScrollBy(-20) + scrolled.Prepended(120) + if got := scrolled.Resolve(100, 620); got != 286 { + t.Fatalf("released anchor after prepending 120 = %v, want 286", got) + } +} + func TestMessageScrollStateAllocatesNothing(t *testing.T) { state := MessageScrollState{AutoScroll: true} if allocations := testing.AllocsPerRun(100, func() { diff --git a/gfx/canvas.go b/gfx/canvas.go index 6a7600376..f0413f1b8 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -572,6 +572,12 @@ type HitOptions struct { // TextAlignment is the line's placement within TextBounds. Zero preserves // an ordinary input's left alignment; the component resolves its default. TextAlignment Alignment + // TextScroll is how far a field that paints its own line has moved it left to keep + // its caret in view, in pixels. The pointer that lands in the field and the input + // method's window are placed from it, so they follow the glyphs the component drew + // rather than where an unscrolled line would have started. A field the platform + // editor paints scrolls its own line and leaves it 0. + TextScroll float32 // HideNativeOverlays asks the platform text service to keep its caret and // selection invisible while preserving native editing, IME and clipboard // behavior. Components that paint their own caret and selection set this @@ -613,7 +619,7 @@ func (options HitOptions) IsZero() bool { options.Live == 0 && options.Range == (ValueRange{}) && !options.SkipFocus && !options.SkipTab && !options.Backdrop && !options.PassSecondary && !options.PassPrimary && !options.label && !options.Presentational && !options.Autofocus && options.TextBounds == (Rect{}) && options.TextSize == 0 && options.TextWeight == 0 && options.TextColor == (Color{}) && options.TextAlignment == 0 && - !options.HideNativeOverlays && !options.NavigationKeys && !options.TypeAhead && options.Placement == nil + options.TextScroll == 0 && !options.HideNativeOverlays && !options.NavigationKeys && !options.TypeAhead && options.Placement == nil } // TextPlacement is what a text field that lays its own rows out tells the @@ -639,6 +645,9 @@ type HitText struct { Color Color Alignment Alignment Placement TextPlacement + // Scroll is HitOptions.TextScroll: how far a field that paints its own line moved + // it left, which the geometry of the field's text is measured from. + Scroll float32 } // Hit is one pointer interaction region in back-to-front paint order. The zero @@ -1801,10 +1810,11 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H // stretch of hits owns a contiguous stretch of hitTexts (see replay.go). var text int32 if options.TextBounds != (Rect{}) || options.TextSize != 0 || options.TextWeight != 0 || - options.TextColor != (Color{}) || options.TextAlignment != 0 || options.Placement != nil { + options.TextColor != (Color{}) || options.TextAlignment != 0 || options.TextScroll != 0 || options.Placement != nil { canvas.hitTexts = append(canvas.hitTexts, HitText{ Bounds: options.TextBounds, Size: options.TextSize, Weight: options.TextWeight, Color: options.TextColor, Alignment: options.TextAlignment, Placement: options.Placement, + Scroll: options.TextScroll, }) text = int32(len(canvas.hitTexts)) } diff --git a/gfx/input.go b/gfx/input.go index 4bdc1eeed..98456f5fc 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -298,9 +298,9 @@ func (e ScrollEvent) StepY(unit float32) float32 { // StepYIn is StepY for content of unit-sized rows inside a scroll region whose // visible height is viewport. When the system asks for whole screens, the notch -// moves as many of the region's pages as Pages says, rounded down to whole rows, -// rather than the window-sized distance DeltaY carries; that is one screen of -// the region, which is a screen of the rows a user sees in it. +// moves as many of the region's pages, ScrollPage of its viewport, as Pages +// says, rounded down to whole rows, rather than the window-sized distance +// DeltaY carries; the rows at the edge it leaves stay in view at the other. func (e ScrollEvent) StepYIn(unit, viewport float32) float32 { if e.Pages == 0 || unit <= 0 || e.DeltaY == 0 { return e.StepY(unit) @@ -322,13 +322,21 @@ func (e ScrollEvent) StepXIn(unit, viewport float32) float32 { return pageStep(e.DeltaX, e.Pages, unit, viewport) } +// ScrollPage is how far a page of scrolling moves a region whose visible extent +// along the axis is viewport: seven eighths of it, as browsers page, so the +// last lines of one page are still in view at the top of the next and a reader +// keeps their place. A page key and a wheel set to whole screens both move it. +func ScrollPage(viewport float32) float32 { + return max(viewport, 0) * 7 / 8 +} + // pageStep is how far pages of a region of viewport units-by-unit move it in the // direction of delta. func pageStep(delta, pages, unit, viewport float32) float32 { if pages < 0 { pages = -pages } - units := float32(int(pages * viewport / unit)) + units := float32(int(pages * ScrollPage(viewport) / unit)) if units < 1 { units = 1 } diff --git a/gfx/scroll_test.go b/gfx/scroll_test.go index cd05518fb..a5e0da234 100644 --- a/gfx/scroll_test.go +++ b/gfx/scroll_test.go @@ -26,30 +26,58 @@ func TestScrollStepRaisesClassicWheelToOneUnit(t *testing.T) { func TestPageStepMovesOnePageOfTheRegion(t *testing.T) { // A page notch reports the window as pixels and the region's own page is - // what moves: whole rows that fit in the region, not the window's. + // what moves: whole rows of the region, not the window's, and fewer than it + // shows, so the rows at the edge it leaves are still in view. cases := []struct { name string event ScrollEvent unit float32 view float32 - want float32 }{ - {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300, 300}, - {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300, -300}, - {"rows that do not fit whole are left out", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305, 300}, - {"two pages", ScrollEvent{DeltaY: 1800, Pages: 2}, 24, 200, 384}, - {"half a page of a trackpad setting", ScrollEvent{DeltaY: 450, Pages: 0.5}, 24, 200, 96}, - {"a region shorter than one row still moves a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 10, 30}, - {"a line notch is not a page", ScrollEvent{DeltaY: 48}, 30, 300, 48}, - {"a zero viewport keeps a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 0, 30}, + {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300}, + {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300}, + {"rows that do not fit whole", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305}, + {"a terminal screen", ScrollEvent{DeltaY: -900, Pages: -1}, 17, 40 * 17}, + {"a two-row region", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 60}, + {"a pane in pixels", ScrollEvent{DeltaY: 900, Pages: 1}, 1, 420}, } for _, c := range cases { - if got := c.event.StepYIn(c.unit, c.view); got != c.want { - t.Errorf("%s: StepYIn(%v, %v) = %v, want %v", c.name, c.unit, c.view, got, c.want) + got := c.event.StepYIn(c.unit, c.view) + if (got < 0) != (c.event.DeltaY < 0) { + t.Errorf("%s: StepYIn = %v, against the direction of %v", c.name, got, c.event.DeltaY) + } + step := got + if step < 0 { + step = -step + } + if rows := step / c.unit; rows != float32(int(rows)) { + t.Errorf("%s: StepYIn = %v, not whole rows of %v", c.name, got, c.unit) + } + if step >= c.view || step < c.view/2 { + t.Errorf("%s: StepYIn = %v, want most of the %v viewport with an overlap", c.name, got, c.view) + } + if step != float32(int(ScrollPage(c.view)/c.unit))*c.unit { + t.Errorf("%s: StepYIn = %v, not the rows of ScrollPage(%v)", c.name, got, c.view) } } - if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 50); got != 50 { - t.Errorf("StepXIn = %v, want 50", got) + one := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(24, 200) + if two := (ScrollEvent{DeltaY: 1800, Pages: 2}).StepYIn(24, 200); two < 2*one || two > 2*one+24 { + t.Errorf("two pages = %v, want twice a page of %v", two, one) + } + if half := (ScrollEvent{DeltaY: 450, Pages: 0.5}).StepYIn(24, 200); half <= 0 || half > one { + t.Errorf("half a page = %v, want a part of a page of %v", half, one) + } + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(30, 10); got != 30 { + t.Errorf("a region shorter than one row moved %v, want a row of 30", got) + } + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepYIn(30, 0); got != 30 { + t.Errorf("a zero viewport moved %v, want a row of 30", got) + } + if got := (ScrollEvent{DeltaY: 48}).StepYIn(30, 300); got != 48 { + t.Errorf("a line notch moved %v, want its own 48", got) + } + if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 80); got <= 0 || got >= 80 { + t.Errorf("StepXIn = %v, want most of the 80 width", got) } // A page setting does not turn a horizontal delta into a vertical page. if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepXIn(10, 50); got != 0 { diff --git a/internal/platform/linux/fonts_concurrent_linux_test.go b/internal/platform/linux/fonts_concurrent_linux_test.go new file mode 100644 index 000000000..cf294a30a --- /dev/null +++ b/internal/platform/linux/fonts_concurrent_linux_test.go @@ -0,0 +1,91 @@ +//go:build !android + +package linux + +import ( + "fmt" + "os" + "os/exec" + "runtime" + "sync" + "testing" + + "github.com/ebitengine/purego" +) + +func TestMonospaceFamiliesConcurrentWithTextRendering(t *testing.T) { + // 原生库崩溃不可 recover,用子进程保护其余测试。 + const probeEnv = "VIVA_TEST_CONCURRENT_FONT_SCAN" + if os.Getenv(probeEnv) != "1" { + command := exec.Command(os.Args[0], "-test.run=^TestMonospaceFamiliesConcurrentWithTextRendering$", "-test.timeout=90s", "-test.v") + command.Env = append(os.Environ(), probeEnv+"=1") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("concurrent font scan: %v\n%s", err, output) + } + return + } + + // 模拟固定在窗口线程上的界面渲染和未绑定线程的后台字体扫描。 + runtime.LockOSThread() + defer runtime.UnlockOSThread() + engine, err := newTextEngine() + if err != nil { + t.Skipf("Pango unavailable: %v", err) + } + defer engine.close() + if len(FontFamilies()) == 0 { + t.Skip("no installed fonts") + } + var workers sync.WaitGroup + start := make(chan struct{}) + for worker := 0; worker < 4; worker++ { + workers.Add(1) + go func() { + defer workers.Done() + <-start + for iteration := 0; iteration < 10; iteration++ { + families := MonospaceFamilies() + if len(families) == 0 { + t.Error("concurrent scan returned no monospace fonts") + return + } + } + }() + } + close(start) + for iteration := 0; iteration < 5000; iteration++ { + width := engine.Width(fmt.Sprintf("Motty font scan %d", iteration), 14, 0) + if width <= 0 { + t.Errorf("text width = %v, want a positive width", width) + break + } + } + workers.Wait() +} + +func TestFontScanServicesOwnIndependentFontMaps(t *testing.T) { + first, err := newFontScanTextServices() + if err != nil { + t.Skipf("PangoFT2 unavailable: %v", err) + } + defer first.close() + second, err := newFontScanTextServices() + if err != nil { + t.Fatal(err) + } + defer second.close() + var contextFontMap func(uintptr) uintptr + purego.RegisterLibFunc(&contextFontMap, first.pango, "pango_context_get_font_map") + firstMap, secondMap := contextFontMap(first.context), contextFontMap(second.context) + if firstMap == 0 || secondMap == 0 || firstMap == secondMap { + t.Fatalf("font scans must own distinct font maps: %x, %x", firstMap, secondMap) + } + // A machine without a monospace alias cannot measure either map; that is the + // environment, not the isolation under test. + if !familyMeasuresMono(first, "monospace") { + t.Skip("no measurable monospace family installed") + } + if !familyMeasuresMono(second, "monospace") { + t.Fatal("an isolated font map must measure the same family as the first") + } +} diff --git a/internal/platform/linux/fonts_linux.go b/internal/platform/linux/fonts_linux.go index b58f6f045..9a77f5adf 100644 --- a/internal/platform/linux/fonts_linux.go +++ b/internal/platform/linux/fonts_linux.go @@ -123,7 +123,7 @@ func fontFamilies(mono bool) []string { for name := range seen { names = append(names, name) } - } else if services, err := newTextServices(); err == nil { + } else if services, err := newFontScanTextServices(); err == nil { defer services.close() names = make([]string, 0, len(seen)) for name := range seen { diff --git a/internal/platform/linux/input_linux.go b/internal/platform/linux/input_linux.go index cbaf8074f..26c9f52bd 100644 --- a/internal/platform/linux/input_linux.go +++ b/internal/platform/linux/input_linux.go @@ -239,6 +239,12 @@ func (router eventRouter) key(keymap *xcbKeymap, event *xcbInputEvent, repeat bo keyEvent.Text = keymap.text(event.Detail, event.State) } keysym := keymap.keysym(event.Detail, event.State) + // 小键盘按当前 Num Lock 和 Shift 状态区分数字与导航键。 + if isKeypadKeysym(keysym) { + key = normalizedKeysym(keysym) + keyEvent.Key = key + keyEvent.Text = keymap.text(event.Detail, event.State) + } if key.IsModifier() && router.ime != nil { // An input method reads a lone modifier by its press and its release (a bare // Shift switches between Chinese and English), so it gets both. @@ -249,6 +255,10 @@ func (router eventRouter) key(keymap *xcbKeymap, event *xcbInputEvent, repeat bo keyEvent.Code = uint32(event.Detail) keyEvent.Text = keymap.shortcutText(event.Detail, 0) keyEvent.Typed = keymap.text(event.Detail, event.State) + // 清空修饰状态会丢失小键盘数字的身份,需保留实际选中的字符。 + if isKeypadKeysym(keysym) { + keyEvent.Text = keyEvent.Typed + } } if handled, err := router.modifierPress(keyEvent, keysym, uint32(event.Detail)); handled { return err @@ -396,6 +406,9 @@ func (router eventRouter) release(keymap *xcbKeymap, event *xcbInputEvent) error // The symbol at the state without the AltGr level: for the AltGr key itself // that is ISO_Level3_Shift, which is not Alt. keysym := keymap.keysym(event.Detail, event.State&^keymap.level3Mask()) + if isKeypadKeysym(keysym) { + key = normalizedKeysym(keysym) + } modifiers := router.releaseModifiers(xcbModifiers(event.State), key, keysym, uint32(event.Detail)) if !router.wantsKeyReleases() && !router.wantsModifierTap(key) || router.config.OnKey == nil { return nil diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index b715dc321..e29c72781 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -964,3 +964,58 @@ func TestX11ModifierTapsDeliverOnlyModifiers(t *testing.T) { } } } + +func TestTerminalRawKeypadRespectsNumLock(t *testing.T) { + for _, test := range []struct { + name string + navigation uint32 + digit uint32 + state uint16 + wantKey input.Key + wantText string + }{ + {"digit 0", 0xff9e, 0xffb0, xcbMod2, input.KeyUnknown, "0"}, + {"digit 1", keysymKPEnd, 0xffb1, xcbMod2, input.KeyUnknown, "1"}, + {"digit 2", keysymKPDown, 0xffb2, xcbMod2, input.KeyUnknown, "2"}, + {"digit 3", 0xff9b, 0xffb3, xcbMod2, input.KeyUnknown, "3"}, + {"digit 4", keysymKPLeft, 0xffb4, xcbMod2, input.KeyUnknown, "4"}, + {"digit 5", 0xff9d, 0xffb5, xcbMod2, input.KeyUnknown, "5"}, + {"digit 6", keysymKPRight, 0xffb6, xcbMod2, input.KeyUnknown, "6"}, + {"digit 7", keysymKPHome, 0xffb7, xcbMod2, input.KeyUnknown, "7"}, + {"digit 8", keysymKPUp, 0xffb8, xcbMod2, input.KeyUnknown, "8"}, + {"digit 9", 0xff9a, 0xffb9, xcbMod2, input.KeyUnknown, "9"}, + {"decimal", keysymKPDelete, 0xffae, xcbMod2, input.KeyUnknown, "."}, + {"left", keysymKPLeft, 0xffb4, 0, input.KeyLeft, ""}, + {"right", keysymKPRight, 0xffb6, 0, input.KeyRight, ""}, + {"shift left", keysymKPLeft, 0xffb4, xcbMod2 | xcbModShift, input.KeyLeft, ""}, + {"shift digit", keysymKPLeft, 0xffb4, xcbModShift, input.KeyUnknown, "4"}, + } { + t.Run(test.name, func(t *testing.T) { + var keys []platform.KeyEvent + router := eventRouter{ + config: platform.Config{OnKey: func(event platform.KeyEvent) (platform.Frame, error) { + keys = append(keys, event) + return platform.Frame{}, nil + }}, + text: &linuxTextInput{enabled: true, input: platform.TextInput{Terminal: true, KeyReleases: true}}, + present: func(platform.Frame) error { return nil }, + modifierKeys: newModifierTracker(), + } + keymap := xcbKeymap{first: 79, last: 79, perKeycode: 2, keysyms: []uint32{test.navigation, test.digit}} + event := xcbInputEvent{Detail: 79, State: test.state} + if err := router.key(&keymap, &event, false); err != nil { + t.Fatal(err) + } + if err := router.release(&keymap, &event); err != nil { + t.Fatal(err) + } + want := []platform.KeyEvent{ + {Key: test.wantKey, Text: test.wantText, Typed: test.wantText, Code: 79, Modifiers: xcbModifiers(test.state)}, + {Key: test.wantKey, Code: 79, Release: true, Modifiers: xcbModifiers(test.state)}, + } + if !reflect.DeepEqual(keys, want) { + t.Fatalf("keys = %+v, want %+v", keys, want) + } + }) + } +} diff --git a/internal/platform/linux/text_linux.go b/internal/platform/linux/text_linux.go index 5fd98fa4d..116d2301b 100644 --- a/internal/platform/linux/text_linux.go +++ b/internal/platform/linux/text_linux.go @@ -193,6 +193,15 @@ func loadTextAPI() (*textServices, error) { } func newTextServices() (*textServices, error) { + return newTextServicesWithFontMap(false) +} + +// 字体扫描使用独立的 FT2 字体映射,避免与界面共享 Cairo 的原生字体缓存。 +func newFontScanTextServices() (*textServices, error) { + return newTextServicesWithFontMap(true) +} + +func newTextServicesWithFontMap(isolated bool) (*textServices, error) { systemTextAPI.once.Do(func() { systemTextAPI.api, systemTextAPI.err = loadTextAPI() }) @@ -201,12 +210,28 @@ func newTextServices() (*textServices, error) { } services := *systemTextAPI.api - fontMap := services.fontMapGetDefault() + var fontMap uintptr + if isolated { + // Linux PangoCairo 依赖 PangoFT2;缺少该符号时由调用方退回 Fontconfig。 + symbol, err := purego.Dlsym(services.pangoCairo, "pango_ft2_font_map_new") + if err != nil || symbol == 0 { + return nil, fmt.Errorf("linux: isolated Pango font map is unavailable") + } + var fontMapNew func() uintptr + purego.RegisterFunc(&fontMapNew, symbol) + fontMap = fontMapNew() + } else { + fontMap = services.fontMapGetDefault() + } if fontMap == 0 { services.close() return nil, fmt.Errorf("linux: system Pango font map is unavailable") } services.context = services.fontMapCreateContext(fontMap) + if isolated { + // context 持有自己的引用;无论创建是否成功,都释放构造器返回的引用。 + services.objectUnref(fontMap) + } if services.context == 0 { services.close() return nil, fmt.Errorf("linux: create Pango font context") diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go index be8262130..a40824281 100644 --- a/internal/platform/windows/api_windows_test.go +++ b/internal/platform/windows/api_windows_test.go @@ -39,6 +39,7 @@ func TestNativeStructureABI(t *testing.T) { {"D3D11_SUBRESOURCE_DATA", unsafe.Sizeof(resourceData{}), 16}, {"D3D11_SHADER_RESOURCE_VIEW_DESC", unsafe.Sizeof(resourceViewDesc{}), 24}, {"DXGI_SWAP_CHAIN_DESC1", unsafe.Sizeof(swapChainDesc1{}), 48}, + {"DXGI_ADAPTER_DESC", unsafe.Sizeof(adapterDesc{}), 312}, {"D3D11_RENDER_TARGET_BLEND_DESC", unsafe.Sizeof(renderBlend{}), 32}, {"D3D11_BLEND_DESC", unsafe.Sizeof(blendDesc{}), 264}, {"D3D11_RASTERIZER_DESC", unsafe.Sizeof(rasterDesc{}), 40}, diff --git a/internal/platform/windows/composition_windows.go b/internal/platform/windows/composition_windows.go index 33246c8db..7e8c6acab 100644 --- a/internal/platform/windows/composition_windows.go +++ b/internal/platform/windows/composition_windows.go @@ -48,6 +48,7 @@ func (renderer *renderer) createCompositionDevice(software bool) error { for _, driver := range drivers { status, _, _ = createD3DDevice.Call(0, driver, 0, 0x20, uintptr(unsafe.Pointer(&levels[0])), 1, 7, uintptr(unsafe.Pointer(&renderer.device)), 0, uintptr(unsafe.Pointer(&renderer.context))) if hresult(status) == nil { + renderer.software = driver == 5 break } release(&renderer.context) diff --git a/internal/platform/windows/device_windows.go b/internal/platform/windows/device_windows.go index 834fc182d..8d6e095bd 100644 --- a/internal/platform/windows/device_windows.go +++ b/internal/platform/windows/device_windows.go @@ -2,6 +2,8 @@ package windows import ( "fmt" + "sync" + "syscall" "time" "unsafe" @@ -15,6 +17,72 @@ import ( // what the window shows is in memory in the renderer, so the device is made again // and the scene drawn once more, instead of closing the window. +var describeDeviceOnce sync.Once + +// describeDevice reports the graphics path once per process: which driver and +// adapter stand behind the Direct3D device, its feature level, and whether +// DirectComposition or the window's own swap chain presents. Every window makes +// its own device the same way, so the first one speaks for the rest. +func (renderer *renderer) describeDevice() { + describeDeviceOnce.Do(func() { + if !diag.Enabled(diag.Info) { + return + } + driver, present := "hardware", "window" + if renderer.software { + driver = "warp" + } + if renderer.usesComposition() { + present = "direct-composition" + } + attrs := []diag.Attr{ + diag.String("driver", driver), + diag.String("present", present), + diag.String("feature-level", featureLevelName(uint32(comCall0(renderer.device, 37)))), // ID3D11Device::GetFeatureLevel + } + if name, ok := renderer.adapterName(); ok { + attrs = append(attrs, diag.String("adapter", name)) + } + diag.Report(diag.Info, "render", "device", "the window draws with Direct3D 11", attrs...) + }) +} + +// featureLevelName spells a D3D_FEATURE_LEVEL the way the SDK does: 0xb000 is 11_0. +func featureLevelName(level uint32) string { + return fmt.Sprintf("%d_%d", level>>12, level>>8&0xf) +} + +var dxgiDeviceIID = guid{0x54ec77fa, 0x1377, 0x44e6, [8]byte{0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}} + +// adapterDesc is DXGI_ADAPTER_DESC. +type adapterDesc struct { + Description [128]uint16 + Vendor, Device, Subsystem, Revision uint32 + Video, System, Shared uintptr + LUID [2]uint32 + Flags uint32 +} + +// adapterName is the adapter the device draws with, as DXGI names it: a display +// driver by its model, or "Microsoft Basic Render Driver" for WARP. +func (renderer *renderer) adapterName() (string, bool) { + var device, adapter uintptr + if renderer.device == 0 || hresult(comCall2(renderer.device, 0, uintptr(unsafe.Pointer(&dxgiDeviceIID)), uintptr(unsafe.Pointer(&device)))) != nil { + return "", false + } + defer release(&device) + // IDXGIDevice::GetAdapter, IDXGIAdapter::GetDesc. + if hresult(comCall1(device, 7, uintptr(unsafe.Pointer(&adapter)))) != nil { + return "", false + } + defer release(&adapter) + var desc adapterDesc + if hresult(comCall1(adapter, 8, uintptr(unsafe.Pointer(&desc)))) != nil { + return "", false + } + return syscall.UTF16ToString(desc.Description[:]), true +} + // deviceLost reports whether the renderer's device is gone. It asks the device // itself (ID3D11Device::GetDeviceRemovedReason), which any failing call can then // be blamed on. diff --git a/internal/platform/windows/materials_windows.go b/internal/platform/windows/materials_windows.go index 15ac77f0d..d12423027 100644 --- a/internal/platform/windows/materials_windows.go +++ b/internal/platform/windows/materials_windows.go @@ -3,6 +3,7 @@ package windows import ( "unsafe" + "github.com/vivaui/viva/internal/diag" "github.com/vivaui/viva/internal/platform" ) @@ -74,8 +75,11 @@ func (renderer *renderer) initializeComposition(software bool) bool { if !renderer.composition { return false } - if err := renderer.createCompositionDevice(software); err == nil { - if err := renderer.createResources(); err == nil { + err := renderer.createCompositionDevice(software) + if err == nil { + err = renderer.createResources() + if err == nil { + renderer.describeDevice() return true } } @@ -83,6 +87,11 @@ func (renderer *renderer) initializeComposition(software bool) bool { renderer.releaseDevice() renderer.composition = false restoreWindowRedirection(renderer.window) + if diag.Enabled(diag.Warn) { + diag.Report(diag.Warn, "render", "composition-fallback", + "DirectComposition could not be made, so the window presents through its own swap chain", + diag.String("error", err.Error())) + } return false } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 770453f5c..f2cfc6989 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -129,6 +129,9 @@ func rectangleScissor(batch compositingBatch, scale float32, width, height int) type renderer struct { drawScratch drawScratch // what draw hands Direct3D by address compositionState + // software says the device is WARP, Microsoft's software rasterizer, rather + // than the display driver, when the driver could not be used or was skipped. + software bool window, device, context, swap, target uintptr rectangleVertex, rectangleFragment, textVertex, textFragment uintptr buffer, view, constants, blend, textBlend, raster, sampler uintptr @@ -260,6 +263,7 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { release(&renderer.device) continue } + renderer.software = driver == 5 if err := renderer.createWindowSwapChain(); err != nil { failure = err release(&renderer.context) @@ -267,7 +271,11 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { release(&renderer.swap) continue } - return renderer.createResources() + err := renderer.createResources() + if err == nil { + renderer.describeDevice() + } + return err } if failure == nil { failure = fmt.Errorf("no Direct3D driver type was tried") diff --git a/internal/platform/windows/secret_windows.go b/internal/platform/windows/secret_windows.go index fa41934f3..3b0591c89 100644 --- a/internal/platform/windows/secret_windows.go +++ b/internal/platform/windows/secret_windows.go @@ -50,6 +50,12 @@ func secretTarget(service, account string) (*uint16, error) { func secretError(operation string, code syscall.Errno) error { switch code { case errorNotFound: + if operation == "write" { + // Nothing was being looked for: a write the store cannot place + // means it has nowhere to keep credentials for this logon, which + // is "no secret store" to the caller, not a missing secret. + return fmt.Errorf("%w: %s: %v", platform.ErrSecretStoreUnavailable, operation, code) + } return platform.ErrSecretNotFound case errorAccessDenied: return fmt.Errorf("%w: %s: %v", platform.ErrSecretDenied, operation, code) diff --git a/internal/platform/windows/secret_windows_test.go b/internal/platform/windows/secret_windows_test.go new file mode 100644 index 000000000..544b843c8 --- /dev/null +++ b/internal/platform/windows/secret_windows_test.go @@ -0,0 +1,23 @@ +package windows + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +// A write that reports ERROR_NOT_FOUND must not look like a missing secret: +// StoreSecret promises ErrSecretNotFound never comes from it, and an +// application that stores a key on first use would otherwise surface the +// sentinel as its save error. +func TestSecretWriteNotFoundIsAnUnavailableStore(t *testing.T) { + if err := secretError("write", errorNotFound); !errors.Is(err, platform.ErrSecretStoreUnavailable) || errors.Is(err, platform.ErrSecretNotFound) { + t.Fatalf("write not found = %v, want the store unavailable", err) + } + for _, operation := range []string{"read", "delete"} { + if err := secretError(operation, errorNotFound); !errors.Is(err, platform.ErrSecretNotFound) { + t.Fatalf("%s not found = %v, want ErrSecretNotFound", operation, err) + } + } +} diff --git a/internal/platform/windows/watermark_windows.go b/internal/platform/windows/watermark_windows.go index d8cf74232..8d0ed73ee 100644 --- a/internal/platform/windows/watermark_windows.go +++ b/internal/platform/windows/watermark_windows.go @@ -144,13 +144,20 @@ func (overlay *watermarkOverlay) close() { // raiseWatermark is the only stacking entry point. New native child/owned windows // must call it after changing the native view tree. func (state *windowState) raiseWatermark() { - if state.watermark != nil && state.watermark.window != 0 { - level := ^uintptr(1) // HWND_NOTOPMOST: match the owner, including demotion. - if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { - level = ^uintptr(0) - } - setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // HWND_TOP, NOMOVE|NOSIZE|NOACTIVATE + if state.watermark == nil || state.watermark.window == 0 { + return } + // The overlay takes its owner's topmost level, at the top of that level. + // HWND_NOTOPMOST would not do alone: it has no effect on a window that is + // not topmost, so a popup shown after the overlay would stay above it and + // see no watermark. HWND_TOP and HWND_TOPMOST always reorder. + level := uintptr(0) // HWND_TOP: the top of the non-topmost group, popup or not. + if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(0) // HWND_TOPMOST: the top of the topmost group, with the bit. + } else if style, err := readDecorationStyle(state.watermark.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(1) // HWND_NOTOPMOST: a stale topmost bit the owner lost is dropped here, above the popups. + } + setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // NOMOVE|NOSIZE|NOACTIVATE } func (state *windowState) syncWatermark() error { diff --git a/tools/patchgen/patchgen.go b/tools/patchgen/patchgen.go index f0a5d5636..aefbb7c1d 100644 --- a/tools/patchgen/patchgen.go +++ b/tools/patchgen/patchgen.go @@ -263,11 +263,12 @@ func extractPayload(archive, goos, arch, executable string) (root, kind string, removeTree() return "", "", nil, fmt.Errorf("patchgen: Linux payloads come from a .tar.gz, not %s", filepath.Base(archive)) } - if err := extractTarGz(archive, directory); err != nil { + executables, err := extractTarGz(archive, directory) + if err != nil { removeTree() return "", "", nil, err } - program, err := findExecutable(directory, executable) + program, err := findExecutable(directory, executable, executables) if err != nil { removeTree() return "", "", nil, err @@ -287,30 +288,27 @@ func extractPayload(archive, goos, arch, executable string) (root, kind string, } } -// findExecutable finds the program in an unpacked Linux archive. A named -// executable wins; otherwise the archive must hold one executable besides -// install.sh. -func findExecutable(root, name string) (string, error) { +// findExecutable finds the program in an unpacked Linux archive, among the +// files the archive's tar headers marked executable (see extractTarGz): the +// header is the only place that fact survives on a host whose file system does +// not keep it, such as Windows, where every regular file reads back mode 0666. +// A named executable wins; otherwise the archive must hold one executable +// besides install.sh. +func findExecutable(root, name string, executables []string) (string, error) { var named, candidates []string - err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { - if err != nil || entry.IsDir() { - return err - } - info, err := entry.Info() - if err != nil { - return err + for _, entry := range executables { + if filepath.Base(entry) == "install.sh" { + continue } - if !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 || entry.Name() == "install.sh" { - return nil + path := filepath.Join(root, filepath.FromSlash(entry)) + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() { + continue } - if name != "" && entry.Name() == name { + if name != "" && filepath.Base(entry) == name { named = append(named, path) } candidates = append(candidates, path) - return nil - }) - if err != nil { - return "", err } if len(named) == 1 { return named[0], nil @@ -380,58 +378,82 @@ func extractZip(archive, destination string) error { } // extractTarGz unpacks a tar.gz, refusing absolute paths and entries that -// climb out of destination. -func extractTarGz(archive, destination string) error { +// climb out of destination. It returns the slash paths of the regular files +// whose header carries an execution bit, in path order: see findExecutable. +func extractTarGz(archive, destination string) ([]string, error) { file, err := os.Open(archive) if err != nil { - return err + return nil, err } defer file.Close() gz, err := gzip.NewReader(file) if err != nil { - return err + return nil, err } defer gz.Close() reader := tar.NewReader(gz) + var marked map[string]bool for { header, err := reader.Next() if err == io.EOF { - return nil + return sortedKeys(marked), nil } if err != nil { - return err + return nil, err } target, err := safeJoin(destination, header.Name) if err != nil { - return err + return nil, err } switch header.Typeflag { case tar.TypeDir: if err := os.MkdirAll(target, 0o755); err != nil { - return err + return nil, err } case tar.TypeReg: if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { - return err + return nil, err } output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(header.Mode)&0o777) if err != nil { - return err + return nil, err } _, copyErr := io.Copy(output, reader) closeErr := output.Close() if copyErr != nil { - return copyErr + return nil, copyErr } if closeErr != nil { - return closeErr + return nil, closeErr + } + // The execution bits travel in the header, which is the only record + // of them a host without them (Windows) can consult later. A name + // the archive repeats is the last one's file, so keep only it. + if header.Mode&0o111 != 0 { + if marked == nil { + marked = map[string]bool{} + } + marked[header.Name] = true + } else { + delete(marked, header.Name) } default: - return fmt.Errorf("patchgen: %s is not a regular file or directory", header.Name) + return nil, fmt.Errorf("patchgen: %s is not a regular file or directory", header.Name) } } } +// sortedKeys names the marked entries in path order, the order the tree walk +// they replace reported. +func sortedKeys(marked map[string]bool) []string { + names := make([]string, 0, len(marked)) + for name := range marked { + names = append(names, name) + } + sort.Strings(names) + return names +} + func safeJoin(root, name string) (string, error) { clean := filepath.Clean(filepath.FromSlash(name)) if filepath.IsAbs(clean) || clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) { diff --git a/tools/patchgen/patchgen_test.go b/tools/patchgen/patchgen_test.go index 750d46990..6ae7d66e2 100644 --- a/tools/patchgen/patchgen_test.go +++ b/tools/patchgen/patchgen_test.go @@ -7,18 +7,35 @@ import ( "compress/gzip" "os" "path/filepath" + "strings" "testing" "github.com/vivaui/viva/update" ) func writeTarGz(t *testing.T, path, root string, files map[string][]byte) { + t.Helper() + modes := make(map[string]int64, len(files)) + for name := range files { + modes[name] = 0o755 + } + writeTarGzModes(t, path, root, files, modes) +} + +// writeTarGzModes writes a tar.gz whose headers carry the given modes, so a +// test decides what the archive says is executable, whatever the host keeps on +// its own file system. +func writeTarGzModes(t *testing.T, path, root string, files map[string][]byte, modes map[string]int64) { t.Helper() var encoded bytes.Buffer gz := gzip.NewWriter(&encoded) writer := tar.NewWriter(gz) for name, data := range files { - header := &tar.Header{Name: root + "/" + name, Mode: 0o755, Size: int64(len(data)), Typeflag: tar.TypeReg} + mode, ok := modes[name] + if !ok { + t.Fatalf("%s has no mode", name) + } + header := &tar.Header{Name: root + "/" + name, Mode: mode, Size: int64(len(data)), Typeflag: tar.TypeReg} if err := writer.WriteHeader(header); err != nil { t.Fatal(err) } @@ -109,6 +126,89 @@ func TestWriteLinuxPatch(t *testing.T) { } } +// TestWriteLinuxPatchPicksTheOnlyExecutableByArchiveMode pins what a Windows +// host cannot re-derive by statting the unpacked tree: the execution bits of +// the program come from the tar header, and the one regular file that has them +// (install.sh aside) is the patch's payload with no name in the manifest. +func TestWriteLinuxPatchPicksTheOnlyExecutableByArchiveMode(t *testing.T) { + dir := t.TempDir() + oldArchive := filepath.Join(dir, "app-1.0.0-linux-amd64.tar.gz") + newArchive := filepath.Join(dir, "app-1.1.0-linux-amd64.tar.gz") + oldFiles := map[string][]byte{ + "app": []byte("the old program, with a fair amount of content"), + "install.sh": []byte("#!/bin/sh\n"), + "README.txt": []byte("read me"), + } + oldModes := map[string]int64{"app": 0o755, "install.sh": 0o755, "README.txt": 0o644} + newFiles := map[string][]byte{ + "app": []byte("the new program, with a fair amount of content and more"), + "install.sh": []byte("#!/bin/sh\n"), + "README.txt": []byte("read me"), + } + newModes := map[string]int64{"app": 0o755, "install.sh": 0o755, "README.txt": 0o644} + writeTarGzModes(t, oldArchive, "app-1.0.0-linux-amd64", oldFiles, oldModes) + writeTarGzModes(t, newArchive, "app-1.1.0-linux-amd64", newFiles, newModes) + patchPath := filepath.Join(dir, "app.patch") + file, err := os.Create(patchPath) + if err != nil { + t.Fatal(err) + } + manifest, err := Write(Request{ + App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", OldArchive: oldArchive, NewArchive: newArchive, Output: file, + }) + file.Close() + if err != nil { + t.Fatal(err) + } + if manifest.Payload != "file" || len(manifest.Files) != 1 || manifest.Files[0].Path != "app" { + t.Fatalf("manifest = %+v", manifest) + } +} + +// TestWriteLinuxPatchRefusesAProgramWithoutExecutionBits keeps a file that the +// archive does not mark executable from being picked by name, whatever the +// host's file system would say about the unpacked copy. +func TestWriteLinuxPatchRefusesAProgramWithoutExecutionBits(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "app-1.0.0-linux-amd64.tar.gz") + writeTarGzModes(t, archive, "app-1.0.0-linux-amd64", map[string][]byte{ + "app": []byte("the old program"), + }, map[string]int64{"app": 0o644}) + file, err := os.Create(filepath.Join(dir, "app.patch")) + if err != nil { + t.Fatal(err) + } + defer file.Close() + _, err = Write(Request{ + App: "dev.example.notes", FromVersion: "1.0.0", ToVersion: "1.1.0", + OS: "linux", Arch: "amd64", OldArchive: archive, NewArchive: archive, + Executable: "app", Output: file, + }) + if err == nil || !strings.Contains(err.Error(), "holds no executable") { + t.Fatalf("Write() = %v, want an archive with no executable", err) + } +} + +// TestFindExecutableTrustsTheArchiveNotTheDisk pins the fix's reason to exist: +// an unpacked copy whose file has no execution bit on disk (every file reads +// back 0666 on Windows) is still the program the archive marked executable. +// It holds on every host, so a regression to a disk-mode check fails here too. +func TestFindExecutableTrustsTheArchiveNotTheDisk(t *testing.T) { + dir := t.TempDir() + program := filepath.Join(dir, "app") + if err := os.WriteFile(program, []byte("the program"), 0o644); err != nil { + t.Fatal(err) + } + got, err := findExecutable(dir, "", []string{"app"}) + if err != nil { + t.Fatalf("findExecutable() error = %v", err) + } + if got != program { + t.Fatalf("findExecutable() = %q, want %q", got, program) + } +} + func TestWriteDarwinPatch(t *testing.T) { dir := t.TempDir() oldArchive := filepath.Join(dir, "app-1.0.0-darwin-arm64.zip") diff --git a/ui/carousel/carousel.go b/ui/carousel/carousel.go index ccd56eba2..78a10edba 100644 --- a/ui/carousel/carousel.go +++ b/ui/carousel/carousel.go @@ -56,6 +56,11 @@ type Geometry = components.CarouselGeometry type State struct { // Orientation selects the content axis. The zero value is horizontal. Orientation components.CarouselOrientation + // Direction sets the reading direction of a horizontal carousel. The zero + // value is LTR. Under RTL the slides read right to left, the offset reveals + // slides on the left of the first one, and the previous and next controls + // swap sides; see components.Carousel.Direction. + Direction components.Direction // ItemCount is the number of caller-owned slides. ItemCount int // Index is the selected slide. It is clamped by the component. @@ -170,6 +175,9 @@ func (c *State) draw(d *ui.DrawContext) { if c.Orientation == components.CarouselVertical { strip = strip.Vertical() } + if c.Direction != 0 { + strip = strip.Direction(c.Direction) + } if c.Disabled { strip = strip.Disabled() } @@ -187,10 +195,11 @@ func (c *State) draw(d *ui.DrawContext) { func (c *State) Geometry() components.CarouselGeometry { return c.geometry } // ItemBounds maps one slide of an evenly divided content extent to page -// coordinates: Index along the axis, the viewport extent across it. It returns -// an empty rectangle for an index outside the item count. Use it in Draw for -// the common one-slide-per-view layout; a caller with items of different -// extents maps them from Geometry.Content instead. +// coordinates: Index along the axis at the reading direction's edge of the +// content — its left in LTR and its right in RTL — and the viewport extent +// across it. It returns an empty rectangle for an index outside the item count. +// Use it in Draw for the common one-slide-per-view layout; a caller with items +// of different extents maps them from Geometry.Content instead. func (c *State) ItemBounds(geometry components.CarouselGeometry, index int) gfx.Rect { if index < 0 || index >= c.ItemCount || c.ItemCount <= 0 { return gfx.Rect{} @@ -207,8 +216,12 @@ func (c *State) ItemBounds(geometry components.CarouselGeometry, index int) gfx. Width: geometry.Viewport.Width, Height: itemExtent, } } + x := content.X + float32(index)*itemExtent + if c.Direction.IsRTL() { + x = content.X + content.Width - float32(index+1)*itemExtent + } return gfx.Rect{ - X: content.X + float32(index)*itemExtent, Y: content.Y, + X: x, Y: content.Y, Width: itemExtent, Height: geometry.Viewport.Height, } } diff --git a/ui/carousel/carousel_test.go b/ui/carousel/carousel_test.go index 66c73504b..2d1638351 100644 --- a/ui/carousel/carousel_test.go +++ b/ui/carousel/carousel_test.go @@ -3,6 +3,7 @@ package carousel_test import ( "testing" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/carousel" @@ -145,6 +146,44 @@ func TestViewPaintsGeometryAndRoutesInput(t *testing.T) { } } +// An RTL state mirrors the placed slides and the controls: the selected slide +// keeps the viewport, the first slide stands at the viewport's right edge, and +// the previous control stands right of the viewport with the next one on its +// left. +func TestRTLDirectionMirrorsSlidesAndControls(t *testing.T) { + m := new(model) + m.open(t, carousel.Horizontal) + m.view.Direction = components.RTL + draw(m.page, m.canvas, m.viewPage) + + geometry := m.view.Geometry() + if geometry.Content.Width != 960 || geometry.Offset != 320 { + t.Fatalf("RTL content = %+v offset %g, want 960 and 320", geometry.Content, geometry.Offset) + } + // The selected slide still fills the viewport; the first one sits entirely + // to the right of it and the last one entirely to its left. + selected := m.view.ItemBounds(geometry, 1) + if selected != geometry.Viewport { + t.Fatalf("RTL selected slide = %+v, want the viewport", selected) + } + first := m.view.ItemBounds(geometry, 0) + if first.X != geometry.Viewport.X+geometry.Viewport.Width || first.Width != 320 { + t.Fatalf("RTL first slide = %+v, want one viewport right of it", first) + } + last := m.view.ItemBounds(geometry, 2) + if last.X+last.Width != geometry.Viewport.X { + t.Fatalf("RTL last slide = %+v, want one viewport left of it", last) + } + previous := hit(t, m.canvas, "Previous slide") + next := hit(t, m.canvas, "Next slide") + if previous.Bounds.X < geometry.Viewport.X+geometry.Viewport.Width { + t.Fatalf("RTL previous control = %+v, want it right of the viewport", previous.Bounds) + } + if next.Bounds.X+next.Bounds.Width > geometry.Viewport.X { + t.Fatalf("RTL next control = %+v, want it left of the viewport", next.Bounds) + } +} + // A click on a navigation control is read with Clicked after View, and a // different identity is not reported. func TestViewReportsClicksForCallerIdentities(t *testing.T) { diff --git a/ui/color_live_test.go b/ui/color_live_test.go new file mode 100644 index 000000000..cfa708f28 --- /dev/null +++ b/ui/color_live_test.go @@ -0,0 +1,71 @@ +package ui_test + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "testing" +) + +func TestColorPickerLiveEditsBoundDraft(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.ColorPicker(c, &state, &color, "Accent").Live(true) + }) + }) + d.click("Accent") + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == "OK" || hit.Label == "Cancel" || hit.Label == "Clear" { + t.Fatalf("live picker exposes confirmation action %q", hit.Label) + } + } + d.click("Saturation and brightness") + if color == gfx.RGB(255, 0, 0) || !state.Applied() || !state.Open() { + t.Fatal("plane did not update the bound draft while keeping the picker open") + } + before := color + d.key(gfx.KeyRight) + if color == before || !state.Applied() { + t.Fatal("keyboard adjustment did not update the draft") + } + d.click("Hex color") + state.SetHexText("#123456") + d.key(gfx.KeyEnter) + if uint8(color.Red*255+.5) != 18 || uint8(color.Green*255+.5) != 52 || uint8(color.Blue*255+.5) != 86 || state.Open() { + t.Fatalf("hex edit = %v, open = %v", color, state.Open()) + } + d.click("Accent") + d.click("Hue") + before = color + d.key(gfx.KeyEscape) + if state.Open() || color != before { + t.Fatal("Escape did not retain the live edit") + } +} + +func TestColorPickerLiveInsideDialogKeepsDraftAndOutsideAction(t *testing.T) { + var state ui.ColorPickerState + color := gfx.RGB(255, 0, 0) + saved := false + d := openPage(t, func(c ui.C) { + dialog := ui.Dialog(c, ui.DialogSpec{Title: "Theme editor", Width: 480, Height: 500, Layer: 600}) + dialog.Body(func() { + ui.ColorPicker(c, &state, &color, "Accent").Live(true) + }) + dialog.Footer(func() { + if ui.Button(c, "Save theme").Clicked() { + saved = true + } + }) + }) + d.click("Accent") + d.click("Saturation and brightness") + if color == gfx.RGB(255, 0, 0) { + t.Fatal("dialog picker did not edit draft") + } + d.click("Save theme") + if !saved || state.Open() { + t.Fatal("outside action did not save and close picker") + } +} diff --git a/ui/color_paint.go b/ui/color_paint.go index 6c21c4303..74eae18bc 100644 --- a/ui/color_paint.go +++ b/ui/color_paint.go @@ -55,12 +55,15 @@ func paintColorPickerPanel(s *ColorPickerState, d *DrawContext, c C, ID gfx.ID, } empty = empty || look.GetEmpty() options := components.ColorPickerOptions{ - IDs: ids, Labels: labels, Value: value, Open: s.GetOpen(), Empty: empty, ShowAlpha: s.ShowsAlpha(), + IDs: ids, Labels: labels, Value: value, Open: s.GetOpen(), Empty: empty, ShowAlpha: s.ShowsAlpha(), Live: s.Live(), RoundTrigger: look.GetRound(), TriggerIcon: look.GetIcon(), SaturationText: s.Summary, Viewport: Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, Layer: s.GetLayer(), } if s.GetOpen() { options.Scope = s.GetHandlers().GetParts().At(8) + if s.Live() { + options.Scope = canvas.FocusScope() + } options.Hex = s.HexPtr().Snapshot(c.GetF(), ids.Hex, labels.Hex, "#3B82F6") if s.GetInvalid() { options.Error = labels.InvalidColor diff --git a/ui/list_follow_test.go b/ui/list_follow_test.go index 8afb14d56..4545dd4a5 100644 --- a/ui/list_follow_test.go +++ b/ui/list_follow_test.go @@ -100,3 +100,57 @@ func TestListFollowReachesTheEndOfALongListItStartsWith(t *testing.T) { t.Fatalf("the last row painted %v (Visible %v, at the end %v)", d.has("row 4999"), visibleOf(&m.list), m.list.AtEnd()) } } + +// ScrollTo on a List that follows its end leaves the end, as a scroll by the user +// does: the request is applied when the list is declared, before the Box it returns +// says Follow(true) again, and the rows that arrive after it do not pull the list +// back to the end. ScrollToEnd follows the end again. +func TestListScrollToLeavesTheEndOfAFollowingList(t *testing.T) { + m := newLogRows(400) + d := openPage(t, followingRows(m)) + settle := func(step string) { + t.Helper() + for frames := 0; d.driver.Transitioning(); frames++ { + if frames == 10 { + t.Fatalf("%s: the list asked for ten paints", step) + } + if err := d.driver.Advance(16 * time.Millisecond); err != nil { + t.Fatal(err) + } + } + d.repaint() + } + d.repaint() + settle("start") + if !m.list.AtEnd() { + t.Fatalf("the following list did not start at its end (Visible %v)", visibleOf(&m.list)) + } + const target = 20 + label := "row " + strconv.Itoa(target) + m.list.ScrollTo(target, ui.ListStart) + d.repaint() + settle("ScrollTo") + if !d.has(label) || m.list.AtEnd() { + t.Fatalf("after ScrollTo(%d) %s painted %v, at the end %v (Visible %v)", target, label, d.has(label), m.list.AtEnd(), visibleOf(&m.list)) + } + area := d.ListArea("Rows") + if top := d.hit(label).Bounds.Y - area.Y; top < -2 || top > 2 { + t.Fatalf("row %d is %v px from the top of the list, want it at the top", target, top) + } + m.n += 5 + d.repaint() + settle("rows arrived") + if !d.has(label) || m.list.AtEnd() { + t.Fatalf("rows that arrived after ScrollTo moved the list: %s painted %v, at the end %v (Visible %v)", label, d.has(label), m.list.AtEnd(), visibleOf(&m.list)) + } + m.list.ScrollToEnd() + d.repaint() + settle("ScrollToEnd") + m.n += 5 + d.repaint() + settle("rows arrived at the end") + last := "row " + strconv.Itoa(m.n-1) + if !d.has(last) || !m.list.AtEnd() { + t.Fatalf("after ScrollToEnd the list did not follow its end: %s painted %v, at the end %v (Visible %v)", last, d.has(last), m.list.AtEnd(), visibleOf(&m.list)) + } +} diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index ff2ecdc0a..5d893c329 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -269,6 +269,59 @@ func run(application *app.Application) error { } ``` +## Notifications that respond to a click + +`Application.ShowNotification` posts a notification and returns a `NotificationHandle`. `OnActivate` runs when the user clicks it, `OnError` reports delivery failures, and `Close` withdraws it. Check `app.Supports(app.CapabilityNotificationActivation)` first: where the platform cannot report clicks, the notification is not interactive, and the example shows a message instead of controls. On macOS the application must be packaged and allowed to show notifications. + +Run `go run ./examples/guides/notifications` to try the complete example. + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} +``` + ## Boundaries worth knowing - Linux file dialogs and notifications use the desktop's portal and notification service over D-Bus, and start an installed desktop utility only on a desktop without them; URL dispatch always does. Viva does not bundle GTK or Qt. diff --git a/website/content/guides/en/windows.md b/website/content/guides/en/windows.md index da6563297..9f32e120c 100644 --- a/website/content/guides/en/windows.md +++ b/website/content/guides/en/windows.md @@ -205,6 +205,37 @@ When a `Menu` is set, a press opens the system's own native menu, built by calli `StatusItem.SetIcon`, `SetTooltip` and `Remove` change or remove the icon later. +## Watermarks + +`Config.Watermark` draws repeated text over the whole window, including embedded native views, without taking input. An empty `Text` turns it off. Native support is reported by `app.Supports(app.CapabilityWindowWatermark)`; hosts without it ignore the setting, so the example sets the watermark only when the capability is present. + +Run `go run ./examples/guides/watermark` to try the complete example. + + +```go +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} +``` + ## What differs between platforms The same call can only say what the platform can say. A status icon reports its rectangle on macOS and Windows but only the click point on Linux. A panel is dismissed by losing key status, by deactivation or by `FocusOut` respectively. A new icon in a full macOS menu bar can be hidden by the system, notably next to the notch, and Windows 11 shows a new icon in the overflow flyout until the user promotes it. `docs/conformance.md` in the repository lists these, and what must be checked by hand on each platform. diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 5fabfecd5..625b59520 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -259,6 +259,59 @@ func run(application *app.Application) error { } ``` +## 可以响应点击的通知 + +`Application.ShowNotification` 发出通知并返回 `NotificationHandle`。用户点击时执行 `OnActivate`,投递失败通过 `OnError` 报告,`Close` 撤回通知。先用 `app.Supports(app.CapabilityNotificationActivation)` 检查:平台无法回报点击时,通知不可交互,示例会改为显示提示文字而不是控件。macOS 上应用必须打包,并获准显示通知。 + +执行 `go run ./examples/guides/notifications` 可以运行完整示例。 + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} +``` + ## 值得了解的边界 - Linux 上的文件对话框、URL 分发和通知,会在用户请求时启动已安装的桌面工具。Viva 不捆绑 GTK、Qt 或 D-Bus 栈。 diff --git a/website/content/guides/zh/windows.md b/website/content/guides/zh/windows.md index b8b1e9165..2ff240380 100644 --- a/website/content/guides/zh/windows.md +++ b/website/content/guides/zh/windows.md @@ -171,6 +171,37 @@ func addTray(application *app.Application, window *app.Window, icon app.StatusIc 之后可以用 `StatusItem.SetIcon`、`SetTooltip` 和 `Remove` 修改或移除图标。 +## 水印 + +`Config.Watermark` 在整个窗口上绘制重复文字,包括嵌入的原生视图,且不接收输入;`Text` 为空时关闭。原生支持由 `app.Supports(app.CapabilityWindowWatermark)` 报告;不支持的宿主会忽略该设置,因此示例只在具备该能力时设置水印。 + +执行 `go run ./examples/guides/watermark` 可以运行完整示例。 + + +```go +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} +``` + ## 各平台的差异 同一个调用只能说出平台能说的东西。状态栏图标在 macOS 和 Windows 上报告它的矩形,在 Linux 上只报告点击点;面板分别因失去 key 状态、窗口停用或 `FocusOut` 而关闭。在已满的 macOS 菜单栏里,新图标可能被系统隐藏,尤其是刘海旁边;Windows 11 会把新图标放进溢出浮层,直到用户把它提升出来。仓库中的 `docs/conformance.md`列出了这些,以及每个平台必须手动检查的项目。 diff --git a/window/text_input.go b/window/text_input.go index 9a3de2cf0..096a6cb14 100644 --- a/window/text_input.go +++ b/window/text_input.go @@ -151,6 +151,11 @@ type TextInputContext struct { FontWeight float32 TextColor gfx.Color Alignment gfx.Alignment + // TextScroll is how far a field that paints its own line moved it left to keep its + // caret in view (gfx.HitOptions.TextScroll): the text the component drew starts that + // far before TextBounds, so the pointer and the input method's window are placed from + // there. It is 0 for a field the platform editor paints, which scrolls its own line. + TextScroll float32 // HideNativeOverlays requests that the platform editor keep its own caret // and selection invisible. Editing, IME and clipboard behavior are // unchanged. Components that paint those overlays themselves set it.