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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,27 @@ terminal.PointerShapeChanged += (sender, e) =>
};
```

**Shell state** (OSC 133 shell integration). `terminal.ShellState` says where the shell is:
`Unknown` (no marks yet, or a shell without integration), `Prompt` (after `133;A`, or after
`133;D` ends a command), `Input` (after `133;B`) or `Running` (after `133;C`). Each mark sets the
state outright, so a lost `D` is repaired by the next prompt's `A`; a full reset (RIS) returns it
to `Unknown`, and the alternate screen does not affect it. `ShellStateChanged` fires only when the
value changes, with the exit code of the `133;D` that ended a command:

```csharp
// Ask before closing only while a command is running.
bool confirmClose = terminal.ShellState == ShellState.Running;

terminal.ShellStateChanged += (sender, e) =>
{
if (e.OldState == ShellState.Running)
Console.WriteLine($"Command finished, exit code {e.ExitCode?.ToString() ?? "not reported"}");
};
```

`LastCommandExitCode` holds the last reported exit code; `ShellIntegrationState` and
`ShellIntegrationMarkReceived` give the raw marks.

**Window manipulation events** (used by some terminal applications):

```csharp
Expand Down
255 changes: 255 additions & 0 deletions src/XTerm.NET.Tests/ShellIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,261 @@ public void Osc133_IgnoresEmptyPayload()
Assert.Null(terminal.ShellIntegrationState);
}

// ---- OSC 133 : derived shell state -------------------------------------------------------

private static List<(ShellState Old, ShellState New, int? Exit)> RecordShellStates(Terminal terminal)
{
var changes = new List<(ShellState, ShellState, int?)>();
terminal.ShellStateChanged += (_, e) => changes.Add((e.OldState, e.NewState, e.ExitCode));
return changes;
}

[Fact]
public void ShellState_IsUnknownBeforeAnyMark()
{
var terminal = CreateTerminal();

Assert.Equal(ShellState.Unknown, terminal.ShellState);
}

[Theory]
[InlineData("A", ShellState.Prompt)]
[InlineData("B", ShellState.Input)]
[InlineData("C", ShellState.Running)]
[InlineData("D;0", ShellState.Prompt)]
public void ShellState_FollowsEachMark(string mark, ShellState expected)
{
var terminal = CreateTerminal();
var changes = RecordShellStates(terminal);

terminal.Write($"\x1B]133;{mark}\x07");

Assert.Equal(expected, terminal.ShellState);
Assert.Equal(new[] { (ShellState.Unknown, expected, mark == "D;0" ? 0 : (int?)null) }, changes);
}

[Fact]
public void ShellState_TracksAFullCycle_AndReportsTheExitCodeOnlyWhenTheCommandEnds()
{
var terminal = CreateTerminal();
var changes = RecordShellStates(terminal);

terminal.Write("\x1B]133;A\x07$ \x1B]133;B\x07");
Assert.Equal(ShellState.Input, terminal.ShellState);

terminal.Write("make\r\n\x1B]133;C\x07");
Assert.Equal(ShellState.Running, terminal.ShellState);

terminal.Write("error\r\n\x1B]133;D;2\x07");
Assert.Equal(ShellState.Prompt, terminal.ShellState);
Assert.Equal(2, terminal.LastCommandExitCode);

// The next prompt's A leaves the state where D put it, so it raises nothing.
terminal.Write("\x1B]133;A\x07");

Assert.Equal(
new (ShellState, ShellState, int?)[]
{
(ShellState.Unknown, ShellState.Prompt, null),
(ShellState.Prompt, ShellState.Input, null),
(ShellState.Input, ShellState.Running, null),
(ShellState.Running, ShellState.Prompt, 2),
},
changes);
}

[Fact]
public void ShellState_ReportsNoExitCode_ForABareD()
{
// cmd.exe always sends a bare D. Null must not read as success.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.Write("\x1B]133;D\x07");

Assert.Equal(new[] { (ShellState.Running, ShellState.Prompt, (int?)null) }, changes);
}

[Fact]
public void ShellState_RepeatedMarksRaiseNothing()
{
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.Write("\x1B]133;C\x07\x1B]133;C\x07");

Assert.Equal(ShellState.Running, terminal.ShellState);
Assert.Empty(changes);
}

[Fact]
public void ShellState_FullReset_ReturnsToUnknown()
{
// RIS while a command runs is what `reset` itself produces: the state goes to Unknown, and
// the D that follows when `reset` exits brings it back to Prompt.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.Write("\u001bc");
Assert.Equal(ShellState.Unknown, terminal.ShellState);

terminal.Write("\x1B]133;D;0\x07");
Assert.Equal(ShellState.Prompt, terminal.ShellState);

Assert.Equal(
new (ShellState, ShellState, int?)[]
{
(ShellState.Running, ShellState.Unknown, null),
(ShellState.Unknown, ShellState.Prompt, 0),
},
changes);
}

