diff --git a/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md b/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md index 672a1115f..6fd6cf41e 100644 --- a/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md +++ b/.agents/notes/implemented/architecture/2026-11-12-plugin-authored-settings-content.md @@ -41,14 +41,16 @@ ### 事件与答案 -- 宿主按契约发送 `open`、`close`、`click`、`change`、`select`、`activate`、`viewport`、`settings` 事件,每个事件调用一次视图函数,参数里带 `instance`、`surface`、`language` 和 `settings{effective, draft}`。 -- 每个视图同一时间只发一个调用,按顺序发送。`viewport` 和 `settings` 停止变化 400 ms 后才发,等待中的同类事件合并成最新一个。输入框只在回车、失焦或提交时发一次 `change`,不按键调用。 +- 宿主按契约发送 `open`、`close`、`click`、`change`、`select`、`activate`、`viewport`、`resize`、`settings` 事件,每个事件调用一次视图函数,参数里带 `instance`、`surface`、`language`、`width` 和 `settings{effective, draft}`。`width` 是视图节点排版用的宽度(整数点,也是顶层画布的宽度);工具窗口要减去视图四周各 10 点的内边距。宿主在绘制时量出宽度,量到之后才发 `open`。 +- 每个视图同一时间只发一个调用,按顺序发送。`viewport`、`resize` 和 `settings` 停止变化 400 ms 后才发,等待中的同类事件合并成最新一个;`resize` 只在画出来的视图里有画布在 `on` 写了它时发,发送时带当时的宽度。输入框只在回车、失焦或提交时发一次 `change`,不按键调用。 - 函数返回整棵视图 `{view}`、补丁 `{patches}`(`set`、`replace`、`remove`、`insert`,最多 512 个)或 `{}`。宿主把答案连同清单、位置和上一次画的视图交给 Core 的 `plugins.ui.applyResult`,Core 校验并应用补丁后返回完整的下一棵视图,宿主只画这棵。宿主不保留自己的校验器或补丁引擎。 - 本版没有插件主动推送:视图只在回答事件时变化。 ### 画布 -- 节点是 `rect`、`path`、`text`、`image`、`group`,按 `viewBox` 坐标缩放到视图宽度。 +- 节点是 `rect`、`path`、`text`、`image`、`group`,用 `viewBox` 坐标,画在和视图一样宽、`height` 点高的区域里。 +- 缩放为 1 时,不写 `pan` 的画布显示整个 `viewBox`:按视图宽度缩放,但不超过 `height`,从左上角开始;写了 `pan` 的画布按视图宽度缩放,缩小到比区域窄时水平居中。只按宽度缩放会在宽窗口里把场景放大、裁掉下半部分,0.8.7/0.8.8 的 Go Modules 预览就是这样。 +- 跟随窗口的场景:插件把 `viewBox` 宽度设成事件里的 `width`,按这个宽度排版,并在 `on` 里写 `resize`;窗口变化后宿主发 `resize`,插件按新宽度重新排版。新答复到达之前,宿主按上面的规则缩放已有场景。旧宿主不带 `width`,它的 Core 也拒绝写了 `resize` 的画布,所以插件只在收到 `width` 后才写 `resize`,否则按固定宽度排版(语言页约 610 点,构建系统页和编译器页的详情约 340 点)(Core [#109](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/109))。 - 颜色可以是固定值、主题令牌(`$accent`、`$text` 等)、深浅两套值,或线性渐变;令牌和深浅两套值跟随主题。宿主控件不接受颜色、字体、尺寸和坐标。 - 可点击的分组必须有 `id`、`w`、`h` 和 `label`。悬停、按下、选中的样式写在 `states`(`hover`、`pressed`、`selected`)里,由宿主本地切换。 - 普通滚轮滚动页面;⌘ 或 Ctrl 加滚轮缩放,拖动空白处平移,缩放按钮由宿主画。悬停提示停留 500 ms 后显示。 @@ -63,7 +65,7 @@ ### 生命周期 -视图显示时发 `open`,消失时发 `close`。关闭、停用、更新或卸载插件、关闭项目、切换界面语言时,宿主取消未完成的调用并丢弃晚到的答案;切换语言后用新的 `instance` 重新打开。视图状态只存在后端和宿主内存里,不写进插件包或应用包。 +视图显示后第一次绘制量到宽度时发 `open`,消失时发 `close`;还没画过就消失的视图两个都不发。关闭、停用、更新或卸载插件、关闭项目、切换界面语言时,宿主取消未完成的调用并丢弃晚到的答案;切换语言后用新的 `instance` 重新打开。视图状态只存在后端和宿主内存里,不写进插件包或应用包。 ### Viva 尚不支持的画布能力 @@ -96,6 +98,7 @@ - 2026-11-12:渲染归 API-13,读写设置归 API-19,插件文字本地化归 API-37,都是现有编号的扩展,不新增编号。契约在 v0 里直接删掉 `native-ui`,换成插件视图,不升版本号(版本已于 2026-11-11 全部归 0)。 - 2026-11-18:设置区域只用插件视图,需要自由绘制时用画布(保留场景),不嵌网页;网页只用于工具窗口,沿用[插件自带网页界面](2026-10-18-plugin-web-content-in-host-windows.md)。顺序是先合设计和原型,再做 Core 契约加 SDK,最后做桌面端 Viva 渲染。 +- 2026-11-19:画布要自动适应窗口:不放大、不裁剪,并按真实宽度重新排版。做法是事件带 `width`、画布可写 `resize`,属于 API-13 的补充,不升能力版本(Core #109 取代只改缩放规则的 #107)。 ## 考虑过的备选方案 @@ -136,7 +139,7 @@ ## 验证 -- `scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/settingswindow/ ./internal/core/ -count=1`:覆盖事件顺序与去抖、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度、视图事件参数(Core 契约 fixture)、区域绑定设置与搜索关键词。 +- `scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/settingswindow/ ./internal/core/ -count=1`:覆盖事件顺序与去抖、量到宽度后才发 `open`、每个事件带 `width`、`resize` 的去抖与合并(含无头窗口缩小后发送新宽度)、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度、视图事件参数(Core 契约 fixture)、区域绑定设置与搜索关键词。 - `scripts/desktop/desktop-go.sh test -count=1 -tags 'vivahead lithevisual' -run 'TestVisualPluginView' ./internal/pluginview/` 和 `scripts/desktop/desktop-go.sh test -count=1 -tags 'vivahead lithevisual' -run 'TestVisualPluginRegion' ./internal/settingswindow/`:设置 `LITHE_VISUAL_OUTPUT_DIR` 后输出工具窗口视图和设置区域的深浅主题截图。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认插件包和应用包在运行中不被写入。 - 原生整机验收:安装一个声明了视图工具窗口和设置区域的测试插件,检查点击、编辑、树选择与激活、画布平移缩放、绑定设置的应用与取消、后端报错后的重试、停用插件后视图关闭;macOS 上打开插件区域时不出现新的 `com.apple.WebKit` 进程。Windows 在虚拟机上重复。 diff --git a/desktop/internal/pluginview/canvas.go b/desktop/internal/pluginview/canvas.go index 816adaf4c..568519229 100644 --- a/desktop/internal/pluginview/canvas.go +++ b/desktop/internal/pluginview/canvas.go @@ -12,11 +12,14 @@ import ( "github.com/vivaui/viva/ui" ) -// A canvas draws its scene in view-box coordinates scaled to the width of the view: at zoom -// 1 the view box's width fills the canvas, and its top edge is at the canvas's top. The user -// drags the empty area to pan (pan) and zooms with ⌘ or Control and the wheel, about the -// pointer, or with the host's zoom buttons, about the middle (zoom). The plain wheel scrolls -// the page. A scene narrower than the canvas is centered; one shorter starts at the top. +// A canvas draws its scene in view-box coordinates. One without pan shows its whole view box +// at zoom 1: scaled to the width of the view, but never taller than the canvas, from the +// canvas's top-left corner, so a scene designed at the narrowest page keeps its size and +// stays whole as the window widens. One with pan is scaled to the width of the view: at +// zoom 1 the view box's width fills the canvas and its top edge is at the canvas's top; a +// scene narrower than the canvas is centered, one shorter starts at the top. The user drags +// the empty area to pan (pan) and zooms with ⌘ or Control and the wheel, about the pointer, +// or with the host's zoom buttons, about the middle (zoom). The plain wheel scrolls the page. // There is no pinch to zoom: Viva reports no trackpad magnify yet (#2182). const ( // canvasZoomStep is how far a zoom button zooms. @@ -34,8 +37,8 @@ const ( // drag under way, and the groups the pointer rests on. It lives in memory and ends with the // showing. type canvasState struct { - // zoom is the user's zoom, 1 at the view's width; x and y are the view-box point at the - // canvas's top-left corner. placed reports that x and y were set. + // zoom is the user's zoom, 1 at the canvas's fitted scale (scale); x and y are the + // view-box point at the canvas's top-left corner. placed reports that x and y were set. zoom, x, y float64 placed bool @@ -98,16 +101,22 @@ func zoomRange(n *Node) (low, high float64) { } // scale is how many pixels one view-box unit takes in rect at the state's zoom; 0 for a -// view box without area, which draws nothing. +// view box without area, which draws nothing. At zoom 1 the view box's width fills rect, +// and a canvas without pan also keeps the view box's height within rect's. func (s *canvasState) scale(rect gfx.Rect, n *Node) float64 { if n.ViewBox[2] <= 0 || n.ViewBox[3] <= 0 || rect.Width <= 0 { return 0 } - return float64(rect.Width) / n.ViewBox[2] * s.zoom + k := float64(rect.Width) / n.ViewBox[2] + if !n.Pan && rect.Height > 0 { + k = math.Min(k, float64(rect.Height)/n.ViewBox[3]) + } + return k * s.zoom } // clamp keeps the visible part inside the view box: a view box narrower than the canvas -// is centered across it, one shorter than the canvas starts at its top. +// is centered across it when the canvas pans and starts at its leading edge when it does +// not; one shorter than the canvas starts at its top. func (s *canvasState) clamp(rect gfx.Rect, n *Node) { k := s.scale(rect, n) if k <= 0 { @@ -119,7 +128,10 @@ func (s *canvasState) clamp(rect gfx.Rect, n *Node) { } width, height := float64(rect.Width)/k, float64(rect.Height)/k if width >= box[2] { - s.x = box[0] - (width-box[2])/2 + s.x = box[0] + if n.Pan { + s.x -= (width - box[2]) / 2 + } } else { s.x = math.Min(math.Max(s.x, box[0]), box[0]+box[2]-width) } diff --git a/desktop/internal/pluginview/canvas_test.go b/desktop/internal/pluginview/canvas_test.go index 9e84ca0ba..3a3693ef7 100644 --- a/desktop/internal/pluginview/canvas_test.go +++ b/desktop/internal/pluginview/canvas_test.go @@ -36,6 +36,40 @@ func TestCanvasScaleFollowsTheWidthAndTheZoom(t *testing.T) { } } +func TestCanvasWithoutPanShowsItsWholeViewBoxFromTheTopLeft(t *testing.T) { + // A scene designed 600 × 300 in a canvas 300 points tall. + n := &Node{Type: "canvas", ID: "preview", ViewBox: [4]float64{10, 20, 600, 300}} + state := &canvasState{zoom: 1} + + // As wide as designed it takes one pixel a unit. + if got := state.scale(gfx.Rect{Width: 600, Height: 300}, n); got != 1 { + t.Fatalf("scale at the designed width = %v, want 1", got) + } + // Narrower, it shrinks to the width. + if got := state.scale(gfx.Rect{Width: 300, Height: 300}, n); got != 0.5 { + t.Fatalf("scale at half the width = %v, want 0.5", got) + } + // Wider, it keeps its size, whole, from the leading edge. + wide := gfx.Rect{Width: 1000, Height: 300} + if got := state.scale(wide, n); got != 1 { + t.Fatalf("scale wider than designed = %v, want the height kept", got) + } + state.clamp(wide, n) + if state.x != 10 || state.y != 20 { + t.Fatalf("wider than designed at (%v, %v), want the view box's top-left corner", state.x, state.y) + } + if got := state.viewport(wide, n); got != (Viewport{X: 10, Y: 20, Width: 1000, Height: 300}) { + t.Fatalf("viewport = %+v", got) + } + + // Its zoom scales the fitted scene. + n.Zoom = &[2]float64{1, 2} + state = &canvasState{zoom: 2} + if got := state.scale(wide, n); got != 2 { + t.Fatalf("scale at zoom 2 = %v, want twice the fitted scale", got) + } +} + func TestCanvasClampKeepsTheViewInsideTheViewBox(t *testing.T) { n := testCanvas() n.ViewBox = [4]float64{100, 50, 400, 200} @@ -99,7 +133,7 @@ func TestCanvasZoomAtKeepsThePointUnderThePointer(t *testing.T) { func openCanvas(t *testing.T) (*backend, *Session, *canvasState) { b := newBackend(t) s := b.session() - s.Open() + show(s) b.answered(s) state := &canvasState{zoom: 2} state.make() diff --git a/desktop/internal/pluginview/render.go b/desktop/internal/pluginview/render.go index 71390a1c9..186e5ecd7 100644 --- a/desktop/internal/pluginview/render.go +++ b/desktop/internal/pluginview/render.go @@ -79,7 +79,17 @@ func Draw(c ui.C, s *Session, host *Host, fill bool) { } } r := &renderer{c: c, s: s, host: host} - root := ui.Column(c).FillWidth().Gap(10) + // The paint measures the width the nodes are laid out in: the view's, less the body's + // padding in a tool window. It sends open, and later resize; the scroll bars of the + // body float over it, so they take none of the width. + if s.measure == nil { + s.measure = s.measured + } + s.inset = 0 + if fill { + s.inset = 2 * bodyPadding + } + root := ui.Column(c).FillWidth().Gap(10).Draw(s.measure) if fill { root = root.Fill() } @@ -91,19 +101,30 @@ func Draw(c ui.C, s *Session, host *Host, fill bool) { nodes := s.View() if fill && !hasTree(nodes) { ui.Scroll(c).FillWidth().Grow(1).Children(func() { - ui.Column(c).FillWidth().Gap(10).PadX(10).PadY(10).Children(func() { r.nodes(c, nodes) }) + ui.Column(c).FillWidth().Gap(10).PadX(bodyPadding).PadY(bodyPadding).Children(func() { r.nodes(c, nodes) }) }) return } body := ui.Column(c).FillWidth().Gap(10) if fill { - body = body.Grow(1).PadX(10).PadY(10) + body = body.Grow(1).PadX(bodyPadding).PadY(bodyPadding) } r.fillTree = fill body.Children(func() { r.nodes(c, nodes) }) }) } +// bodyPadding is the space around the nodes of a view that fills a tool window. +const bodyPadding = 10 + +// measured is the paint callback that gives the session the width its nodes are laid +// out in, and asks for the frame that sends a resize once it is due. +func (s *Session) measured(d *ui.DrawContext) { + if wait := s.Measured(d.Rect.Width - s.inset); wait > 0 && d.Canvas != nil { + d.Canvas.RequestFrameIn(wait) + } +} + // hasTree reports a tree among the top-level nodes: it scrolls by itself, so the body does not. func hasTree(nodes []Node) bool { for i := range nodes { diff --git a/desktop/internal/pluginview/render_test.go b/desktop/internal/pluginview/render_test.go index f56b8105c..1316ec952 100644 --- a/desktop/internal/pluginview/render_test.go +++ b/desktop/internal/pluginview/render_test.go @@ -29,11 +29,17 @@ func drawView(t *testing.T, view string) *viewDriver { b := newBackend(t) b.answer = func(map[string]any) (json.RawMessage, bool, error) { return json.RawMessage(view), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) if !s.Drawn() { t.Fatalf("the open answer was not drawn: %v", s.Err()) } + return paintView(t, b, s) +} + +// paintView draws the session as a tool window body in a headless window 480 points wide. +func paintView(t *testing.T, b *backend, s *Session) *viewDriver { + t.Helper() theme := ui.LightTheme() background := theme.Background invalidator := &app.Invalidator{} @@ -240,3 +246,27 @@ func TestDrawShowsTheFailureWithRetry(t *testing.T) { // errPluginFailed is a backend's own failure, shown untranslated under the host's words. var errPluginFailed = errors.New("the index is locked") + +func TestDrawSendsOpenAndResizeWithTheWidthItsNodesAreLaidOutIn(t *testing.T) { + b := newBackend(t) + b.answer = func(map[string]any) (json.RawMessage, bool, error) { return resizeView(), true, nil } + s := b.session() + s.Open() + d := paintView(t, b, s) + // The window is 480 points wide, and the body pads the nodes by 10 on each side. + if open := d.sent(); open["event"] != "open" || open["width"] != 460.0 { + t.Fatalf("event = %v, want open at the width the first paint measured", open) + } + d.repaint() + if err := d.driver.Resize(400, 400); err != nil { + t.Fatal(err) + } + if len(b.pending) != 0 { + t.Fatal("resize went out before the width settled") + } + b.now = b.now.Add(settleDelay) + d.repaint() + if resize := d.sent(); resize["event"] != "resize" || resize["width"] != 380.0 { + t.Fatalf("event = %v, want resize at the new width", resize) + } +} diff --git a/desktop/internal/pluginview/session.go b/desktop/internal/pluginview/session.go index 4730890ef..276705c2f 100644 --- a/desktop/internal/pluginview/session.go +++ b/desktop/internal/pluginview/session.go @@ -4,6 +4,8 @@ import ( "context" "encoding/json" "errors" + "math" + "slices" "strconv" "sync" "sync/atomic" @@ -12,9 +14,10 @@ import ( "github.com/vivaui/viva/ui" ) -// settleDelay is how long a canvas stays still, or the settings stay unchanged, before -// the host sends the viewport or settings event: the contract's 400 ms for viewport, -// which settings follow so typing in a declared row does not call the backend per key. +// settleDelay is how long a canvas stays still, the view's width stays the same, or the +// settings stay unchanged, before the host sends the viewport, resize or settings event: +// the contract's 400 ms for viewport and resize, which settings follow so typing in a +// declared row does not call the backend per key. const settleDelay = 400 * time.Millisecond // Call sends one view event to the plugin's backend and has Core check the answer. It @@ -112,6 +115,18 @@ type Session struct { settings *settling viewports map[string]*settling + // width is the width the view's nodes are laid out in, in whole points, as the last + // paint measured it: 0 until the first paint, and open waits for it. heard is the + // width the last open or resize event carried, and changed is when width last + // changed, so resize goes out once the width stays the same for settleDelay. + width int + heard int + changed time.Time + // inset is how much narrower than the view the nodes are laid out, and measure the + // paint callback that measures the width, made once so a paint does not allocate it. + inset float32 + measure func(*ui.DrawContext) + // fields, selects, toggles, trees and canvases are the host's own state of the // drawn nodes, by node ID. They live in memory and end with the showing. fields map[string]*fieldState @@ -135,8 +150,9 @@ func NewSession(options Options) *Session { return &Session{options: options} } -// Open shows the view: it sends open with a new instance. A session already open is -// left as it is. +// Open shows the view: it sends open with a new instance once Measured gives the +// view's width, so the plugin lays out its first view in the space it has. A session +// already open is left as it is. func (s *Session) Open() { if s == nil || s.open { return @@ -148,7 +164,8 @@ func (s *Session) Open() { } // Close hides the view: it cancels the pending call, drops its late answer and every -// waiting event, sends close, and forgets the view and the host's state of it. +// waiting event, sends close when open went out, and forgets the view and the host's +// state of it. func (s *Session) Close() { if s == nil || !s.open { return @@ -156,7 +173,9 @@ func (s *Session) Close() { if s.cancel != nil { s.cancel() } - if s.options.Call != nil { + // heard is set when open goes out, so a view closed before its first paint sends + // neither open nor close. + if s.options.Call != nil && s.heard > 0 { event := s.encode(Event{Name: "close"}) view, call := s.raw, s.options.Call // The close event outlives the showing, so it is not cancelled with it. @@ -168,9 +187,42 @@ func (s *Session) Close() { s.generation++ s.open, s.instance, s.raw, s.nodes, s.err, s.failed = false, "", nil, nil, nil, nil s.busy, s.cancel, s.queue, s.settings, s.viewports = false, nil, nil, nil, nil + s.width, s.heard = 0, 0 s.fields, s.selects, s.toggles, s.trees, s.canvases = nil, nil, nil, nil, nil } +// Measured takes the width the view's nodes are laid out in, which the paint measures. +// The first width sends the open that waits for it. A later change sends resize once +// the width stays the same for settleDelay, while the drawn view has a canvas that +// listens for it; wait is then how long until it is due, so the host asks for a frame. +func (s *Session) Measured(width float32) (wait time.Duration) { + if s == nil || !s.open { + return 0 + } + w := int(math.Floor(float64(width))) + if w < 1 || w == s.width { + return 0 + } + first := s.width == 0 + s.width, s.changed = w, s.options.Now() + if first { + s.pump() + return 0 + } + if !listsResize(s.nodes) { + return 0 + } + return settleDelay +} + +// Width is the width the view's nodes are laid out in, 0 before the first paint. +func (s *Session) Width() int { + if s == nil { + return 0 + } + return s.width +} + // Opened reports whether the view is showing. func (s *Session) Opened() bool { return s != nil && s.open } @@ -248,10 +300,39 @@ func (s *Session) Take() (wait time.Duration) { wait = left } } + // A width the plugin has not laid out at goes out as resize once it settles. A view + // that starts listening later hears the width that changed before it at once. + if s.heard > 0 && s.width != s.heard && !s.queued("resize") && listsResize(s.nodes) { + due := s.changed.Add(settleDelay) + if !now.Before(due) { + s.enqueue(Event{Name: "resize"}) + } else if left := due.Sub(now); wait == 0 || left < wait { + wait = left + } + } s.pump() return wait } +// queued reports an event of the name waiting to be sent. +func (s *Session) queued(name string) bool { + return slices.ContainsFunc(s.queue, func(event Event) bool { return event.Name == name }) +} + +// listsResize reports a canvas among nodes, at any depth, that lists resize in its on. +func listsResize(nodes []Node) bool { + for i := range nodes { + n := &nodes[i] + if n.Type == "canvas" && slices.Contains(n.On, "resize") { + return true + } + if listsResize(n.Children) { + return true + } + } + return false +} + // apply takes in the answer of the call that just finished. func (s *Session) apply(done *outcome) { if done.err != nil { @@ -283,10 +364,11 @@ func (s *Session) apply(done *outcome) { } // enqueue queues a settled event, merging it into a waiting one of the same kind: the -// latest settings, or the latest viewport of the same canvas, is all the plugin needs. +// latest settings, the latest viewport of the same canvas, or one resize, which carries +// the width at sending, is all the plugin needs. func (s *Session) enqueue(event Event) { for i, waiting := range s.queue { - if waiting.Name == event.Name && (event.Name == "settings" || waiting.Canvas == event.Canvas) { + if waiting.Name == event.Name && (event.Name != "viewport" || waiting.Canvas == event.Canvas) { s.queue = append(s.queue[:i], s.queue[i+1:]...) break } @@ -294,13 +376,17 @@ func (s *Session) enqueue(event Event) { s.queue = append(s.queue, event) } -// pump starts the next waiting event when no call is pending. +// pump starts the next waiting event when no call is pending and the width is known. func (s *Session) pump() { - if s.busy || len(s.queue) == 0 || s.options.Call == nil { + if s.busy || len(s.queue) == 0 || s.options.Call == nil || s.width == 0 { return } event := s.queue[0] s.queue = s.queue[1:] + if event.Name == "open" || event.Name == "resize" { + // The plugin lays out its whole view at the width these carry. + s.heard = s.width + } encoded := s.encode(event) s.busy = true s.generation++ @@ -332,6 +418,9 @@ func (s *Session) encode(event Event) json.RawMessage { } } params["event"], params["instance"] = event.Name, s.instance + if s.width > 0 { + params["width"] = s.width + } if event.Node != "" { params["node"] = event.Node } diff --git a/desktop/internal/pluginview/session_test.go b/desktop/internal/pluginview/session_test.go index 36e76870e..4c2fb42c8 100644 --- a/desktop/internal/pluginview/session_test.go +++ b/desktop/internal/pluginview/session_test.go @@ -124,6 +124,20 @@ func (b *backend) last() map[string]any { return b.calls[len(b.calls)-1].params } +// testWidth is the width the tests' first paint measures. +const testWidth = 600 + +// show opens the session and measures its width, as the first paint of the view does. +func show(s *Session) { + s.Open() + s.Measured(testWidth) +} + +// resizeView is a view whose canvas lays itself out at the width and listens for resize. +func resizeView() json.RawMessage { + return json.RawMessage(`[{"type":"canvas","id":"fit","label":"Fit","height":120,"viewBox":[0,0,600,120],"on":["resize"],"nodes":[]}]`) +} + // shown is the text of the session's label, which names the event that drew it. func shown(t *testing.T, s *Session) string { t.Helper() @@ -138,8 +152,15 @@ func TestSessionOpenSendsOpenAndDrawsTheAnswer(t *testing.T) { b := newBackend(t) s := b.session() s.Open() - if !s.Opened() || !s.Busy() || len(b.pending) != 1 { - t.Fatalf("after Open: opened %v, busy %v, %d calls queued", s.Opened(), s.Busy(), len(b.pending)) + if !s.Opened() || s.Busy() || len(b.pending) != 0 { + t.Fatalf("before the first paint: opened %v, busy %v, %d calls queued", s.Opened(), s.Busy(), len(b.pending)) + } + if s.Measured(0.5) != 0 || len(b.pending) != 0 { + t.Fatal("a width under one point sent open") + } + s.Measured(612.7) + if !s.Busy() || len(b.pending) != 1 || s.Width() != 612 { + t.Fatalf("after the first paint: busy %v, %d calls queued, width %d", s.Busy(), len(b.pending), s.Width()) } if s.Drawn() { t.Fatal("a view is drawn before the backend answered") @@ -158,6 +179,9 @@ func TestSessionOpenSendsOpenAndDrawsTheAnswer(t *testing.T) { if call.params["event"] != "open" || call.view != nil || call.closing { t.Fatalf("open call = %+v, want open with no drawn view", call) } + if call.params["width"] != 612.0 { + t.Fatalf("open width = %v, want the measured width in whole points", call.params["width"]) + } if instance := s.Instance(); !strings.HasPrefix(instance, "view-") || call.params["instance"] != instance { t.Fatalf("instance = %q, sent %v", instance, call.params["instance"]) } @@ -173,7 +197,7 @@ func TestSessionOpenSendsOpenAndDrawsTheAnswer(t *testing.T) { func TestSessionSendsOneEventAtATimeWithTheDrawnView(t *testing.T) { b := newBackend(t) s := b.session() - s.Open() + show(s) b.answered(s) s.Send(Event{Name: "click", Node: "refresh"}) s.Send(Event{Name: "change", Node: "filter", Value: "core"}) @@ -202,7 +226,7 @@ func TestSessionSendsOneEventAtATimeWithTheDrawnView(t *testing.T) { func TestSessionSettlesSettingsAndSendsTheValuesAtSending(t *testing.T) { b := newBackend(t) s := b.session() - s.Open() + show(s) b.answered(s) s.SettingsChanged() b.now = b.now.Add(100 * time.Millisecond) @@ -233,7 +257,7 @@ func TestSessionSettlesSettingsAndSendsTheValuesAtSending(t *testing.T) { func TestSessionMergesWaitingViewportsPerCanvas(t *testing.T) { b := newBackend(t) s := b.session() - s.Open() + show(s) s.ViewportMoved("graph", Viewport{X: 1, Width: 10, Height: 10}) s.ViewportMoved("minimap", Viewport{X: 2, Width: 5, Height: 5}) b.now = b.now.Add(settleDelay) @@ -259,7 +283,7 @@ func TestSessionMergesWaitingViewportsPerCanvas(t *testing.T) { func TestSessionCloseDropsTheLateAnswerAndSendsClose(t *testing.T) { b := newBackend(t) s := b.session() - s.Open() + show(s) first := s.Instance() s.Close() if s.Opened() || s.Instance() != "" || len(b.pending) != 2 { @@ -274,13 +298,16 @@ func TestSessionCloseDropsTheLateAnswerAndSendsClose(t *testing.T) { if !closing.closing || closing.params["event"] != "close" || closing.params["instance"] != first { t.Fatalf("close call = %+v", closing) } + if closing.params["width"] != float64(testWidth) { + t.Fatalf("close width = %v", closing.params["width"]) + } if err := closing.ctx.Err(); err != nil { t.Fatalf("the close call's context = %v, want it to outlive the showing", err) } if s.Take() != 0 || s.Drawn() { t.Fatal("a closed session took the late answer") } - s.Open() + show(s) if s.Instance() == first || s.Instance() == "" { t.Fatalf("reopening kept instance %q", s.Instance()) } @@ -297,9 +324,9 @@ func TestSessionKeepsTheNewerAnswerWhenAClosedShowingAnswersLate(t *testing.T) { return labelView(instance), true, nil } s := b.session() - s.Open() + show(s) s.Close() - s.Open() + show(s) if len(b.pending) != 3 { t.Fatalf("%d calls queued, want the first open, close and the second open", len(b.pending)) } @@ -326,7 +353,7 @@ func TestSessionRetrySendsTheFailedEventAgain(t *testing.T) { return labelView(name), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) s.Send(Event{Name: "click", Node: "refresh"}) b.answered(s) @@ -358,7 +385,7 @@ func TestSessionLogsAViewItCannotRead(t *testing.T) { return labelView("open"), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) s.Send(Event{Name: "click", Node: "refresh"}) b.answered(s) @@ -383,7 +410,7 @@ func TestSessionIgnoresACancelledCall(t *testing.T) { return labelView("open"), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) s.Send(Event{Name: "click"}) b.answered(s) @@ -409,7 +436,7 @@ func TestSessionKeepsTheViewForAnEmptyOrUnchangedAnswer(t *testing.T) { return labelView("open"), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) s.Send(Event{Name: "click"}) b.answered(s) @@ -424,7 +451,7 @@ func TestSessionEncodesTheEventOverTheSurfaceParams(t *testing.T) { b := newBackend(t) b.params["event"], b.params["instance"] = "spoofed", "spoofed" s := b.session() - s.Open() + show(s) b.answered(s) if _, ok := b.calls[0].params["node"]; ok { t.Fatalf("open params %v carry a node", b.calls[0].params) @@ -437,7 +464,7 @@ func TestSessionEncodesTheEventOverTheSurfaceParams(t *testing.T) { params := b.last() want := map[string]any{ "event": "activate", "instance": s.Instance(), "node": "modules", "item": "core", - "setting": "jdk", "value": 3.0, "canvas": "graph", + "setting": "jdk", "value": 3.0, "canvas": "graph", "width": float64(testWidth), } for key, value := range want { if params[key] != value { @@ -458,7 +485,7 @@ func TestSessionCallsEndWithTheHostContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() s := b.session(func(options *Options) { options.Context = ctx }) - s.Open() + show(s) cancel() b.run() if err := b.calls[0].ctx.Err(); !errors.Is(err, context.Canceled) { @@ -473,6 +500,9 @@ func TestSessionTakesNoInputWhileClosed(t *testing.T) { s.SettingsChanged() s.ViewportMoved("graph", Viewport{Width: 1, Height: 1}) s.Retry() + if s.Measured(500) != 0 || s.Width() != 0 { + t.Fatal("a closed session took a width") + } b.now = b.now.Add(settleDelay) if s.Take() != 0 || len(b.pending) != 0 || len(b.calls) != 0 { t.Fatalf("a closed session sent %d events", len(b.pending)+len(b.calls)) @@ -480,8 +510,116 @@ func TestSessionTakesNoInputWhileClosed(t *testing.T) { var none *Session none.Open() none.Send(Event{Name: "click"}) + none.Measured(500) none.Close() if none.Opened() || none.Drawn() || none.Busy() || none.Err() != nil || none.View() != nil || none.Instance() != "" { t.Fatal("a nil session reports a view") } } + +func TestSessionSendsResizeOnceTheWidthSettles(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { return resizeView(), true, nil } + s := b.session() + show(s) + b.answered(s) + if wait := s.Measured(500); wait != settleDelay { + t.Fatalf("a new width waits %v, want %v", wait, settleDelay) + } + b.now = b.now.Add(100 * time.Millisecond) + if wait := s.Take(); wait != 300*time.Millisecond || len(b.pending) != 0 { + t.Fatalf("100 ms after the width changed: wait %v, %d calls", wait, len(b.pending)) + } + b.now = b.now.Add(100 * time.Millisecond) + s.Measured(450) + b.now = b.now.Add(300 * time.Millisecond) + if wait := s.Take(); wait != 100*time.Millisecond || len(b.pending) != 0 { + t.Fatalf("a second change did not restart the wait: wait %v, %d calls", wait, len(b.pending)) + } + // An event in between carries the width, but the plugin lays out again only on resize. + s.Send(Event{Name: "click", Node: "refresh"}) + b.answered(s) + if b.last()["width"] != 450.0 { + t.Fatalf("click width = %v", b.last()["width"]) + } + b.now = b.now.Add(100 * time.Millisecond) + if wait := s.Take(); wait != 0 || len(b.pending) != 1 { + t.Fatalf("once settled: wait %v, %d calls", wait, len(b.pending)) + } + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "click", "resize"}) || b.last()["width"] != 450.0 { + t.Fatalf("events = %v, last %v", got, b.last()) + } + b.now = b.now.Add(time.Second) + if wait := s.Take(); wait != 0 || len(b.pending) != 0 { + t.Fatalf("a width the plugin laid out at sent resize again: wait %v, %d calls", wait, len(b.pending)) + } +} + +func TestSessionMergesAWaitingResizeAndSendsTheWidthAtSending(t *testing.T) { + b := newBackend(t) + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { return resizeView(), true, nil } + s := b.session() + show(s) + b.answered(s) + s.Send(Event{Name: "click", Node: "refresh"}) + s.Measured(500) + b.now = b.now.Add(settleDelay) + s.Take() + s.Measured(450) + b.now = b.now.Add(settleDelay) + s.Take() + for len(b.pending) > 0 { + b.answered(s) + } + if got := b.events(); !slices.Equal(got, []string{"open", "click", "resize"}) || b.last()["width"] != 450.0 { + t.Fatalf("events = %v, last %v, want one resize with the latest width", got, b.last()) + } +} + +func TestSessionSendsNoResizeWithoutACanvasThatListens(t *testing.T) { + b := newBackend(t) + listens := false + b.answer = func(params map[string]any) (json.RawMessage, bool, error) { + if listens { + return resizeView(), true, nil + } + return labelView("open"), true, nil + } + s := b.session() + show(s) + b.answered(s) + if wait := s.Measured(500); wait != 0 { + t.Fatalf("a view without a resize canvas waits %v", wait) + } + b.now = b.now.Add(time.Second) + if wait := s.Take(); wait != 0 || len(b.pending) != 0 { + t.Fatalf("a view without a resize canvas: wait %v, %d calls", wait, len(b.pending)) + } + // A view that starts listening hears the width that changed before it at once. + listens = true + s.Send(Event{Name: "click", Node: "refresh"}) + b.answered(s) + if len(b.pending) != 1 { + t.Fatalf("%d calls queued, want the resize the new canvas listens for", len(b.pending)) + } + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open", "click", "resize"}) || b.last()["width"] != 500.0 { + t.Fatalf("events = %v, last %v", got, b.last()) + } +} + +func TestSessionClosedBeforeItsFirstPaintSendsNothing(t *testing.T) { + b := newBackend(t) + s := b.session() + s.Open() + s.Close() + if len(b.pending) != 0 || len(b.calls) != 0 { + t.Fatalf("a view closed before its first paint sent %d events", len(b.pending)+len(b.calls)) + } + show(s) + b.answered(s) + if got := b.events(); !slices.Equal(got, []string{"open"}) || shown(t, s) != "open" { + t.Fatalf("events = %v after reopening", got) + } +} diff --git a/desktop/internal/pluginview/view_visual_test.go b/desktop/internal/pluginview/view_visual_test.go index ebd81f1ab..42bec67d1 100644 --- a/desktop/internal/pluginview/view_visual_test.go +++ b/desktop/internal/pluginview/view_visual_test.go @@ -92,7 +92,7 @@ func TestVisualPluginView(t *testing.T) { b := newBackend(t) b.answer = func(map[string]any) (json.RawMessage, bool, error) { return json.RawMessage(visualView), true, nil } s := b.session() - s.Open() + show(s) b.answered(s) if !s.Drawn() { t.Fatalf("the view was not drawn: %v", s.Err()) diff --git a/desktop/internal/settingswindow/plugin_region_view_test.go b/desktop/internal/settingswindow/plugin_region_view_test.go index ed2745de3..bb3aa4104 100644 --- a/desktop/internal/settingswindow/plugin_region_view_test.go +++ b/desktop/internal/settingswindow/plugin_region_view_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "math" "os" "reflect" "slices" @@ -310,6 +311,10 @@ func TestRegionViewOpensWithThePageAndClosesWhenThePageChanges(t *testing.T) { if opened.params["event"] != "open" || opened.region != "overview" || opened.function != "settingsView" || opened.closing { t.Fatalf("the first call = %+v, want open of the overview region", opened) } + // The region lays out at the width of the page's content, which the paint measures. + if width, _ := opened.params["width"].(float64); width < 100 || width != math.Floor(width) { + t.Fatalf("the view opened at width %v, want the region's width in whole points", opened.params["width"]) + } if opened.params["language"] != i18n.English.Code() { t.Fatalf("the view opened in %v", opened.params["language"]) } diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index c7cae60ba..7683c8d38 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -27,7 +27,12 @@ native_path() { fi } -# Lithe-core-rust main at 545ca11: #104, squash-merged into main: plugin views replace the native +# Lithe-core-rust main at 0b6da27: #109, squash-merged into main: a canvas's on may list resize +# beside viewport, which the desktop sends with the new width 400 ms after the width stops +# changing; every view event carries width, the width the view's nodes are laid out in. It is on +# top of #108 (9dea6aa), squash-merged into main: managedRuntimes 1 lists mirror URLs for runtime +# artifacts, and #105 (555eb95), which only changed the plugin documentation. +# Below them, Lithe-core-rust main at 545ca11: #104, squash-merged into main: plugin views replace the native # UI document. A tool window's view.function and a manifest's settingRegions[].view name a backend # view function the host calls once per event, and plugins.ui.applyResult checks each result (a # whole view, patches or nothing) against the manifest, the surface and the view drawn last and @@ -266,7 +271,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="9dea6aa6eaaf830c3568b647aa7daae5018b9727" +PINNED_CORE_REVISION="0b6da2725ded74de7c3b62b49d12c1947dc0a38a" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json index ba805abad..ea03ac390 100644 --- a/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json +++ b/shared/platform-feature-matrix/features/declarative-native-plugin-ui.json @@ -2,7 +2,7 @@ "id": "declarative-native-plugin-ui", "area": "插件", "group": "插件界面", - "capability": "插件视图(ui 0 的 view 工具窗口):插件后端的视图函数返回节点树(JSON 场景),宿主用自己的 Viva 控件原生绘制,后端不接触界面库;节点包括 row/section 布局、label、textField、select/segmented、toggle、button、keyValue、table、banner、可折叠树(选择、双击激活、超过 12 行自身滚动)和画布(rect/path/text/image/group,主题色令牌 $accent 等、viewBox 缩放、平移缩放视口);宿主按契约发送 open/close/click/change/select/activate/viewport/settings 事件,同一时间只发一个调用、viewport 与 settings 事件 400 ms 去抖合并,答案由 Core 校验后才绘制;失败显示宿主文案加插件原文并可重试,关闭、停用或替换时取消并丢弃晚到答案;工具窗口标题栏图标与停靠位置沿用已有工具窗口;设置区域(settingRegions)复用同一渲染器,见 plugin-registered-settings-pages", + "capability": "插件视图(ui 0 的 view 工具窗口):插件后端的视图函数返回节点树(JSON 场景),宿主用自己的 Viva 控件原生绘制,后端不接触界面库;节点包括 row/section 布局、label、textField、select/segmented、toggle、button、keyValue、table、banner、可折叠树(选择、双击激活、超过 12 行自身滚动)和画布(rect/path/text/image/group,主题色令牌 $accent 等、viewBox 缩放:不写 pan 时完整显示、写了 pan 时宽度占满,平移缩放视口);宿主在绘制时量出视图宽度,量到后才发 open,每个事件带 width;按契约发送 open/close/click/change/select/activate/viewport/resize/settings 事件,同一时间只发一个调用、viewport、resize 与 settings 事件 400 ms 去抖合并,画布在 on 写了 resize 时窗口宽度变化后发 resize,让插件按新宽度重新排版;答案由 Core 校验后才绘制;失败显示宿主文案加插件原文并可重试,关闭、停用或替换时取消并丢弃晚到答案;工具窗口标题栏图标与停靠位置沿用已有工具窗口;设置区域(settingRegions)复用同一渲染器,见 plugin-registered-settings-pages", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -50,7 +50,7 @@ ] }, "owner": "Plugin Platform", - "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/core/,覆盖事件顺序与去抖、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度,宿主视图事件参数(Core 契约 fixture settings.plugin.json)和工作台视图调用失败的日志;无头截图:LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginView ./internal/pluginview/,检查深浅主题。原生整机验收 pending:安装一个声明 view 工具窗口的测试插件,打开、点击、编辑、选择树项、双击激活、拖动与缩放画布,确认事件到达后端并重绘;停用插件、关闭项目时视图关闭且无晚到重绘;后端报错时显示失败与重试。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复上述原生验收。", + "verification": "自动化:scripts/desktop/desktop-go.sh test ./internal/pluginview/ ./internal/pluginservice/ ./internal/workbench/ ./internal/core/,覆盖事件顺序与去抖、量到宽度后才发 open、每个事件带 width、resize 去抖与合并(含无头窗口缩小后发送新宽度)、画布缩放规则、晚到答案丢弃、失败重试、节点解析、画布路径与颜色、图片限制、嵌套树高度,宿主视图事件参数(Core 契约 fixture settings.plugin.json)和工作台视图调用失败的日志;无头截图:LITHE_VISUAL_OUTPUT_DIR=<目录> scripts/desktop/desktop-go.sh test -tags 'vivahead lithevisual' -run TestVisualPluginView ./internal/pluginview/,检查深浅主题。原生整机验收 pending:安装一个声明 view 工具窗口的测试插件,打开、点击、编辑、选择树项、双击激活、拖动与缩放画布,拖动窗口改变宽度后画布按新宽度重新排版、不放大也不裁剪,确认事件到达后端并重绘;停用插件、关闭项目时视图关闭且无晚到重绘;后端报错时显示失败与重试。Windows 使用同一 Go Viva 桌面端,需在 Windows 虚拟机上重复上述原生验收。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {