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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions desktop/internal/core/output_style.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package core

import (
"context"
"encoding/json"
)

// OutputColor is one colour of a styled output range: a palette entry
// (0-15 follow the theme, 16-255 the xterm cube and grey ramp) or a
// "#rrggbb" colour.
type OutputColor struct {
Index *int `json:"index,omitempty"`
RGB string `json:"rgb,omitempty"`
}

// OutputStyle is how a range of console output is drawn. Unset colours are the
// console's own.
type OutputStyle struct {
Foreground *OutputColor `json:"foreground,omitempty"`
Background *OutputColor `json:"background,omitempty"`
Bold bool `json:"bold,omitempty"`
Dim bool `json:"dim,omitempty"`
Italic bool `json:"italic,omitempty"`
Underline bool `json:"underline,omitempty"`
Inverse bool `json:"inverse,omitempty"`
Hidden bool `json:"hidden,omitempty"`
Strikethrough bool `json:"strikethrough,omitempty"`
}

// OutputSpan styles Length UTF-16 code units of a line from Start. Spans are
// ascending and never overlap; text outside every span is plain.
type OutputSpan struct {
Start int `json:"start"`
Length int `json:"length"`
Style OutputStyle `json:"style"`
}

// OutputLine is one line of console output with its escapes removed.
type OutputLine struct {
Text string `json:"text"`
Spans []OutputSpan `json:"spans,omitempty"`
}

// OutputStyleDecoding is Core's answer for one chunk of console output.
type OutputStyleDecoding struct {
// Lines are the lines the chunk finished, oldest first; the first one
// continues the previous answer's Open line.
Lines []OutputLine
// Open is the line still being written, shown after Lines.
Open OutputLine
// State is passed back unchanged with the console's next chunk.
State json.RawMessage
}

// DecodeOutputStyle turns one chunk of console output with ANSI escapes into
// plain lines and styled ranges. state is the State of the previous answer for
// the same console, or nil for its first chunk; chunks are at most 1 MiB.
func (c *Client) DecodeOutputStyle(ctx context.Context, text string, state json.RawMessage) (OutputStyleDecoding, error) {
request := struct {
Text string `json:"text"`
State json.RawMessage `json:"state,omitempty"`
}{Text: text, State: state}
var response struct {
Lines []OutputLine `json:"lines"`
State json.RawMessage `json:"state"`
}
if err := c.Execute(ctx, "outputStyle.decode", request, &response); err != nil {
return OutputStyleDecoding{}, err
}
var open struct {
Line OutputLine `json:"line"`
}
if err := json.Unmarshal(response.State, &open); err != nil {
return OutputStyleDecoding{}, err
}
return OutputStyleDecoding{Lines: response.Lines, Open: open.Line, State: response.State}, nil
}
78 changes: 78 additions & 0 deletions desktop/internal/core/output_style_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package core

import (
"context"
"encoding/json"
"os"
"reflect"
"testing"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture"
)

// TestDecodeOutputStyleFollowsTheCoreFixture replays every case of the shared
// fixture through the client, passing each answer's state to the next chunk:
// Core decides the text and ranges, the client only carries them.
func TestDecodeOutputStyleFollowsTheCoreFixture(t *testing.T) {
data, err := os.ReadFile(contractfixture.CoreFixture("terminal/output-style-v1.json"))
if err != nil {
t.Fatal(err)
}
var fixture struct {
Cases []struct {
Name string `json:"name"`
Chunks []string `json:"chunks"`
Lines []OutputLine `json:"lines"`
Open OutputLine `json:"open"`
} `json:"cases"`
}
if err := json.Unmarshal(data, &fixture); err != nil {
t.Fatal(err)
}
if len(fixture.Cases) == 0 {
t.Fatal("the fixture has no cases")
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
client := NewClient()
for _, test := range fixture.Cases {
t.Run(test.Name, func(t *testing.T) {
var state json.RawMessage
lines := []OutputLine{}
var open OutputLine
for _, chunk := range test.Chunks {
decoded, err := client.DecodeOutputStyle(ctx, chunk, state)
if err != nil {
t.Fatal(err)
}
lines = append(lines, decoded.Lines...)
open, state = decoded.Open, decoded.State
}
want := test.Lines
if want == nil {
want = []OutputLine{}
}
if !reflect.DeepEqual(lines, want) {
got, _ := json.Marshal(lines)
expected, _ := json.Marshal(want)
t.Fatalf("lines = %s, want %s", got, expected)
}
if !reflect.DeepEqual(open, test.Open) {
got, _ := json.Marshal(open)
expected, _ := json.Marshal(test.Open)
t.Fatalf("open = %s, want %s", got, expected)
}
})
}
}

// TestDecodeOutputStyleRejectsAForeignState: a state Core never returned is an
// invalid request, so a console cannot carry another console's or a stale state.
func TestDecodeOutputStyleRejectsAForeignState(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := NewClient().DecodeOutputStyle(ctx, "x", json.RawMessage(`{"line":{"text":"ab","spans":[{"start":1,"length":5,"style":{"bold":true}}]}}`)); err == nil {
t.Fatal("a state whose range runs past its line was accepted")
}
}
24 changes: 24 additions & 0 deletions desktop/internal/i18n/i18n_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,27 @@ func TestParseRoundTrips(t *testing.T) {
t.Error("Parse accepts an unsupported code")
}
}

