Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ WebView and no bundled rendering runtime.
by the application.
- Native fullscreen through `Window.SetFullscreen`, with `Config.OnFullscreen`
reporting system transitions and restoring normal window placement on exit.
- `Window.SetTitle` changes a window's title after it opens: the system title
bar, the task switcher and the taskbar or Dock window list.
- Explicit multi-window applications through `app.RunApplication`: every
window owns independent retained paint, focus, input, text, invalidation, and
close state, and the native loop exits after the final window closes.
Expand Down
5 changes: 5 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ type Config struct {
// text input and input methods behave as before. Handled and Repaint apply
// as for OnKey.
OnModifierTap func(event gfx.ModifierTapEvent) gfx.EventResult
// OnFocusLost is called when the window loses the keyboard to another window
// or application, after the keys that were down are released. It is how an
// application saves or hides what only makes sense while it has the user's
// attention. Its Repaint asks for a new frame. Native windows only.
OnFocusLost func() gfx.EventResult
// OnScroll receives normalized pixel deltas and the hovered hit target.
// Handled suppresses the window's default canvas scroll offset.
OnScroll func(event gfx.ScrollEvent) gfx.EventResult
Expand Down
38 changes: 38 additions & 0 deletions app/focus_lost_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//go:build darwin || windows || linux

package app

import (
"testing"

"github.com/vivaui/viva/gfx"
)

func TestFocusLostIsReportedAfterKeysAreReleased(t *testing.T) {
var keys []gfx.KeyEvent
lost := 0
heldWhenLost := -1
driver, err := NewDriver(Config{
Width: 320, Height: 180,
Paint: func(canvas *gfx.Canvas, _ gfx.Size) {},
OnKey: func(event gfx.KeyEvent) gfx.EventResult { keys = append(keys, event); return gfx.EventResult{} },
OnFocusLost: func() gfx.EventResult {
lost++
heldWhenLost = len(keys)
return gfx.EventResult{Repaint: true}
},
}, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(driver.Close)
if err := driver.LoseFocus(); err != nil {
t.Fatal(err)
}
if lost != 1 {
t.Fatalf("OnFocusLost called %d times, want 1", lost)
}
if heldWhenLost != len(keys) {
t.Fatalf("OnFocusLost ran before the held keys were released: %d of %d key events", heldWhenLost, len(keys))
}
}
20 changes: 14 additions & 6 deletions app/painter.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ type painter struct {
onScroll func(gfx.ScrollEvent) gfx.EventResult
// onModifierTap and tap recognize a modifier pressed and released on its own.
onModifierTap func(gfx.ModifierTapEvent) gfx.EventResult
tap input.ModifierTap
onFileDrop func(gfx.FileDropEvent) gfx.EventResult
onResize func(gfx.Size)
// onFocusLost hears that the window lost the keyboard (Config.OnFocusLost).
onFocusLost func() gfx.EventResult
tap input.ModifierTap
onFileDrop func(gfx.FileDropEvent) gfx.EventResult
onResize func(gfx.Size)
// scale is the display's device pixels per logical pixel, zero when the platform
// does not report it (see platform.Size): the canvas then keeps the scale it was given.
scale float32
Expand Down Expand Up @@ -158,6 +160,7 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D
onShortcut: config.OnShortcut,
onScroll: config.OnScroll,
onModifierTap: config.OnModifierTap,
onFocusLost: config.OnFocusLost,
onFileDrop: config.OnFileDrop,
onResize: config.OnResize,
textInput: config.TextInput,
Expand Down Expand Up @@ -612,17 +615,22 @@ func (painter *painter) releaseKeys() bool {

// focusLostHandler is what a window hands the platform for the loss of the
// keyboard: it releases the keys that were down, since their releases will go
// to whatever window has the keyboard now.
// to whatever window has the keyboard now, and tells the application.
func (painter *painter) focusLostHandler() platform.FocusLostHandler {
if painter.onKey == nil && painter.onModifierTap == nil {
if painter.onKey == nil && painter.onModifierTap == nil && painter.onFocusLost == nil {
return nil
}
return painter.focusLost
}

func (painter *painter) focusLost() (platform.Frame, error) {
painter.tap.Cancel()
if !painter.releaseKeys() {
repaint := painter.releaseKeys()
if painter.onFocusLost != nil {
response := painter.onFocusLost()
repaint = painter.applyEventResult(response) || response.Repaint || repaint
}
if !repaint {
return platform.Frame{}, nil
}
return painter.repaint()
Expand Down
24 changes: 24 additions & 0 deletions app/title.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package app

import "fmt"

type titleControl interface {
SetTitle(string) error
}

// SetTitle changes the window's title: the text of its system title bar, the
// task switcher and the taskbar or Dock window list. A window with
// WindowCustomTitlebar keeps no visible system title bar, but the title is still
// what the system lists and what assistive technology reads. Calls are safe from
// any goroutine; the change is applied on the window's thread. Unsupported hosts
// return an error wrapping ErrUnsupported.
func (window *Window) SetTitle(title string) error {
if window == nil || window.closed.Load() {
return fmt.Errorf("app: window is closed")
}
control, ok := window.control.(titleControl)
if !ok {
return fmt.Errorf("%w: window titles", ErrUnsupported)
}
return control.SetTitle(title)
}
41 changes: 41 additions & 0 deletions app/title_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//go:build darwin || windows || linux

package app

import (
"errors"
"testing"
)

type titleTestControl struct {
fakeWindow
titles []string
}

func (control *titleTestControl) SetTitle(title string) error {
control.titles = append(control.titles, title)
return nil
}

func TestSetTitleDelegatesToTheHost(t *testing.T) {
control := &titleTestControl{}
window := &Window{control: control}
if err := window.SetTitle("project – main.go"); err != nil {
t.Fatal(err)
}
if len(control.titles) != 1 || control.titles[0] != "project – main.go" {
t.Fatalf("titles = %q", control.titles)
}
window.closed.Store(true)
if err := window.SetTitle("closed"); err == nil || len(control.titles) != 1 {
t.Fatal("closed window accepted a title")
}
var missing *Window
if err := missing.SetTitle("nil"); err == nil {
t.Fatal("nil window accepted a title")
}
unsupported := &Window{control: &fakeWindow{}}
if err := unsupported.SetTitle("x"); !errors.Is(err, ErrUnsupported) {
t.Fatalf("unsupported host: %v", err)
}
}
80 changes: 74 additions & 6 deletions components/markdown.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ type MarkdownStyle struct {
// string that runs over several lines is only colored where the lexer can
// tell from the line itself. The colors come from MarkdownLook.Code.
Highlight func(language, line string, dst []MarkdownCodeRun) []MarkdownCodeRun
// Image, when set, is asked for the bitmap of every image (![alt](destination)),
// with the destination as written. The view never reads files or the network:
// an application resolves relative paths and fetches what it allows. A bitmap's
// pixels are its size in the layout, scaled down to the column and never up.
// false lays the image out as its alt text, so an application can answer once
// the image has loaded and lay the document out again.
Image func(destination string) (gfx.Bitmap, bool)
}

// MarkdownCodeClass says what a stretch of code is, which MarkdownLook.Code turns
Expand Down Expand Up @@ -167,6 +174,7 @@ type MarkdownView struct {
boxes []mdBox
links []mdLink
codes []MarkdownCode
images []mdImage
anchors []MarkdownAnchor
atoms []mdAtom
numbers []byte
Expand Down Expand Up @@ -489,11 +497,21 @@ type mdLink struct {
text, dest string
}

// mdImage is an image laid out at x, y, w by h.
type mdImage struct {
bitmap gfx.Bitmap
x, y, w, h float32
}

type mdAtom struct {
span, lo, hi int32
w, space float32 // width, and the width of the blank that follows it
brk bool // a line break
glue bool // punctuation that may not start a line
// image marks an image's atom: w by h of bitmap.
image bool
h float32
bitmap gfx.Bitmap
w, space float32 // width, and the width of the blank that follows it
brk bool // a line break
glue bool // punctuation that may not start a line
}

type mdFont struct {
Expand All @@ -503,6 +521,8 @@ type mdFont struct {

// mdLayout is the state of one Layout call.
type mdLayout struct {
// column is the widest an image may be laid out, set by inline.
column float32
v *MarkdownView
canvas *gfx.Canvas
style MarkdownStyle
Expand All @@ -519,6 +539,7 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark
if style.LineHeight <= 0 {
style.LineHeight = float32(int(style.Size*1.55 + 0.5))
}
v.images = v.images[:0]
v.pieces, v.boxes, v.links, v.codes, v.anchors, v.numbers, v.runs, v.tabs, v.tabBound, v.plain, v.spanBase = v.pieces[:0], v.boxes[:0], v.links[:0], v.codes[:0], v.anchors[:0], v.numbers[:0], v.runs[:0], v.tabs[:0], v.tabBound[:0], v.plain[:0], v.spanBase[:0]
v.bars = [markdownMaxQuote + 1]int32{}
v.face = style.MonoFace
Expand Down Expand Up @@ -1070,6 +1091,20 @@ func (l *mdLayout) atomize(spans []markdown.Span, t mdFont) {
pending = 0
continue
}
if sp.Image != "" && l.style.Image != nil {
if bitmap, ok := l.style.Image(sp.Image); ok && bitmap.Width > 0 && bitmap.Height > 0 {
w, h := float32(bitmap.Width), float32(bitmap.Height)
if column := l.column; column > 0 && w > column {
w, h = column, h*column/w
}
if pending > 0 && len(atoms) > 0 && !atoms[len(atoms)-1].brk {
atoms[len(atoms)-1].space = pending
}
pending = 0
atoms = append(atoms, mdAtom{span: int32(si), image: true, w: w, h: h, bitmap: bitmap})
continue
}
}
mono := sp.Style&markdown.Mono != 0
italic := sp.Style&markdown.Italic != 0
size, weight := t.size, spanWeight(t.weight, sp.Style)
Expand Down Expand Up @@ -1148,9 +1183,12 @@ type mdLine struct {
piece int // the open piece, or -1
lo int32
span int32
pieceP int // first piece, box and link of the line, for alignment
pieceP int // first piece, box, link and image of the line, for alignment
pieceB int
pieceL int
pieceI int
// tall is the height of the tallest image on the line.
tall float32
// grew reports that the open piece took a second atom, so its width is a
// running sum that closePiece must settle.
grew bool
Expand All @@ -1167,7 +1205,9 @@ func (l *mdLayout) inline(spans []markdown.Span, x, width, y float32, t mdFont,
if len(spans) == 0 {
return y
}
l.column = width
l.atomize(spans, t)
l.column = 0
m := mdLine{l: l, spans: spans, t: t, align: align, x0: x, width: width, y: y, piece: -1}
m.reset()
for _, a := range l.v.atoms {
Expand Down Expand Up @@ -1232,7 +1272,8 @@ func (m *mdLine) fit(a mdAtom) (mdAtom, bool) {
func (m *mdLine) reset() {
v := m.l.v
m.x, m.w, m.has, m.piece = 0, 0, false, -1
m.pieceP, m.pieceB, m.pieceL = len(v.pieces), len(v.boxes), len(v.links)
m.pieceP, m.pieceB, m.pieceL, m.pieceI = len(v.pieces), len(v.boxes), len(v.links), len(v.images)
m.tall = 0
m.measuredSpan, m.measuredLo, m.measuredHi, m.measuredEnd = -1, 0, 0, 0
m.grew = false
}
Expand Down Expand Up @@ -1261,6 +1302,9 @@ func (m *mdLine) spanPad(sp markdown.Span) float32 {
}

func (m *mdLine) exactWidth(a mdAtom) float32 {
if a.image {
return a.w
}
if a.hi <= a.lo {
return 0
}
Expand Down Expand Up @@ -1431,6 +1475,20 @@ func (m *mdLine) place(a mdAtom) {
v := l.v
sp := m.spans[a.span]
mono := sp.Style&markdown.Mono != 0
if a.image {
m.closePiece()
x := m.x0 + m.x
v.images = append(v.images, mdImage{bitmap: a.bitmap, x: x, y: m.y, w: a.w, h: a.h})
if sp.Link != "" {
v.links = append(v.links, mdLink{x: x, y: m.y, w: a.w, h: a.h, size: m.t.size, text: sp.Text, dest: sp.Link})
}
m.x += a.w
m.w = m.x
m.x += a.space
m.has = true
m.tall = max(m.tall, a.h)
return
}
if a.hi <= a.lo {
return
}
Expand Down Expand Up @@ -1553,9 +1611,13 @@ func (m *mdLine) endLine() {
for i := m.pieceL; i < len(v.links); i++ {
v.links[i].x += shift
}
for i := m.pieceI; i < len(v.images); i++ {
v.images[i].x += shift
}
}
}
m.y += m.t.line
// A line with an image is as tall as the image, with the text along its top.
m.y += max(m.t.line, m.tall+4)
m.l.lines++
m.reset()
}
Expand Down Expand Up @@ -1592,6 +1654,12 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) {
canvas.Rounded(rect, 4, look.InlineCodeFill)
}
}
for _, image := range v.images {
rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h}
if visible(rect.Y, rect.Height) {
canvas.DrawBitmap(image.bitmap, rect)
}
}
start, end := p.Selection.Range(v.plain)
if start < end && look.Selection.Alpha > 0 {
for index := range v.pieces {
Expand Down
38 changes: 38 additions & 0 deletions components/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1740,3 +1740,41 @@ func TestHeadingInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) {
t.Errorf("heading inline code selection is %v wide, want %v", rects[0].Bounds.Width, want)
}
}

func TestMarkdownImagesAreScaledToTheColumnAndPainted(t *testing.T) {
wide := gfx.Bitmap{Pix: make([]byte, 400*100*4), Width: 400, Height: 100, Stride: 400 * 4, ID: 1}
small := gfx.Bitmap{Pix: make([]byte, 20*10*4), Width: 20, Height: 10, Stride: 20 * 4, ID: 2}
style := MarkdownStyle{Size: 12, Image: func(dest string) (gfx.Bitmap, bool) {
switch dest {
case "wide.png":
return wide, true
case "small.png":
return small, true
}
return gfx.Bitmap{}, false
}}
view, _ := layoutMarkdown(t, "![a](wide.png)\n\n[![b](small.png)](https://example.com/) ![missing](gone.png)", 200, style)
if len(view.images) != 2 {
t.Fatalf("images = %+v", view.images)
}
if got := view.images[0]; got.w != 200 || got.h != 50 {
t.Errorf("a wide image is %vx%v, want 200x50", got.w, got.h)
}
if got := view.images[1]; got.w != 20 || got.h != 10 {
t.Errorf("a small image is %vx%v, want its own 20x10", got.w, got.h)
}
if view.Height() < 50 {
t.Errorf("height %v leaves no room for the image", view.Height())
}
if view.LinkCount() != 1 || view.Link(0) != "https://example.com/" {
t.Errorf("the linked badge is not a link: %d", view.LinkCount())
}
if !strings.Contains(string(view.plain), "missing") {
t.Errorf("an unresolved image shows no alt text: %q", view.plain)
}
var canvas gfx.Canvas
view.Paint(&canvas, MarkdownPaint{X: 0, Y: 0})
if len(canvas.Images()) != 2 {
t.Errorf("painted %d images", len(canvas.Images()))
}
}
Loading