You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2026/09/03 10:44:31 UTC
(plc4x-extras) 04/05: fix: Make the browser's help true, its columns fit, and its results usable
This is an automated email from the ASF dual-hosted git repository.
sruehl pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x-extras.git
commit 4242fc0a47a8f2a8393ae59a7a8fcb1fa74d2289
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Thu Sep 3 12:00:18 2026 +0200
fix: Make the browser's help true, its columns fit, and its results usable
Seven improvements to the browser, two of which were defects.
The help advertised seven keys that did nothing. g/G, the page keys, /, y,
f, e and L were all in the footer and none of them was handled: I had wired
only part of the shared keymap, which is the same dead-affordance defect the
port existed to remove -- the old UI's TODO selection handlers -- reappearing
in the help text. All seven now work: first/last, page scrolling, a filter
applied as it is typed, yank to the clipboard through OSC52 so it works over
ssh, a follow toggle that keeps the newest message selected, an expandable
error, and a log level that cycles. A generic test walks the bindings the
footer actually shows and fails on any that changes nothing.
The message table claimed 48 cells in the 40-cell pane the reference layout
gives, so it truncated -- and what it truncated was the tag, the one field a
row exists to show, clipped to two characters while the connection column
repeated the same string on every line. Columns are now budgeted in priority
order and dropped rather than squeezed: the connection goes first, since with
one connection open it distinguishes nothing, then the row number, then the
code narrows, then the operation. The tag keeps a floor of eight cells at
every width from 24 to 140, and the columns sum to exactly the pane.
Browsing flooded the message list. It emitted one message per tag, so
browsing the demo device pushed in eight rows with the same timestamp and
shoved the events being watched off the screen. A browse is now one message
carrying every tag, listed in the detail pane where a tag list belongs.
Nothing could be done with a tag once it was found. Browse showed temp/1 and
the only way to read it was to retype the address the pane was already
showing. r, w and s over a message now compose that request from its tags,
which for a browse means all of them.
Three smaller things: the detail pane named the operation and connection in
its header and then repeated both in a summary line the log already carried
verbatim, so it now shows the timing and the tags and says what can be done
with them; the sidebar's eleven blank rows hold the last browse as a
catalogue that persists while individual tags are read, rather than mirroring
the detail pane; and the status bar counts failures, since a message count
says nothing about whether any of them failed.
216 test cases in the browser at 79% coverage, 991 across the tools,
race-clean, gofmt and "go fix -diff" clean, apache-rat clean.
---
plc4go/tools/QUICKSTART.md | 21 +-
plc4go/tools/plc4xbrowser/browser/commands.go | 39 ++-
plc4go/tools/plc4xbrowser/browser/compose.go | 22 +-
plc4go/tools/plc4xbrowser/browser/keys_test.go | 382 +++++++++++++++++++++
plc4go/tools/plc4xbrowser/browser/model.go | 430 ++++++++++++++++++++++--
plc4go/tools/plc4xbrowser/browser/model_test.go | 8 +-
plc4go/tools/plc4xbrowser/browser/mouse_test.go | 16 +-
plc4go/tools/plc4xbrowser/browser/view.go | 39 ++-
8 files changed, 899 insertions(+), 58 deletions(-)
diff --git a/plc4go/tools/QUICKSTART.md b/plc4go/tools/QUICKSTART.md
index aaf68174..af402339 100644
--- a/plc4go/tools/QUICKSTART.md
+++ b/plc4go/tools/QUICKSTART.md
@@ -107,12 +107,18 @@ read-direct demo://nowhere temp/1
The error is pinned above the prompt until `Esc` dismisses it, and it names the connections
that *are* open. Errors used to scroll away in a ten-row console.
-### 7. Completion
+### 7. Act on what you found
+
+Browsing gives you **one** message carrying every tag, listed in **Detail** and kept in the
+sidebar as a catalogue. Select it and press `r`, `w` or `s` to read, write or subscribe to
+those tags — the request is composed for you rather than retyped. `y` copies the selection.
+
+### 8. Completion
Type `re` then `Tab`. Type `read-direct ` then `Tab` and it offers the open connection; after a
connection it offers the tag catalogue.
-### 8. Resize it
+### 9. Resize it
Shrink the terminal below 100 columns: the prompt stays visible and the layout collapses to a
single column, with the sidebar and detail reachable as overlays. Below 60×12 it says the
@@ -171,8 +177,15 @@ help # list every command
| `Alt+1` … `Alt+4` | the same, where the terminal delivers it |
| `:` or `Esc` | return the keyboard to the prompt |
| `↑` / `↓` or `k` / `j` | move within a pane; history at the prompt |
-| `g` / `G` | top / end |
-| `/` | filter |
+| `g` / `G` | first / last |
+| `PgUp` / `PgDn` | scroll a screenful |
+| `/` | filter the message list, applied as you type; `Esc` clears it |
+| `f` | follow — keep the newest message selected (on by default) |
+| `y` | copy the selection to the clipboard (works over ssh, via OSC52) |
+| `e` | expand a long error |
+| `L` | cycle the log level |
+| `r` / `w` / `s` | read, write or subscribe to the selected message's tag |
+| `b` | in Detail: the wire bytes of the request |
| `?` or `F1` | toggle full help |
| `Ctrl+C` | quit |
| `Ctrl+D` | quit, on an empty prompt — it deletes a character otherwise, as in a shell |
diff --git a/plc4go/tools/plc4xbrowser/browser/commands.go b/plc4go/tools/plc4xbrowser/browser/commands.go
index 28a6fff1..d5b7ca35 100644
--- a/plc4go/tools/plc4xbrowser/browser/commands.go
+++ b/plc4go/tools/plc4xbrowser/browser/commands.go
@@ -289,6 +289,7 @@ func browseDirectCommand() *Command {
if err := requireConnected(env, connection); err != nil {
return Result{}, err
}
+ started := env.Now()
browse, err := env.Session.Browse(ctx, connection, strings.TrimSpace(query))
if err != nil {
return Result{}, err
@@ -296,18 +297,28 @@ func browseDirectCommand() *Command {
result := Result{Lines: []string{
fmt.Sprintf("browse %s found %d tags in %s", connection, len(browse.Items), browse.Duration),
}}
- for _, item := range browse.Items {
- result.Events = append(result.Events, plcsession.Event{
- Kind: plcsession.EventBrowse,
- Connection: connection,
- Received: env.Now(),
- Summary: browseSummary(item),
- Tags: []plcsession.TagResult{{
+ // One message for the whole browse, not one per tag. Emitting a message per tag
+ // meant browsing a device with eight tags pushed eight rows into the list, all with
+ // the same timestamp, and shoved the events the user was actually watching off the
+ // screen. The tags belong in the detail pane, which is what it is for.
+ if len(browse.Items) > 0 {
+ tags := make([]plcsession.TagResult, 0, len(browse.Items))
+ for _, item := range browse.Items {
+ tags = append(tags, plcsession.TagResult{
Name: item.Name,
Address: item.Address,
DataType: item.DataType,
+ Value: browseAccess(item),
Code: plcsession.ResponseCodeOK,
- }},
+ })
+ }
+ result.Events = append(result.Events, plcsession.Event{
+ Kind: plcsession.EventBrowse,
+ Connection: connection,
+ Started: started,
+ Received: env.Now(),
+ Tags: tags,
+ Summary: fmt.Sprintf("%d tags", len(tags)),
})
}
if len(browse.Items) == 0 {
@@ -524,8 +535,9 @@ func resultForTags(env *Env, kind plcsession.EventKind, connection string, tags
}
}
-// browseSummary renders one browse item for the message list.
-func browseSummary(item plcsession.BrowseItem) string {
+// browseAccess renders a browsed tag's access flags as rws, which is what a user needs before
+// choosing to read, write or subscribe to it.
+func browseAccess(item plcsession.BrowseItem) string {
var access strings.Builder
for _, flag := range []struct {
enabled bool
@@ -537,7 +549,12 @@ func browseSummary(item plcsession.BrowseItem) string {
access.WriteString("-")
}
}
- return fmt.Sprintf("%s %s %s %s", item.Address, item.DataType, access.String(), item.Name)
+ // The address and the data type are already columns of their own wherever this is shown, so
+ // repeating them here rendered each tag twice over.
+ if item.Name != "" {
+ return access.String() + " " + item.Name
+ }
+ return access.String()
}
// suggestConnections offers the open connections.
diff --git a/plc4go/tools/plc4xbrowser/browser/compose.go b/plc4go/tools/plc4xbrowser/browser/compose.go
index a38b5065..b8ee39d5 100644
--- a/plc4go/tools/plc4xbrowser/browser/compose.go
+++ b/plc4go/tools/plc4xbrowser/browser/compose.go
@@ -317,19 +317,25 @@ func (m *Model) submitComposer() (tea.Model, tea.Cmd) {
out := Result{Lines: []string{
"browse " + connection + " found " + strconv.Itoa(len(result.Items)) + " tags",
}}
- for _, item := range result.Items {
+ // One message for the whole browse; see browseDirectCommand for why.
+ if len(result.Items) > 0 {
+ tags := make([]plcsession.TagResult, 0, len(result.Items))
+ for _, item := range result.Items {
+ tags = append(tags, plcsession.TagResult{
+ Name: item.Name,
+ Address: item.Address,
+ DataType: item.DataType,
+ Value: browseAccess(item),
+ Code: plcsession.ResponseCodeOK,
+ })
+ }
out.Events = append(out.Events, plcsession.Event{
Kind: plcsession.EventBrowse,
Connection: connection,
Started: started,
Received: env.Now(),
- Summary: browseSummary(item),
- Tags: []plcsession.TagResult{{
- Name: item.Name,
- Address: item.Address,
- DataType: item.DataType,
- Code: plcsession.ResponseCodeOK,
- }},
+ Tags: tags,
+ Summary: strconv.Itoa(len(tags)) + " tags",
})
}
return commandDoneMsg{result: out}
diff --git a/plc4go/tools/plc4xbrowser/browser/keys_test.go b/plc4go/tools/plc4xbrowser/browser/keys_test.go
new file mode 100644
index 00000000..797d33b9
--- /dev/null
+++ b/plc4go/tools/plc4xbrowser/browser/keys_test.go
@@ -0,0 +1,382 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package browser
+
+import (
+ "strconv"
+ "strings"
+ "testing"
+
+ "charm.land/bubbles/v2/key"
+ "charm.land/bubbles/v2/table"
+ tea "charm.land/bubbletea/v2"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/apache/plc4x-extras/plc4go/tools/internal/plcsession"
+ "github.com/apache/plc4x-extras/plc4go/tools/internal/tui"
+)
+
+// The browser advertised seven keys in its help and implemented none of them: g/G, the page
+// keys, the filter, yank, follow, expand and the log level. That is the dead-affordance defect
+// the port existed to remove, reintroduced in the footer, so each one is pinned here.
+
+// inPane focuses a pane by its number and returns the model.
+func inPane(t *testing.T, model *Model, digit rune) *Model {
+ t.Helper()
+ press(t, model, tea.KeyPressMsg{Code: digit, Mod: tea.ModAlt})
+ _, promptFocused := model.Focused()
+ require.False(t, promptFocused, "pane %c should have the keyboard", digit)
+ return model
+}
+
+// withMessages returns a model carrying several distinct messages.
+func withMessages(t *testing.T, addresses ...string) *Model {
+ t.Helper()
+ model := sized(t, newTestModel(t), 120, 30)
+ for _, address := range addresses {
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " " + address})
+ runCmd(t, model, cmd)
+ }
+ return model
+}
+
+// TestEveryAdvertisedPaneKeyIsHandled is the guard against the help lying again. It walks the
+// bindings the footer actually shows and asserts the model reacts to each.
+func TestEveryAdvertisedPaneKeyIsHandled(t *testing.T) {
+ keys := tui.NewKeyMap().ForFocus(tui.FocusPane)
+ advertised := map[string]key.Binding{
+ "Top": keys.Top, "Bottom": keys.Bottom,
+ "PageUp": keys.PageUp, "PageDown": keys.PageDown,
+ "Filter": keys.Filter, "Wrap": keys.Wrap, "Yank": keys.Yank,
+ "Follow": keys.Follow, "Expand": keys.Expand, "LogLevel": keys.LogLevel,
+ "Select": keys.Select, "Up": keys.Up, "Down": keys.Down,
+ }
+
+ // Select is left out: enter on the already-selected row is idempotent by design, so a
+ // "something changed" assertion cannot express it. It has its own tests, as does the
+ // sidebar's use of it.
+ delete(advertised, "Select")
+
+ for name, binding := range advertised {
+ t.Run(name, func(t *testing.T) {
+ require.NotEmpty(t, binding.Keys(), "%s is advertised, so it must be bound", name)
+
+ model := withMessages(t, "temp/1", "press/1", "flow/1")
+ model = inPane(t, model, '2')
+ // Park the cursor mid-list so that both ends have somewhere to go: following keeps
+ // it on the last row, where G is legitimately a no-op.
+ press(t, model, tea.KeyPressMsg{Code: 'g', Text: "g"})
+ press(t, model, tea.KeyPressMsg{Code: 'j', Text: "j"})
+ before := snapshot(model)
+
+ press(t, model, tea.KeyPressMsg{Code: rune(binding.Keys()[0][0]), Text: binding.Keys()[0]})
+ assert.NotEqual(t, before, snapshot(model),
+ "%s (%v) changed nothing; the footer advertises it, so it must do something",
+ name, binding.Keys())
+ })
+ }
+}
+
+// snapshot captures the observable state a key press could plausibly change.
+func snapshot(m *Model) string {
+ shown, total := m.EventCount()
+ focus, promptFocused := m.Focused()
+ return strings.Join([]string{
+ strconv.Itoa(shown), strconv.Itoa(total), strconv.Itoa(int(focus)),
+ strconv.FormatBool(promptFocused), strconv.FormatBool(m.Following()),
+ strconv.FormatBool(m.Filtering()), strconv.FormatBool(m.detailBytes),
+ strconv.FormatBool(m.toastExpanded), m.options.Config.LogLevel,
+ strconv.Itoa(m.messages.Cursor()), m.yanked, m.PromptValue(),
+ strconv.FormatBool(m.ComposerOpen()),
+ }, "|")
+}
+
+func TestTopAndBottomMoveTheMessageCursor(t *testing.T) {
+ model := withMessages(t, "temp/1", "press/1", "flow/1", "temp/2")
+ model = inPane(t, model, '2')
+
+ press(t, model, tea.KeyPressMsg{Code: 'g', Text: "g"})
+ assert.Zero(t, model.messages.Cursor(), "g goes to the first message")
+
+ press(t, model, tea.KeyPressMsg{Code: 'G', Text: "G"})
+ shown, _ := model.EventCount()
+ assert.Equal(t, shown-1, model.messages.Cursor(), "G goes to the last")
+}
+
+func TestTopStopsFollowingSoTheCursorStaysPut(t *testing.T) {
+ model := withMessages(t, "temp/1", "press/1")
+ model = inPane(t, model, '2')
+ require.True(t, model.Following())
+
+ press(t, model, tea.KeyPressMsg{Code: 'g', Text: "g"})
+ assert.False(t, model.Following(), "moving to the top by hand means taking over from the stream")
+}
+
+func TestFollowKeepsTheNewestMessageSelected(t *testing.T) {
+ model := withMessages(t, "temp/1", "press/1")
+ model = inPane(t, model, '2')
+
+ // Turn following off, move away, then a new message must not steal the selection.
+ press(t, model, tea.KeyPressMsg{Code: 'f', Text: "f"})
+ require.False(t, model.Following())
+ press(t, model, tea.KeyPressMsg{Code: 'g', Text: "g"})
+ at := model.messages.Cursor()
+
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " flow/1"})
+ runCmd(t, model, cmd)
+ assert.Equal(t, at, model.messages.Cursor(), "with following off a new message must not move the cursor")
+
+ press(t, model, tea.KeyPressMsg{Code: 'f', Text: "f"})
+ require.True(t, model.Following())
+ shown, _ := model.EventCount()
+ assert.Equal(t, shown-1, model.messages.Cursor(), "turning it back on jumps to the newest")
+}
+
+func TestTheFilterNarrowsAsItIsTypedAndEscapeClearsIt(t *testing.T) {
+ model := withMessages(t, "temp/1", "press/1", "temp/2")
+ model = inPane(t, model, '2')
+ _, total := model.EventCount()
+
+ press(t, model, tea.KeyPressMsg{Code: '/', Text: "/"})
+ require.True(t, model.Filtering(), "/ starts the filter line")
+
+ for _, r := range "press" {
+ press(t, model, tea.KeyPressMsg{Code: r, Text: string(r)})
+ }
+ shown, stillTotal := model.EventCount()
+ assert.Less(t, shown, total, "the list must narrow as the filter is typed")
+ assert.Equal(t, total, stillTotal, "and nothing may be discarded")
+
+ press(t, model, tea.KeyPressMsg{Code: tea.KeyEnter})
+ assert.False(t, model.Filtering(), "enter commits the filter")
+
+ press(t, model, tea.KeyPressMsg{Code: '/', Text: "/"})
+ press(t, model, tea.KeyPressMsg{Code: tea.KeyEscape})
+ shown, _ = model.EventCount()
+ assert.Equal(t, total, shown, "escape clears the filter, showing everything again")
+}
+
+func TestTheFilterLineTakesPrecedenceOverPaneKeys(t *testing.T) {
+ model := withMessages(t, "temp/1")
+ model = inPane(t, model, '2')
+ press(t, model, tea.KeyPressMsg{Code: '/', Text: "/"})
+
+ // "g" would be a top-of-list jump outside the filter; inside it, it is text.
+ press(t, model, tea.KeyPressMsg{Code: 'g', Text: "g"})
+ assert.True(t, model.Filtering(), "the filter line keeps the keyboard")
+ assert.Equal(t, "g", model.filterDraft)
+}
+
+func TestYankCopiesTheSelectedMessage(t *testing.T) {
+ model := withMessages(t, "temp/1")
+ model = inPane(t, model, '2')
+
+ _, cmd := model.Update(tea.KeyPressMsg{Code: 'y', Text: "y"})
+ require.NotNil(t, cmd, "y must produce a clipboard command")
+ assert.NotEmpty(t, model.yanked)
+ assert.Contains(t, model.yanked, "temp/1", "the copied text must carry the tag")
+ // tea.SetClipboard writes an OSC52 sequence, which works over ssh as well as locally.
+ assert.NotNil(t, cmd())
+}
+
+func TestLogLevelCyclesAndIsRecorded(t *testing.T) {
+ model := withMessages(t, "temp/1")
+ model = inPane(t, model, '2')
+
+ first := model.options.Config.LogLevel
+ press(t, model, tea.KeyPressMsg{Code: 'L', Text: "L"})
+ second := model.options.Config.LogLevel
+ assert.NotEqual(t, first, second, "L must change the level")
+ assert.Contains(t, strings.Join(model.LogLines(), "\n"), "log level "+second,
+ "and say so, since the change is otherwise invisible")
+}
+
+func TestExpandTogglesTheToast(t *testing.T) {
+ model := sized(t, newTestModel(t), 120, 30)
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct demo://nowhere temp/1"})
+ runCmd(t, model, cmd)
+ require.NotEmpty(t, model.Toast())
+
+ model = inPane(t, model, '2')
+ require.False(t, model.toastExpanded)
+ press(t, model, tea.KeyPressMsg{Code: 'e', Text: "e"})
+ assert.True(t, model.toastExpanded, "e must expand the error")
+}
+
+// TestRWSComposeFromTheSelectedMessage is the workflow fix: browse, see a tag, act on it
+// without retyping the address the pane is already showing.
+func TestRWSComposeFromTheSelectedMessage(t *testing.T) {
+ for pressed, want := range map[rune]Operation{
+ 'r': OperationRead,
+ 'w': OperationWrite,
+ 's': OperationSubscribe,
+ } {
+ t.Run(string(pressed), func(t *testing.T) {
+ model := withMessages(t, "temp/1")
+ model = inPane(t, model, '2')
+
+ press(t, model, tea.KeyPressMsg{Code: pressed, Text: string(pressed)})
+ require.True(t, model.ComposerOpen(), "%c must open the composer", pressed)
+ assert.Equal(t, want, model.composer.operation)
+ assert.Equal(t, plcsession.DemoDeviceOne, model.composer.connection)
+ require.Len(t, model.composer.rows, 1)
+ assert.Equal(t, "temp/1", model.composer.rows[0].address,
+ "the tag must be carried over rather than retyped")
+ })
+ }
+}
+
+func TestComposingFromABrowseCarriesEveryTag(t *testing.T) {
+ model := sized(t, newTestModel(t), 120, 30)
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
+ runCmd(t, model, cmd)
+ model = inPane(t, model, '2')
+
+ press(t, model, tea.KeyPressMsg{Code: 'r', Text: "r"})
+ require.True(t, model.ComposerOpen())
+ assert.Greater(t, len(model.composer.rows), 1,
+ "reading a browse result should offer every tag it found, not just the first")
+}
+
+// TestTheMessageColumnsFitThePaneExactly is the regression test for a table that claimed 48
+// cells in a 40-cell pane at the tool's own reference size. It truncated, and what it
+// truncated was the tag -- the field the row exists to show.
+func TestTheMessageColumnsFitThePaneExactly(t *testing.T) {
+ for _, width := range []int{24, 30, 38, 40, 48, 58, 70, 78, 96, 140} {
+ for _, showConnection := range []bool{false, true} {
+ name := strconv.Itoa(width)
+ if showConnection {
+ name += "+conn"
+ }
+ t.Run(name, func(t *testing.T) {
+ total := 0
+ tagWidth := 0
+ for _, column := range messageColumns(width, showConnection) {
+ total += column.Width
+ assert.Positive(t, column.Width, "%q must not be given zero width", column.Title)
+ if column.Title == "tag" {
+ tagWidth = column.Width
+ }
+ }
+ assert.Equal(t, width, total,
+ "the columns must use exactly the pane's width, not more")
+ assert.GreaterOrEqual(t, tagWidth, 8,
+ "the tag is what the row is for; it must never be squeezed below eight cells")
+ })
+ }
+ }
+}
+
+// TestTheConnectionColumnOnlyAppearsWhenItDistinguishesSomething: with one connection open it
+// would repeat the same string on every row while the tag paid for the space.
+func TestTheConnectionColumnOnlyAppearsWhenItDistinguishesSomething(t *testing.T) {
+ hasConnection := func(columns []table.Column) bool {
+ for _, column := range columns {
+ if column.Title == "connection" {
+ return true
+ }
+ }
+ return false
+ }
+
+ assert.False(t, hasConnection(messageColumns(140, false)),
+ "one connection open: the column would say the same thing on every row")
+ assert.True(t, hasConnection(messageColumns(140, true)),
+ "several connections: now it tells rows apart")
+ assert.False(t, hasConnection(messageColumns(44, true)),
+ "narrow: the tag keeps the space even when there are connections to distinguish")
+}
+
+func TestTheModelOffersTheConnectionColumnOnlyWithSeveralConnections(t *testing.T) {
+ model := sized(t, newTestModel(t), 140, 30)
+ assert.False(t, model.showConnectionColumn(), "the fixture opens one connection")
+
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "connect " + plcsession.DemoDeviceTwo})
+ runCmd(t, model, cmd)
+ assert.True(t, model.showConnectionColumn())
+}
+
+// TestABrowseIsOneMessageCarryingEveryTag is the flooding fix: one message per tag meant
+// browsing an eight-tag device pushed eight rows in and shoved real events off the screen.
+func TestABrowseIsOneMessageCarryingEveryTag(t *testing.T) {
+ model := sized(t, newTestModel(t), 120, 30)
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
+ runCmd(t, model, cmd)
+
+ shown, total := model.EventCount()
+ assert.Equal(t, 1, total, "a browse is one message, however many tags it found")
+ assert.Equal(t, 1, shown)
+
+ event, ok := model.SelectedEvent()
+ require.True(t, ok)
+ assert.Greater(t, len(event.Tags), 1, "and it carries every tag it found")
+ assert.Equal(t, plcsession.EventBrowse, event.Kind)
+}
+
+// TestTheSidebarKeepsTheBrowseCatalogue: it is a reference you refer back to while reading
+// individual tags, which is why it is not simply the selected message's tags -- that would
+// show the same list the detail pane is already showing.
+func TestTheSidebarKeepsTheBrowseCatalogue(t *testing.T) {
+ model := sized(t, newTestModel(t), 120, 30)
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
+ runCmd(t, model, cmd)
+
+ rendered := strings.Join(renderLines(t, model), "\n")
+ assert.Contains(t, rendered, "TAGS", "the browse result belongs in the sidebar's dead space")
+ assert.Contains(t, rendered, "motor/speed", "and it lists the tags")
+
+ // Move on to a read: the catalogue must persist rather than follow the selection.
+ _, cmd = model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " temp/1"})
+ runCmd(t, model, cmd)
+ rendered = strings.Join(renderLines(t, model), "\n")
+ assert.Contains(t, rendered, "motor/speed",
+ "the catalogue is a reference; it must not vanish when the selection moves")
+}
+
+// TestTheStatusBarCountsFailures: a message count says nothing about whether any failed, which
+// is the one number worth glancing at.
+func TestTheStatusBarCountsFailures(t *testing.T) {
+ model := sized(t, newTestModel(t), 120, 30)
+ status := renderLines(t, model)[0]
+ assert.NotContains(t, status, "failed", "nothing has failed yet")
+
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " no/such/tag"})
+ runCmd(t, model, cmd)
+
+ assert.Equal(t, 1, model.FailedCount())
+ assert.Contains(t, renderLines(t, model)[0], "1 failed")
+}
+
+// TestTheDetailPaneDoesNotRepeatItself pins the de-duplication: the header already names the
+// operation and the connection, and the log carries the timing line verbatim.
+func TestTheDetailPaneDoesNotRepeatItself(t *testing.T) {
+ model := withMessages(t, "temp/1")
+ event, ok := model.SelectedEvent()
+ require.True(t, ok)
+
+ rendered := renderEventDetail(testTheme(), event)
+ occurrences := strings.Count(rendered, plcsession.DemoDeviceOne)
+ assert.Equal(t, 1, occurrences,
+ "the connection should be named once, not in a header and again in a summary:\n%s", rendered)
+ assert.NotContains(t, rendered, "tags in",
+ "the timing sentence belongs in the log, not repeated in the detail body")
+ assert.Contains(t, rendered, "r read", "the detail pane should advertise what can be done with the tag")
+}
diff --git a/plc4go/tools/plc4xbrowser/browser/model.go b/plc4go/tools/plc4xbrowser/browser/model.go
index e7d6427e..940d997e 100644
--- a/plc4go/tools/plc4xbrowser/browser/model.go
+++ b/plc4go/tools/plc4xbrowser/browser/model.go
@@ -31,6 +31,8 @@ import (
"charm.land/bubbles/v2/viewport"
tea "charm.land/bubbletea/v2"
+ "github.com/rs/zerolog"
+
"github.com/apache/plc4x-extras/plc4go/tools/internal/plcsession"
"github.com/apache/plc4x-extras/plc4go/tools/internal/tui"
)
@@ -133,7 +135,26 @@ type Model struct {
messages table.Model
detail viewport.Model
// detailBytes switches the detail pane to the wire bytes of the selected request.
- detailBytes bool
+ detailBytes bool
+ // follow keeps the newest message selected as events arrive. On by default, because a tool
+ // watching a subscription is usually watching the latest value; it turns itself off the
+ // moment the cursor is moved by hand.
+ follow bool
+ // filtering is true while the filter line is being typed, which claims the keyboard.
+ filtering bool
+ // filterDraft is the filter being typed, applied on enter.
+ filterDraft string
+ // toastExpanded shows the whole of a long error instead of one clipped line.
+ toastExpanded bool
+ // yanked records what was last copied, so the interface can confirm it.
+ yanked string
+ // catalogue is the tags the last browse found, kept as a reference list. Deliberately not
+ // "the selected message's tags": mirroring the detail pane in the sidebar would show the
+ // same thing twice, whereas a catalogue that persists is what you want beside the message
+ // list once you have moved on to reading individual tags.
+ catalogue []plcsession.TagResult
+ catalogueConnection string
+
logView viewport.Model
composer *composer
sidebarRows []sidebarRow
@@ -194,13 +215,14 @@ func NewModel(options Options) *Model {
model.help = tui.NewHelpFooter(theme)
model.messages = table.New(
- table.WithColumns(messageColumns(80)),
+ table.WithColumns(messageColumns(80, false)),
table.WithFocused(false),
table.WithStyles(tableStyles(theme)),
)
model.detail = viewport.New()
model.logView = viewport.New()
model.promptFocused = true
+ model.follow = true
model.refreshSidebar()
return model
}
@@ -214,20 +236,82 @@ func themeOptions(dark bool, options Options) tui.Options {
return themeOptions
}
-// messageColumns sizes the message table for a pane width.
-func messageColumns(width int) []table.Column {
- // The fixed columns are sized to their content; the connection column takes what is left,
- // because a connection string is the one field that is unboundedly long.
- const fixed = 4 + 14 + 10 + 12 + 8
- connection := max(width-fixed, 10)
- return []table.Column{
- {Title: "#", Width: 4},
- {Title: "time", Width: 14},
- {Title: "op", Width: 10},
- {Title: "connection", Width: connection},
- {Title: "tag", Width: 12},
- {Title: "code", Width: 8},
+// messageColumns sizes the message table to exactly the width it is given.
+//
+// The previous fixed widths claimed 48 cells, which is eight more than the pane has at the
+// tool's own reference size of 100 columns. The table then truncated, and what it truncated was
+// the tag -- the one field the row exists to show -- while the connection column repeated the
+// same string on every line. Columns are therefore budgeted in order of what a row is for: the
+// tag and its outcome first, the connection last, since with one connection open it says
+// nothing at all.
+func messageColumns(width int, showConnection bool) []table.Column {
+ width = max(width, 24)
+
+ // Columns are dropped, not squeezed. Squeezing is what the fixed widths did: they claimed
+ // 48 cells in the 40-cell pane the reference layout gives, and the table then truncated the
+ // tag -- the one field a row exists to show. So the budget is spent in priority order and
+ // whatever does not fit is left out entirely, which is legible where a two-character column
+ // is not.
+ const tagFloor = 8
+
+ stamp, operation, code := 13, 10, 7
+ if width < 70 {
+ // To the second is enough to place an event; the millisecond is in the detail pane.
+ stamp, operation, code = 9, 7, 7
+ }
+
+ // number and connection are the two the tag outranks.
+ number := 4
+ connection := 0
+ if showConnection && width >= 4+stamp+operation+code+tagFloor+16 {
+ connection = 16
+ }
+
+ remaining := func() int { return width - number - stamp - operation - code - connection }
+ if remaining() < tagFloor {
+ connection = 0
+ }
+ if remaining() < tagFloor {
+ // The row number is positional and repeated in the detail pane's ordering, so it is the
+ // next thing the tag can have.
+ number = 0
+ }
+ if remaining() < tagFloor {
+ code = 4 // "OK" or "bad"
+ }
+ if remaining() < tagFloor {
+ operation = 5 // "read", "brow", "subs"
+ }
+ if remaining() < tagFloor {
+ stamp = 8 // HH:MM:SS
+ }
+ if remaining() < tagFloor {
+ // At the very floor -- a pane in a 60-column terminal -- even the operation goes. The
+ // detail pane names it, and a tag clipped to five characters names nothing.
+ operation = 0
+ }
+
+ var columns []table.Column
+ if number > 0 {
+ columns = append(columns, table.Column{Title: "#", Width: number})
+ }
+ columns = append(columns, table.Column{Title: "time", Width: stamp})
+ if operation > 0 {
+ columns = append(columns, table.Column{Title: "op", Width: operation})
}
+ if connection > 0 {
+ columns = append(columns, table.Column{Title: "connection", Width: connection})
+ }
+ return append(columns,
+ table.Column{Title: "tag", Width: max(remaining(), 1)},
+ table.Column{Title: "code", Width: code},
+ )
+}
+
+// showConnectionColumn reports whether the connection is worth a column: only once more than
+// one is open, since otherwise every row would carry the same string.
+func (m *Model) showConnectionColumn() bool {
+ return len(m.options.Session.Connections()) > 1
}
// tableStyles maps the theme onto the table's own styling.
@@ -317,6 +401,11 @@ func (m *Model) handleKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
return m.updateComposer(msg)
}
+ // The filter line is text entry, so it takes every key but the ones that finish it.
+ if m.filtering {
+ return m.filterKey(msg)
+ }
+
keys := m.keys.ForFocus(m.currentFocus())
switch {
@@ -421,6 +510,42 @@ func paneForDigit(name string) (pane, bool) {
return pane(digit - 1), true
}
+// filterKey handles a key while the message filter is being typed.
+func (m *Model) filterKey(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
+ switch msg.String() {
+ case "esc":
+ // Escape abandons the edit and clears the filter, which is the only way back to the
+ // whole list that does not require deleting what was typed.
+ m.filtering = false
+ m.filterDraft = ""
+ m.SetFilter("")
+ return m, nil
+ case "enter":
+ m.filtering = false
+ m.SetFilter(m.filterDraft)
+ return m, nil
+ case "backspace":
+ if m.filterDraft != "" {
+ runes := []rune(m.filterDraft)
+ m.filterDraft = string(runes[:len(runes)-1])
+ m.SetFilter(m.filterDraft)
+ }
+ return m, nil
+ }
+ if text := msg.String(); len([]rune(text)) == 1 {
+ m.filterDraft += text
+ // Applied as it is typed: seeing the list narrow is the whole point of a filter.
+ m.SetFilter(m.filterDraft)
+ }
+ return m, nil
+}
+
+// Filtering reports whether the filter line is being typed, for tests.
+func (m *Model) Filtering() bool { return m.filtering }
+
+// Following reports whether the newest message stays selected, for tests.
+func (m *Model) Following() bool { return m.follow }
+
// currentFocus maps the model's focus onto the keymap's notion of it.
func (m *Model) currentFocus() tui.Focus {
switch {
@@ -434,7 +559,31 @@ func (m *Model) currentFocus() tui.Focus {
}
// paneKey handles a key aimed at the focused pane.
+//
+// Every binding the help advertises is handled here. That is not a nicety: the shared keymap
+// puts g/G, the page keys, the filter, yank, follow, expand and the log level in the footer,
+// and for a while the browser advertised all seven and implemented none of them -- the same
+// dead-affordance defect the port existed to remove, reintroduced in the help text.
func (m *Model) paneKey(msg tea.KeyPressMsg, keys tui.KeyMap) (tea.Model, tea.Cmd) {
+ // Bindings that mean the same thing in every pane.
+ switch {
+ case key.Matches(msg, keys.Top):
+ return m, m.paneTop()
+ case key.Matches(msg, keys.Bottom):
+ return m, m.paneBottom()
+ case key.Matches(msg, keys.PageUp):
+ return m, m.panePage(-1)
+ case key.Matches(msg, keys.PageDown):
+ return m, m.panePage(1)
+ case key.Matches(msg, keys.Yank):
+ return m.yank()
+ case key.Matches(msg, keys.Expand):
+ m.toastExpanded = !m.toastExpanded
+ return m, nil
+ case key.Matches(msg, keys.LogLevel):
+ return m.cycleLogLevel()
+ }
+
switch m.focus {
case paneSidebar:
switch {
@@ -448,12 +597,34 @@ func (m *Model) paneKey(msg tea.KeyPressMsg, keys tui.KeyMap) (tea.Model, tea.Cm
return m.activateSidebarRow()
}
case paneMessages:
- if key.Matches(msg, keys.Select) {
+ switch {
+ case key.Matches(msg, keys.Filter):
+ m.filtering = true
+ m.filterDraft = m.filter
+ return m, nil
+ case key.Matches(msg, keys.Follow):
+ m.follow = !m.follow
+ if m.follow {
+ m.messages.GotoBottom()
+ m.syncDetail()
+ }
+ return m, nil
+ case key.Matches(msg, keys.Select):
m.syncDetail()
return m, nil
}
+ // Composing a request from the selected message's tag: browse, see a tag, act on it.
+ // Retyping the address the pane is already showing was the sharpest edge in the tool.
+ if spec, ok := m.composeFromSelection(msg.String()); ok {
+ m.openComposer(spec)
+ return m, nil
+ }
var cmd tea.Cmd
m.messages, cmd = m.messages.Update(msg)
+ // Moving the cursor by hand means the user has taken over from the stream.
+ if key.Matches(msg, keys.Up) || key.Matches(msg, keys.Down) {
+ m.follow = false
+ }
m.syncDetail()
return m, cmd
case paneDetail:
@@ -478,6 +649,166 @@ func (m *Model) paneKey(msg tea.KeyPressMsg, keys tui.KeyMap) (tea.Model, tea.Cm
return m, nil
}
+// paneTop jumps the focused pane to its start.
+func (m *Model) paneTop() tea.Cmd {
+ switch m.focus {
+ case paneSidebar:
+ m.sidebarIndex = 0
+ m.clampSidebar()
+ case paneMessages:
+ m.messages.GotoTop()
+ m.follow = false
+ m.syncDetail()
+ case paneDetail:
+ m.detail.GotoTop()
+ case paneLog:
+ m.logView.GotoTop()
+ }
+ return nil
+}
+
+// paneBottom jumps the focused pane to its end.
+func (m *Model) paneBottom() tea.Cmd {
+ switch m.focus {
+ case paneSidebar:
+ m.sidebarIndex = len(m.sidebarRows) - 1
+ m.clampSidebar()
+ case paneMessages:
+ m.messages.GotoBottom()
+ m.syncDetail()
+ case paneDetail:
+ m.detail.GotoBottom()
+ case paneLog:
+ m.logView.GotoBottom()
+ }
+ return nil
+}
+
+// panePage scrolls the focused pane by a screenful in a direction.
+func (m *Model) panePage(direction int) tea.Cmd {
+ switch m.focus {
+ case paneSidebar:
+ for range max(m.layout.BodyHeight-2, 1) {
+ m.moveSidebar(direction)
+ }
+ case paneMessages:
+ page := max(m.messages.Height(), 1)
+ if direction < 0 {
+ m.messages.MoveUp(page)
+ } else {
+ m.messages.MoveDown(page)
+ }
+ m.follow = false
+ m.syncDetail()
+ case paneDetail:
+ m.detail.SetYOffset(max(m.detail.YOffset()+direction*max(m.detail.Height(), 1), 0))
+ case paneLog:
+ m.logView.SetYOffset(max(m.logView.YOffset()+direction*max(m.logView.Height(), 1), 0))
+ }
+ return nil
+}
+
+// yank copies what the focused pane is showing to the clipboard.
+//
+// tea.SetClipboard writes an OSC52 sequence, which the terminal forwards to the local
+// clipboard, so this works over ssh as well as locally.
+func (m *Model) yank() (tea.Model, tea.Cmd) {
+ text := ""
+ switch m.focus {
+ case paneSidebar:
+ if row, ok := m.SidebarSelection(); ok {
+ text = row.label
+ }
+ case paneMessages, paneDetail:
+ if event, ok := m.SelectedEvent(); ok {
+ text = yankText(event)
+ }
+ case paneLog:
+ text = strings.Join(m.logLines, "\n")
+ }
+ if text == "" {
+ return m, nil
+ }
+ m.yanked = text
+ m.appendLog("copied " + strconv.Itoa(len(text)) + " bytes to the clipboard")
+ return m, tea.SetClipboard(text)
+}
+
+// yankText renders an event as the plain text a user would want on the clipboard: the values,
+// not the styling.
+func yankText(event plcsession.Event) string {
+ var parts []string
+ parts = append(parts, string(event.Kind)+" "+event.Connection)
+ for _, tag := range event.Tags {
+ line := tag.Address
+ if tag.DataType != "" {
+ line += " " + tag.DataType
+ }
+ if tag.Value != "" {
+ line += " " + tag.Value
+ }
+ if !tag.Succeeded() {
+ line += " " + tag.Code
+ }
+ parts = append(parts, line)
+ }
+ return strings.Join(parts, "\n")
+}
+
+// cycleLogLevel steps the log level, so the noise can be turned up without leaving the pane.
+func (m *Model) cycleLogLevel() (tea.Model, tea.Cmd) {
+ order := []zerolog.Level{
+ zerolog.ErrorLevel, zerolog.WarnLevel, zerolog.InfoLevel, zerolog.DebugLevel, zerolog.TraceLevel,
+ }
+ current, err := zerolog.ParseLevel(m.options.Config.LogLevel)
+ if err != nil {
+ current = zerolog.InfoLevel
+ }
+ next := order[0]
+ for i, level := range order {
+ if level == current {
+ next = order[(i+1)%len(order)]
+ break
+ }
+ }
+ m.options.Config.LogLevel = next.String()
+ zerolog.SetGlobalLevel(next)
+ m.appendLog("log level " + next.String())
+ return m, nil
+}
+
+// composeFromSelection turns r, w or s pressed over a message into a pre-filled request for
+// the tag that message is showing.
+func (m *Model) composeFromSelection(pressed string) (ComposeSpec, bool) {
+ var operation Operation
+ switch pressed {
+ case "r":
+ operation = OperationRead
+ case "w":
+ operation = OperationWrite
+ case "s":
+ operation = OperationSubscribe
+ default:
+ return ComposeSpec{}, false
+ }
+
+ event, ok := m.SelectedEvent()
+ if !ok || len(event.Tags) == 0 {
+ return ComposeSpec{}, false
+ }
+ tags := make([]plcsession.TagSpec, 0, len(event.Tags))
+ for i, tag := range event.Tags {
+ if tag.Address == "" {
+ continue
+ }
+ tags = append(tags, plcsession.TagSpec{Name: "tag" + strconv.Itoa(i+1), Address: tag.Address})
+ }
+ if len(tags) == 0 {
+ return ComposeSpec{}, false
+ }
+ return ComposeSpec{Operation: operation, Connection: event.Connection, Tags: tags}, true
+}
+
// focusPrompt returns the keyboard to the command line.
func (m *Model) focusPrompt() {
m.promptFocused = true
@@ -599,11 +930,18 @@ func (m *Model) applyResult(result Result) (tea.Model, tea.Cmd) {
m.appendLog(line)
}
if len(result.Events) > 0 {
+ for _, event := range result.Events {
+ if event.Kind == plcsession.EventBrowse && len(event.Tags) > 0 {
+ m.catalogue = event.Tags
+ m.catalogueConnection = event.Connection
+ }
+ }
m.events = append(m.events, result.Events...)
m.trimEvents()
m.refreshMessages()
}
if result.Clear.Has(ClearMessages) {
+ m.catalogue, m.catalogueConnection = nil, ""
m.events = nil
m.refreshMessages()
m.detail.SetContent("")
@@ -730,19 +1068,45 @@ func eventHaystack(event plcsession.Event) string {
// refreshMessages rebuilds the table rows from the events.
func (m *Model) refreshMessages() {
events := m.filteredEvents()
+ columns := m.messages.Columns()
+ // The row has to match the columns the table was given: a cell more or fewer than there are
+ // columns is silently dropped or leaves a hole.
+ withConnection, withNumber, withOperation := false, false, false
+ stampWidth := 9
+ for _, column := range columns {
+ switch column.Title {
+ case "connection":
+ withConnection = true
+ case "#":
+ withNumber = true
+ case "op":
+ withOperation = true
+ case "time":
+ stampWidth = column.Width
+ }
+ }
+ layout := "15:04:05"
+ if stampWidth >= 13 {
+ layout = "15:04:05.000"
+ }
+
rows := make([]table.Row, 0, len(events))
for i, event := range events {
- rows = append(rows, table.Row{
- fmt.Sprintf("%d", i+1),
- event.Received.Format("15:04:05.000"),
- string(event.Kind),
- event.Connection,
- firstTagAddress(event),
- eventCode(event),
- })
+ var row table.Row
+ if withNumber {
+ row = append(row, strconv.Itoa(i+1))
+ }
+ row = append(row, event.Received.Format(layout))
+ if withOperation {
+ row = append(row, string(event.Kind))
+ }
+ if withConnection {
+ row = append(row, event.Connection)
+ }
+ rows = append(rows, append(row, firstTagAddress(event), eventCode(event)))
}
m.messages.SetRows(rows)
- if len(rows) > 0 {
+ if m.follow && len(rows) > 0 {
m.messages.GotoBottom()
}
m.syncDetail()
@@ -804,6 +1168,20 @@ func (m *Model) SelectedEvent() (plcsession.Event, bool) {
return events[cursor], true
}
+// FailedCount reports how many held messages carry a failed tag.
+func (m *Model) FailedCount() int {
+ failed := 0
+ for _, event := range m.events {
+ for _, tag := range event.Tags {
+ if !tag.Succeeded() {
+ failed++
+ break
+ }
+ }
+ }
+ return failed
+}
+
// EventCount reports how many messages are held and how many the filter shows.
func (m *Model) EventCount() (shown, total int) {
return len(m.filteredEvents()), len(m.events)
@@ -928,7 +1306,7 @@ func (m *Model) resize(size tui.Size) {
m.messages.SetWidth(max(mainWidth-2, 1))
m.messages.SetHeight(tableHeight)
- m.messages.SetColumns(messageColumns(max(mainWidth-2, 12)))
+ m.messages.SetColumns(messageColumns(max(mainWidth-2, 12), m.showConnectionColumn()))
m.detail.SetWidth(max(detailWidth(m.layout)-2, 1))
m.detail.SetHeight(max(m.layout.BodyHeight-tableHeight-4, 1))
diff --git a/plc4go/tools/plc4xbrowser/browser/model_test.go b/plc4go/tools/plc4xbrowser/browser/model_test.go
index 1f2aa38f..14ad662b 100644
--- a/plc4go/tools/plc4xbrowser/browser/model_test.go
+++ b/plc4go/tools/plc4xbrowser/browser/model_test.go
@@ -323,8 +323,12 @@ func TestClearEmptiesTheMessageTable(t *testing.T) {
func TestTheMessageFilterNarrowsTheTableWithoutLosingTheEvents(t *testing.T) {
model := sized(t, newTestModel(t), 120, 30)
- _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
- runCmd(t, model, cmd)
+ // A mix of tags, so a filter has something to exclude. A browse is a single message now,
+ // so it cannot supply the variety on its own.
+ for _, address := range []string{"temp/1", "press/1", "temp/2", "flow/1"} {
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " " + address})
+ runCmd(t, model, cmd)
+ }
_, total := model.EventCount()
require.Greater(t, total, 1)
diff --git a/plc4go/tools/plc4xbrowser/browser/mouse_test.go b/plc4go/tools/plc4xbrowser/browser/mouse_test.go
index 099e77e0..5553157b 100644
--- a/plc4go/tools/plc4xbrowser/browser/mouse_test.go
+++ b/plc4go/tools/plc4xbrowser/browser/mouse_test.go
@@ -84,10 +84,13 @@ func TestClickingOutsideThePanesReturnsToThePrompt(t *testing.T) {
// TestClickingAMessageRowSelectsIt covers the click-to-select the old lists provided.
func TestClickingAMessageRowSelectsIt(t *testing.T) {
model := sized(t, newTestModel(t), 120, 30)
- _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
- runCmd(t, model, cmd)
+ // Several separate reads: a browse is one message, so it would give only one row.
+ for range 5 {
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " temp/1"})
+ runCmd(t, model, cmd)
+ }
shown, _ := model.EventCount()
- require.Greater(t, shown, 2, "the demo catalogue should give us several rows")
+ require.Greater(t, shown, 2, "several reads should give several rows")
region, ok := model.regionFor(paneMessages)
require.True(t, ok)
@@ -138,8 +141,11 @@ func TestTheWheelScrollsThePaneUnderThePointerWithoutTakingFocus(t *testing.T) {
func TestTheWheelMovesTheMessageCursor(t *testing.T) {
model := sized(t, newTestModel(t), 120, 30)
- _, cmd := model.Update(tui.PromptSubmitMsg{Line: "browse-direct " + plcsession.DemoDeviceOne})
- runCmd(t, model, cmd)
+ // Several separate reads: a browse is one message now, so it gives nothing to scroll.
+ for range 5 {
+ _, cmd := model.Update(tui.PromptSubmitMsg{Line: "read-direct " + plcsession.DemoDeviceOne + " temp/1"})
+ runCmd(t, model, cmd)
+ }
region, ok := model.regionFor(paneMessages)
require.True(t, ok)
diff --git a/plc4go/tools/plc4xbrowser/browser/view.go b/plc4go/tools/plc4xbrowser/browser/view.go
index a13db442..82bf63e2 100644
--- a/plc4go/tools/plc4xbrowser/browser/view.go
+++ b/plc4go/tools/plc4xbrowser/browser/view.go
@@ -120,6 +120,11 @@ func (m *Model) renderStatus(width int) string {
if shown != total {
counts += fmt.Sprintf(" (%d shown)", shown)
}
+ // A count of messages says nothing about whether any of them failed, which is the one
+ // number worth glancing at.
+ if failed := m.FailedCount(); failed > 0 {
+ counts += " " + glyphs.Separator + " " + theme.Err.Render(strconv.Itoa(failed)+" failed")
+ }
logLevel := m.options.Config.LogLevel
if logLevel == "" {
logLevel = "info"
@@ -240,6 +245,20 @@ func (m *Model) renderSidebarPane(width, height int) string {
}
}
+ // The pane had eleven blank rows at the reference size with one connection and one driver.
+ // The last browse goes there as a catalogue you can refer back to while reading individual
+ // tags -- not the selected message's tags, which the detail pane is already showing.
+ if len(m.catalogue) > 0 {
+ lines = append(lines, "", theme.Key.Render("TAGS "+m.catalogueConnection))
+ for _, tag := range m.catalogue {
+ label := " " + tag.Address
+ if tag.DataType != "" {
+ label += " " + theme.Muted.Render(tag.DataType)
+ }
+ lines = append(lines, fitInline(label, inner))
+ }
+ }
+
status := strconv.Itoa(len(m.options.Session.Connections()))
pane := tui.Pane{
Title: paneTitle(paneSidebar),
@@ -411,13 +430,28 @@ func renderEventDetail(theme tui.Theme, event plcsession.Event) string {
glyphs := theme.Glyphs
var lines []string
+ // The header carries the operation and the connection. The old body then repeated both in
+ // a summary line that the log pane already showed verbatim, so three places said the same
+ // thing and none of them said anything new.
header := theme.Value.Render(string(event.Kind))
if event.Connection != "" {
header += " " + theme.Muted.Render(event.Connection)
}
lines = append(lines, header)
- lines = append(lines, theme.Muted.Render("received "+event.Received.Format("15:04:05.000")))
- if event.Summary != "" {
+
+ timing := event.Received.Format("15:04:05.000")
+ if !event.Started.IsZero() {
+ if took := event.Received.Sub(event.Started); took > 0 {
+ timing += " " + glyphs.Separator + " " + took.String()
+ }
+ }
+ if len(event.Tags) > 0 {
+ timing += " " + glyphs.Separator + " " + strconv.Itoa(len(event.Tags)) + " tags"
+ }
+ lines = append(lines, theme.Muted.Render(timing))
+
+ // A summary only when it adds something the tags do not, which for a browse is nothing.
+ if event.Summary != "" && len(event.Tags) == 0 {
lines = append(lines, "", theme.Muted.Render(event.Summary))
}
@@ -440,6 +474,7 @@ func renderEventDetail(theme tui.Theme, event plcsession.Event) string {
}
lines = append(lines, line)
}
+ lines = append(lines, "", theme.Muted.Render("r read "+glyphs.Separator+" w write "+glyphs.Separator+" s subscribe "+glyphs.Separator+" y yank"))
}
return strings.Join(lines, "\n")
}