// A run's duration is milliseconds under a second, then seconds and milliseconds, then minutes
// and seconds, then hours and minutes; a clock that steps back reads as no time.
func TestRunDurationPicksTheLargestTwoUnits(t *testing.T) {
for _, test := range []struct {
language Language
milliseconds int
want string
}{
{English, -5, "0 ms"},
{English, 999, "999 ms"},
{English, 1632, "1 s 632 ms"},
{English, 61_000, "1 min 1 s"},
{English, 3_725_000, "1 h 2 min"},
{Chinese, 999, "999毫秒"},
{Chinese, 1632, "1秒632毫秒"},
{Chinese, 61_000, "1分1秒"},
{Chinese, 3_725_000, "1小时2分"},
} {
if got := For(test.language).Run.Duration(test.milliseconds); got != test.want {
t.Errorf("language %s, %d ms: duration %q, want %q", test.language.Code(), test.milliseconds, got, test.want)
}
}
}
53 changes: 48 additions & 5 deletions desktop/internal/i18n/run_messages.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
package i18n

import "strconv"
import (
"strconv"
"time"
)

// RunMessages are the words of the plugin-started run entries shown beside the
// build output.
// RunMessages are the words of the Run tool window: its execution tabs, tree and console.
type RunMessages struct {
Build string
Rerun string
Ended string
LinkMissing string
LinkUnresolved string
// CloseSession closes the tab of a finished execution; Empty is the window before anything ran.
CloseSession string
Empty string
// Running, Succeeded, Failed and Stopped name where an execution stands, beside its icon.
Running, Succeeded, Failed, Stopped string
// Snapshot words the output snapshot of a run (run_snapshot_messages.go).
Snapshot RunSnapshotMessages
// Performance words the CPU and memory readings of a run (run_performance_messages.go).
Expand All @@ -18,15 +24,25 @@ type RunMessages struct {
Exited func(code int) string
// Signalled reports a process ended by a signal.
Signalled func(signal string) string
// StartedAt follows an execution's name in the tree with when it started, already formatted.
StartedAt func(time string) string
// Duration is how long an execution took, given in milliseconds: seconds and milliseconds
// under a minute, then minutes and seconds, then hours and minutes.
Duration func(milliseconds int) string
}

func runMessages(language Language) RunMessages {
return RunMessages{
Build: Shared(language, "desktop.run.build"),
Rerun: Shared(language, "desktop.run.rerun"),
Ended: Shared(language, "desktop.run.ended"),
LinkMissing: Shared(language, "desktop.run.linkMissing"),
LinkUnresolved: Shared(language, "desktop.run.linkUnresolved"),
CloseSession: Shared(language, "desktop.run.closeSession"),
Empty: Shared(language, "desktop.run.empty"),
Running: Shared(language, "desktop.run.statusRunning"),
Succeeded: Shared(language, "desktop.run.statusSucceeded"),
Failed: Shared(language, "desktop.run.statusFailed"),
Stopped: Shared(language, "desktop.run.statusStopped"),
Snapshot: runSnapshotMessages(language),
Performance: runPerformanceMessages(language),
Exited: func(code int) string {
Expand All @@ -35,5 +51,32 @@ func runMessages(language Language) RunMessages {
Signalled: func(signal string) string {
return SharedFormat(language, "desktop.run.signalled", map[string]string{"signal": signal})
},
StartedAt: func(time string) string {
return SharedFormat(language, "desktop.run.startedAt", map[string]string{"time": time})
},
Duration: func(milliseconds int) string {
return runDuration(language, time.Duration(milliseconds)*time.Millisecond)
},
}
}

func runDuration(language Language, elapsed time.Duration) string {
elapsed = max(elapsed, 0)
count := func(value time.Duration) string { return strconv.FormatInt(int64(value), 10) }
switch {
case elapsed < time.Second:
return SharedFormat(language, "desktop.run.durationMilliseconds", map[string]string{"milliseconds": count(elapsed / time.Millisecond)})
case elapsed < time.Minute:
return SharedFormat(language, "desktop.run.durationSeconds", map[string]string{
"seconds": count(elapsed / time.Second), "milliseconds": count(elapsed % time.Second / time.Millisecond),
})
case elapsed < time.Hour:
return SharedFormat(language, "desktop.run.durationMinutes", map[string]string{
"minutes": count(elapsed / time.Minute), "seconds": count(elapsed % time.Minute / time.Second),
})
default:
return SharedFormat(language, "desktop.run.durationHours", map[string]string{
"hours": count(elapsed / time.Hour), "minutes": count(elapsed % time.Hour / time.Minute),
})
}
}
26 changes: 24 additions & 2 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions desktop/internal/termview/palette.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ func newPalette(look Look, epoch uint32) palette {
return pal
}

// ANSI is the 16 ANSI colors the terminal draws with in look, for consoles outside the terminal
// view that color their output the same way.
func (look Look) ANSI() [16][3]uint8 {
return newPalette(look, 0).ansi
}

// nativeContrast is the least contrast, by WCAG 2's ratio, a color of the system terminal's
// profile needs against the background to replace the built-in one: the AA level for text.
const nativeContrast = 4.5
Expand Down
1 change: 1 addition & 0 deletions desktop/internal/workbench/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ type Kernel interface {
processExitKernel
processMemoryKernel
MatchOutputLinks(context.Context, core.OutputLinkRequest) ([]core.OutputLink, error)
DecodeOutputStyle(ctx context.Context, text string, state json.RawMessage) (core.OutputStyleDecoding, error)
CreateDebugSession(ctx context.Context, request core.DebugCreateSessionRequest) (core.DebugUpdate, error)
LaunchDebug(ctx context.Context, sessionID, operationID string, configuration core.DebugLaunchConfiguration) (core.DebugUpdate, error)
NormalizeSteppingFilters(ctx context.Context, adapterID string, filters core.DebugSteppingFilters) (core.DebugSteppingFilters, error)
Expand Down
Loading
Loading