diff --git a/README.md b/README.md index d54c71f46..0dd65e4e0 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/app/app.go b/app/app.go index f9de5ec32..672b5c2b7 100644 --- a/app/app.go +++ b/app/app.go @@ -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 diff --git a/app/focus_lost_test.go b/app/focus_lost_test.go new file mode 100644 index 000000000..3d8198025 --- /dev/null +++ b/app/focus_lost_test.go @@ -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)) + } +} diff --git a/app/painter.go b/app/painter.go index de08df39d..ac5a059d6 100644 --- a/app/painter.go +++ b/app/painter.go @@ -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 @@ -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, @@ -612,9 +615,9 @@ 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 @@ -622,7 +625,12 @@ func (painter *painter) focusLostHandler() platform.FocusLostHandler { 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() diff --git a/app/title.go b/app/title.go new file mode 100644 index 000000000..3ad9c3a3e --- /dev/null +++ b/app/title.go @@ -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) +} diff --git a/app/title_test.go b/app/title_test.go new file mode 100644 index 000000000..a2828d29d --- /dev/null +++ b/app/title_test.go @@ -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) + } +} diff --git a/components/markdown.go b/components/markdown.go index 5bd2dd8db..7366781db 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -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 @@ -167,6 +174,7 @@ type MarkdownView struct { boxes []mdBox links []mdLink codes []MarkdownCode + images []mdImage anchors []MarkdownAnchor atoms []mdAtom numbers []byte @@ -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 { @@ -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 @@ -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 @@ -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) @@ -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 @@ -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 { @@ -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 } @@ -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 } @@ -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 } @@ -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() } @@ -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 { diff --git a/components/markdown_test.go b/components/markdown_test.go index d076036a1..656b417a4 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -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())) + } +} diff --git a/docs/conformance.md b/docs/conformance.md index 379dfff30..f8b77d75d 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -241,6 +241,14 @@ moves). `VIVA_SCALE` overrides it for Viva alone, snapped to quarters and kept b Linux: it draws a window at 125% or 150% on a display at 100%, which is how fractional scaling was measured. The renderer puts every label texture and image on a whole device pixel. +## Window titles + +`Window.SetTitle` changes the native title after creation from any goroutine. macOS +sets the NSWindow title on the main thread, Windows posts the change to the window +thread and applies it with `SetWindowTextW` (also updating the accessibility tree's +window name), and Linux sets the GTK toplevel's title on the GTK thread. The +headless host records it in the `windows` listing. + ## Fullscreen windows `Window.SetFullscreen` requests native fullscreen; `Config.OnFullscreen` publishes diff --git a/headless/application.go b/headless/application.go index 927571479..3c149d523 100644 --- a/headless/application.go +++ b/headless/application.go @@ -149,6 +149,18 @@ func (window *headlessWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle records the title the windows command lists. +func (window *headlessWindow) SetTitle(title string) error { + window.application.mu.Lock() + defer window.application.mu.Unlock() + entry := window.application.windows[window.id] + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + entry.title = title + return nil +} + func (window *headlessWindow) Fullscreen() bool { window.application.mu.Lock() entry := window.application.windows[window.id] diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 2560cb6da..a08ff0bd9 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -375,6 +375,7 @@ int viva_application_window_frame(void *window, double *out); /* Puts the window's content area at x, y in top-left screen coordinates. */ void viva_application_move_window(void *window, double x, double y); int viva_application_set_fullscreen(void *window, int fullscreen); +int viva_application_set_title(void *window, const char *title); int viva_application_fullscreen(void *window); int viva_application_set_always_on_top(void *window, int enabled); int viva_application_run(void); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 3221b6d75..f4716fca3 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -5708,6 +5708,7 @@ - (void)confirmClose; - (void)hideWindow; - (void)showWindow; - (void)setFullscreen:(BOOL)fullscreen; +- (void)setWindowTitle:(NSString *)title; - (void)setAlwaysOnTop:(BOOL)enabled; - (BOOL)isFullscreen; - (void)reopenWindow; @@ -6250,6 +6251,20 @@ - (BOOL)isFullscreen { return (_window.styleMask & NSWindowStyleMaskFullScreen) != 0; } +- (void)setWindowTitle:(NSString *)title { + [_title release]; + _title = [title copy]; + if (_window != nil) { + _window.title = _title; + /* A new title lays the titlebar out again, and AppKit sets the zoom + * button back at the system's height without reporting the move as a + * frame change, so keepTrafficLightsCentered never hears of it. */ + if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR) { + viva_place_traffic_lights(_window, _titlebarHeight); + } + } +} + - (void)setFullscreen:(BOOL)fullscreen { _fullscreenTarget = fullscreen; if (!_fullscreenTransition && [self isFullscreen] != fullscreen) { @@ -6989,6 +7004,28 @@ int viva_application_set_fullscreen(void *window, int fullscreen) { return found; } +int viva_application_set_title(void *window, const char *title) { + __block int found = 0; + NSString *value = [[NSString alloc] initWithUTF8String:title != NULL ? title : ""]; + if (value == nil) { + value = [@"" retain]; + } + void (^work)(void) = ^{ + VivaAppDelegate *delegate = viva_find_window(window); + if (delegate != nil) { + found = 1; + [delegate setWindowTitle:value]; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + [value release]; + return found; +} + int viva_application_fullscreen(void *window) { __block int fullscreen = 0; void (^work)(void) = ^{ diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index e70709554..a7d411214 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -109,6 +109,19 @@ func (window *nativeWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle changes the NSWindow's title on the main thread. +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + value := C.CString(title) + defer C.free(unsafe.Pointer(value)) + if C.viva_application_set_title(window.token, value) == 0 { + return fmt.Errorf("darwin: window is unavailable") + } + return nil +} + func (window *nativeWindow) Fullscreen() bool { return window != nil && !window.closed.Load() && C.viva_application_fullscreen(window.token) != 0 } diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 7e9c98258..6480260ce 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -123,6 +123,13 @@ int main(void) { window.titlebarAppearsTransparent = NO; window.titlebarAppearsTransparent = YES; assertCenter(window, 18, "after the titlebar was restyled"); + // A new title lays the titlebar out too, and AppKit moves the zoom + // button back without reporting it as a frame change. + [delegate setWindowTitle:@"project"]; + assertCenter(window, 18, "after the title changed"); + assertAligned(window, "after the title changed"); + [delegate setWindowTitle:@"project - file"]; + assertAligned(window, "after the title changed again"); [delegate setAlwaysOnTop:YES]; assert(window.level == NSFloatingWindowLevel); [delegate setAlwaysOnTop:NO]; diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 62fdd2e26..c185e08f1 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -284,6 +284,17 @@ func (w *gtkWindow) SetFullscreen(fullscreen bool) error { func (w *gtkWindow) Fullscreen() bool { return w.fullscreen.Load() } +// SetTitle changes the toplevel's title on the GTK thread. +func (w *gtkWindow) SetTitle(title string) error { + w.app.enqueue(func() { + if !w.closed { + value := cString(title) + w.g.windowSetTitle(w.toplevel, &value[0]) + } + }) + return nil +} + func (w *gtkWindow) SetAlwaysOnTop(enabled bool) error { if w == nil || w.app == nil { return fmt.Errorf("linux: window is closed") diff --git a/internal/platform/windows/title_windows.go b/internal/platform/windows/title_windows.go new file mode 100644 index 000000000..e8959a93f --- /dev/null +++ b/internal/platform/windows/title_windows.go @@ -0,0 +1,54 @@ +package windows + +import ( + "fmt" + "sync" + "syscall" + "unsafe" +) + +// wmSetTitle asks the window thread to apply the title SetTitle stored. +// SetWindowTextW from another thread would send WM_SETTEXT and wait for the +// window thread, so the change is posted instead. +const wmSetTitle = 0x8052 + +var setWindowText = user.NewProc("SetWindowTextW") + +// titleRequest holds the latest title asked for until the window thread applies it. +type titleRequest struct { + mu sync.Mutex + title string + pending bool +} + +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + request := &window.state.pendingTitle + request.mu.Lock() + request.title, request.pending = title, true + request.mu.Unlock() + if ok, _, err := postMessage.Call(window.state.window, wmSetTitle, 0, 0); ok == 0 { + return fmt.Errorf("windows: request title: %w", err) + } + return nil +} + +// applyTitle sets the stored title on the window and in the accessibility tree. +func (state *windowState) applyTitle() { + request := &state.pendingTitle + request.mu.Lock() + title, pending := request.title, request.pending + request.pending = false + request.mu.Unlock() + if !pending || state.window == 0 { + return + } + value, err := syscall.UTF16PtrFromString(title) + if err != nil { + return + } + state.config.Title = title + setWindowText.Call(state.window, uintptr(unsafe.Pointer(value))) +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 967339d39..6905294bb 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -67,6 +67,8 @@ const ( ) type windowState struct { + // pendingTitle is the title SetTitle asked for, applied on the window thread. + pendingTitle titleRequest fullscreen atomic.Bool fullscreenChanging bool fullscreenStyle uint32 @@ -438,6 +440,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmSetTitle: + state.applyTitle() + return 0 case wmSysCommand: if state.fullscreen.Load() { switch first & 0xfff0 { diff --git a/markdown/inline.go b/markdown/inline.go index fa80c0d08..3da7a8fc0 100644 --- a/markdown/inline.go +++ b/markdown/inline.go @@ -63,6 +63,16 @@ func (d *Document) inline(s string, style Style, link string, depth int) { } i += n continue + case '!': + if i+1 < len(s) && s[i+1] == '[' { + if labelEnd, dest, end := d.findLink(s, i+1); end >= 0 { + d.emit(s[text:i], style, link) + d.spans = append(d.spans, Span{Text: s[i+2 : labelEnd], Style: style, Link: link, Image: dest}) + i = end + text = i + continue + } + } case '[': if link == "" && depth < maxNesting { if labelEnd, dest, end := d.findLink(s, i); end >= 0 { diff --git a/markdown/markdown.go b/markdown/markdown.go index b435d8d64..4412a0b64 100644 --- a/markdown/markdown.go +++ b/markdown/markdown.go @@ -14,7 +14,8 @@ // not closed (a "**" with no partner, a fence nobody ended yet) stays as typed, // so half a message that is still arriving reads sensibly. Links are kept only // when they point to http, https or mailto; any other destination is shown as -// plain text. HTML, images, footnotes and indented code are not interpreted. +// plain text. HTML, footnotes and indented code are not interpreted; an image is a +// Span whose Image is its destination. package markdown import "strings" @@ -55,6 +56,10 @@ type Span struct { // Link is the destination when the text is a link, and empty otherwise. // Only http, https and mailto destinations are ever set. Link string + // Image is the destination of an image (![alt](destination)) as written, + // whatever its scheme, and empty for text; Text is then the alt text. The + // package never reads it: a view asks the application for the bitmap. + Image string } // Newline is the Text of the Span that separates two lines of a block. diff --git a/markdown/markdown_test.go b/markdown/markdown_test.go index a6f599dce..554f2e58e 100644 --- a/markdown/markdown_test.go +++ b/markdown/markdown_test.go @@ -297,3 +297,23 @@ func TestBlockRangesNameTheLinesOfTheirBlocks(t *testing.T) { } } } + +func TestAnImageIsASpanWithItsDestination(t *testing.T) { + var d Document + d.Parse("see ![the diagram](docs/arch.png) and [![build](https://x/badge.svg)](https://x/ci)") + var images []Span + for _, span := range d.Spans(&d.Blocks[0]) { + if span.Image != "" { + images = append(images, span) + } + } + if len(images) != 2 { + t.Fatalf("images = %+v", images) + } + if images[0].Image != "docs/arch.png" || images[0].Text != "the diagram" || images[0].Link != "" { + t.Errorf("first image %+v", images[0]) + } + if images[1].Image != "https://x/badge.svg" || images[1].Link != "https://x/ci" { + t.Errorf("a linked badge %+v", images[1]) + } +} diff --git a/ui/list.go b/ui/list.go index e7901d5dc..79a556151 100644 --- a/ui/list.go +++ b/ui/list.go @@ -876,7 +876,8 @@ func (p *Page) listArea(c C, state *ListState, n int, horizontal bool, row func( scroll.Offset = max(state.top(n)-viewport, 0) } // The rows are placed and hit-tested on whole logical pixels, as the layout - // applies them, so a label's native texture survives a fractional scroll. + // applies them, so a label's native texture survives a fractional scroll. The node + // carries that offset, so the paint that adds the rows shows the requested end. offset := snapScroll(scroll.Offset) c.f.nodes[area.i].scroll = offset first := max(state.rowAt(offset)-listOverscan, 0) diff --git a/ui/menu.go b/ui/menu.go index 67ab6c115..2214894de 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -54,6 +54,29 @@ func Menu(c C, anchor Box, open *bool, body func(*MenuItems)) { p.declareMenu(c, menu, scope, open, anchor.i, body) } +// MenuAt shows the items body declares at the point x, y of the window while *open, +// as a ContextMenu looks and behaves: for a menu the application opens itself at a +// place no control stands for, such as a mark painted inside a custom-drawn view. +// Choosing an item, Escape or a press outside closes it. +// +// if pressed := m.markAt(event); pressed { +// m.lanes, m.lanesAt = true, ui.Rect{X: event.X, Y: event.Y} +// } +// ui.MenuAt(c, m.lanesAt.X, m.lanesAt.Y, &m.lanes, func(menu *ui.MenuItems) { ... }) +// +// Not inside a Memo. +func MenuAt(c C, x, y float32, open *bool, body func(*MenuItems)) { + p := c.page + p.forbidInMemo("MenuAt") + if !*open { + return + } + scope := p.boundScope(pkMenu, unsafe.Pointer(open)) + menu := stateIn[MenuItems](p, scope, "menu") + menu.context, menu.at = true, Rect{X: x, Y: y} + p.declareMenu(c, menu, scope, open, -1, body) +} + // ContextMenu shows the items body declares at the pointer when target is pressed // with the secondary button, or at the target when it has the focus and Shift+F10 // is pressed, as shadcn's ContextMenu. It behaves as a Menu then, but Tab does not diff --git a/ui/menu_test.go b/ui/menu_test.go index 85cc91bec..acec13c5c 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -508,3 +508,27 @@ func TestMenuAbove(t *testing.T) { t.Fatalf("the menu at %v is not over its anchor at %v", item, anchor) } } + +// MenuAt opens where the application says, closes when an item is chosen, and +// leaves *open false. +func TestMenuAtOpensAtThePointGiven(t *testing.T) { + open, chosen := true, 0 + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Button(c, "Below") + ui.MenuAt(c, 120, 90, &open, func(menu *ui.MenuItems) { + if menu.Item("Lane").Clicked() { + chosen++ + } + }) + }) + }) + lane := d.hit("Lane").Bounds + if !d.page.Overlay() || lane.X < 119 || lane.Y < 89 { + t.Fatalf("overlay %v, the menu at %v is not at (120, 90)", d.page.Overlay(), lane) + } + d.click("Lane") + if chosen != 1 || open || d.has("Lane") { + t.Fatalf("chosen %d, open %v, shown %v", chosen, open, d.has("Lane")) + } +}