[Fact]
public void ShellState_FullResetWithNoState_RaisesNothing()
{
var terminal = CreateTerminal();
var changes = RecordShellStates(terminal);

terminal.Write("\u001bc");

Assert.Empty(changes);
}

[Fact]
public void ResetShellState_ForgetsTheStateAndNothingElse()
{
// A host connecting the terminal to a new process: the old shell's state must go, its screen
// must not.
var terminal = CreateTerminal();
terminal.Write("old output\r\n\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.ResetShellState();

Assert.Equal(ShellState.Unknown, terminal.ShellState);
Assert.Equal(new[] { (ShellState.Running, ShellState.Unknown, (int?)null) }, changes);
Assert.StartsWith("old output", terminal.Buffer.Lines[0]!.TranslateToString(true));

// And the next shell's marks are heard from scratch, even a B the old shell had also sent last.
terminal.ResetShellState();
terminal.Write("\x1B]133;B\x07");
Assert.Equal(ShellState.Input, terminal.ShellState);
Assert.Equal(2, changes.Count);
}

[Fact]
public void ShellState_SoftResetLeavesItAlone()
{
// DECSTR resets modes for the program that asked; it says nothing about the shell.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");

terminal.Write("\x1B[!p");

Assert.Equal(ShellState.Running, terminal.ShellState);
}

[Fact]
public void ShellState_RecoversFromAMissingD_AtTheNextPrompt()
{
// The shell crashed mid-command, or the command was killed before D: a new prompt's A is
// evidence enough that nothing is running any more.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;D;5\x07\x1B]133;A\x07\x1B]133;B\x07\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.Write("\x1B]133;A\x07");

Assert.Equal(ShellState.Prompt, terminal.ShellState);
Assert.Equal(new[] { (ShellState.Running, ShellState.Prompt, (int?)null) }, changes);
// The last exit code is still the last one REPORTED; a missing D reports nothing.
Assert.Equal(5, terminal.LastCommandExitCode);
}

[Fact]
public void ShellState_FollowsTheLatestMark_WhenMarksArriveOutOfOrder()
{
var terminal = CreateTerminal();

// C with no A or B before it: a shell whose integration starts mid-session.
terminal.Write("\x1B]133;C\x07");
Assert.Equal(ShellState.Running, terminal.ShellState);

// B with no A after a D: the prompt mark was dropped.
terminal.Write("\x1B]133;D\x07\x1B]133;B\x07");
Assert.Equal(ShellState.Input, terminal.ShellState);

// A while waiting for input: the prompt was redrawn (Ctrl+C, a resize).
terminal.Write("\x1B]133;A\x07");
Assert.Equal(ShellState.Prompt, terminal.ShellState);
}

[Fact]
public void ShellState_FollowsTheInnerShell_WhenShellsNest()
{
// `bash` run from bash: the outer shell's C, then the inner shell's own cycle, then the
// outer shell's D when the inner one exits. The terminal follows whoever spoke last.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;A\x07\x1B]133;B\x07\x1B]133;C\x07");

terminal.Write("\x1B]133;A\x07\x1B]133;B\x07");
Assert.Equal(ShellState.Input, terminal.ShellState);

terminal.Write("\x1B]133;C\x07");
Assert.Equal(ShellState.Running, terminal.ShellState);

terminal.Write("\x1B]133;D;0\x07\x1B]133;A\x07\x1B]133;B\x07");
Assert.Equal(ShellState.Input, terminal.ShellState);

// `exit` in the inner shell: the outer shell's D and its next prompt.
terminal.Write("\x1B]133;C\x07\x1B]133;D;0\x07\x1B]133;A\x07");
Assert.Equal(ShellState.Prompt, terminal.ShellState);
}

[Fact]
public void ShellState_IsUnchangedByTheAlternateScreen()
{
// vim takes the alternate screen inside a running command; neither switch is a shell mark.
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");
var changes = RecordShellStates(terminal);

terminal.Write("\x1B[?1049h");
Assert.Equal(ShellState.Running, terminal.ShellState);
terminal.Write("\x1B[2J~\x1B[?1049l");

Assert.Equal(ShellState.Running, terminal.ShellState);
Assert.Empty(changes);
}

[Fact]
public void ShellState_IgnoresUnknownMarks()
{
var terminal = CreateTerminal();
terminal.Write("\x1B]133;C\x07");

terminal.Write("\x1B]133;Z\x07\x1B]133\x07");

Assert.Equal(ShellState.Running, terminal.ShellState);
}

[Fact]
public void ShellState_IsCurrent_WhenTheMarkEventIsRaised()
{
// A handler of the raw mark event reading ShellState sees the state that mark produced.
var terminal = CreateTerminal();
ShellState? seen = null;
terminal.ShellIntegrationMarkReceived += (_, _) => seen = terminal.ShellState;

terminal.Write("\x1B]133;C\x07");

Assert.Equal(ShellState.Running, seen);
}

// ---- OSC 9 ; 9 : working directory -------------------------------------------------------

[Fact]
Expand Down
49 changes: 49 additions & 0 deletions src/XTerm.NET/Common/ShellState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace XTerm.Common;

/// <summary>
/// Where the shell is in its prompt/command cycle, as derived from its OSC 133 marks.
/// </summary>
/// <remarks>
/// <para>What <see cref="XTerm.Terminal.ShellState"/> reports, and the question a host asks before
/// closing a terminal: <see cref="Running"/> means a command owns the terminal and closing it would
/// kill that command; anything else means the shell itself has it.</para>
/// <para>The transitions, one per mark, with the latest mark always winning:</para>
/// <list type="bullet">
/// <item><c>133;A</c> (prompt start) - <see cref="Prompt"/>.</item>
/// <item><c>133;B</c> (input start) - <see cref="Input"/>.</item>
/// <item><c>133;C</c> (command start) - <see cref="Running"/>.</item>
/// <item><c>133;D</c> (command finished) - <see cref="Prompt"/>. The command is over and the shell has
/// the terminal back; what it does next is draw a prompt. Not <see cref="Unknown"/>, because the shell
/// has just told us exactly where it is.</item>
/// <item>RIS (<c>ESC c</c>) - <see cref="Unknown"/>. A full reset discards everything the terminal knew
/// about the session, and the shell has to say again.</item>
/// </list>
/// <para>Because each mark sets the state outright, a lost <c>133;D</c> - a shell that crashed and was
/// replaced, or a command killed before it could report - cannot leave the state stuck at
/// <see cref="Running"/>: the next prompt's <c>133;A</c> puts it back. The same rule covers nesting:
/// a shell started from another shell sends its own marks, and the terminal follows whichever shell
/// spoke last. Switching to and from the alternate screen changes nothing.</para>
/// </remarks>
public enum ShellState
{
/// <summary>
/// No mark since the terminal was created or last reset. Shell integration is configured in the
/// shell, so this is also the permanent state of a shell without it: "cannot say", never "idle".
/// </summary>
Unknown = 0,

/// <summary>
/// The shell is drawing its prompt (after <c>133;A</c>, or after <c>133;D</c> ended a command).
/// </summary>
Prompt = 1,

/// <summary>
/// The prompt is drawn and the shell is waiting for the user's command line (after <c>133;B</c>).
/// </summary>
Input = 2,

/// <summary>
/// A command is running and owns the terminal (after <c>133;C</c>, until the next mark).
/// </summary>
Running = 3,
}
26 changes: 26 additions & 0 deletions src/XTerm.NET/Events/TerminalEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -672,4 +672,30 @@ public CursorStyleChangedEventArgs(CursorStyle style, bool blink)
Blink = blink;
}
}

/// <summary>
/// Shell state changed event - fired when <see cref="Terminal.ShellState"/> takes a new value.
/// </summary>
public class ShellStateChangedEventArgs : EventArgs
{
public ShellStateChangedEventArgs(ShellState oldState, ShellState newState, int? exitCode)
{
OldState = oldState;
NewState = newState;
ExitCode = exitCode;
}

/// <summary>The state before the change.</summary>
public ShellState OldState { get; }

/// <summary>The state after the change, which <see cref="Terminal.ShellState"/> now reports.</summary>
public ShellState NewState { get; }

/// <summary>
/// The exit code the shell reported with the <c>133;D</c> that caused this change, or null when
/// something else caused it or the shell sent a bare D. Null means "not reported", never
/// "succeeded".
/// </summary>
public int? ExitCode { get; }
}
}
1 change: 1 addition & 0 deletions src/XTerm.NET/InputHandler.Osc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,7 @@ private void HandleShellIntegration(string data)
line?.AddMark(new Buffer.LineMark(_buffer.X, mark, exitCode));

_terminal.ShellIntegrationState = mark;
_terminal.SetShellState(Terminal.ShellStateAfter(mark), exitCode);
_terminal.RaiseShellIntegrationMark(mark, exitCode);
}

Expand Down
Loading
Loading