Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for SIGWINCH #15

Merged
merged 2 commits into from
Dec 8, 2022
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
3 changes: 3 additions & 0 deletions Demos/Sharpie.Demos.Slk/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Sharpie;
using Sharpie.Backend;

Expand Down Expand Up @@ -36,13 +37,15 @@ void DrawHeader()
DrawHeader();
terminal.SoftLabelKeys.Refresh(true);


// Run the main loop.
await terminal.RunAsync(@event =>
{
switch (@event)
{
case TerminalResizeEvent:
DrawHeader();
terminal.SoftLabelKeys.Refresh(true);
break;
case KeyEvent { Key: Key.Character, Char.Value: var k and >= '1' and <= '8' }:
{
Expand Down
81 changes: 71 additions & 10 deletions Sharpie.Tests/EventPumpTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

namespace Sharpie.Tests;

using Nito.Disposables;

[TestClass]
public class EventPumpTests
{
Expand Down Expand Up @@ -64,6 +66,7 @@ private Event[] SimulateEvents(int count, ISurface w, params (int result, uint k
});

var events = new List<Event>();

foreach (var e in _pump.Listen(w, _source.Token))
{
count--;
Expand Down Expand Up @@ -357,9 +360,58 @@ public void Listen1_SkipsBadReads()
}

[TestMethod]
public void Listen1_ApplyPendingRefreshes_WhenReadFails()
public void Listen1_CallsUpdate_WhenNoEventAndNoResizeMonitoring()
{
SimulateEvents(1, _window, (-1, 0), (0, 0));
_cursesMock.Verify(v => v.doupdate(), Times.Once);
}

[TestMethod]
public void Listen1_TriesToSetupResizeMonitoring()
{
var disposed = false;
_cursesMock.Setup(s => s.monitor_pending_resize(It.IsAny<Action>(), out It.Ref<IDisposable?>.IsAny))
.Returns((Action action, out IDisposable? handle) =>
{
action.ShouldNotBeNull();
handle = new Disposable(() => { disposed = true; });
return true;
});

SimulateEvents(1, _window, (-1, 0), (0, 0));

disposed.ShouldBeTrue();
}

[TestMethod]
public void Listen1_DoesNotCallUpdate_WhenNoEventAndMonitoringResize()
{
_cursesMock.Setup(s => s.monitor_pending_resize(It.IsAny<Action>(), out It.Ref<IDisposable?>.IsAny))
.Returns((Action _, out IDisposable? handle) =>
{
handle = new Disposable(null);
return true;
});

var events = SimulateEvents(1, _window, (-1, 0), (0, 0));
events[0].Type.ShouldBe(EventType.KeyPress);
_cursesMock.Verify(v => v.doupdate(), Times.Never);
}

[TestMethod]
public void Listen1_CallsUpdate_WhenMonitoringResizeTriggers()
{
_cursesMock.Setup(s => s.monitor_pending_resize(It.IsAny<Action>(), out It.Ref<IDisposable?>.IsAny))
.Returns((Action act, out IDisposable? handle) =>
{
handle = new Disposable(null);
act();
return true;
});

var events = SimulateEvents(2, _window, (-1, 0), (-1, 0), (-1, 0), (0, 0));
events[0].Type.ShouldBe(EventType.TerminalAboutToResize);
events[1].Type.ShouldBe(EventType.KeyPress);
_cursesMock.Verify(v => v.doupdate(), Times.Once);
}

Expand All @@ -374,7 +426,7 @@ public void Listen1_GoesDeepWithinChildren_ToApplyPendingRefreshes()
}

[TestMethod]
public void Listen1_ProcessesTerminalResizeEvents_InScreen()
public void Listen1_ProcessesTerminalResizeEvents_InScreen_WithoutMonitoring()
{
_window.Dispose();

Expand All @@ -384,18 +436,21 @@ public void Listen1_ProcessesTerminalResizeEvents_InScreen()
_cursesMock.Setup(s => s.getmaxx(_terminal.Screen.Handle))
.Returns(20);

var @event = SimulateEvent(_terminal.Screen, (int) CursesKey.Yes, (uint) CursesKey.Resize);

@event.Type.ShouldBe(EventType.TerminalResize);
((TerminalResizeEvent) @event).Size.ShouldBe(new(20, 10));
var events = SimulateEvents(2, _terminal.Screen, ((int) CursesKey.Yes, (uint) CursesKey.Resize));

events.Length.ShouldBe(2);
events[0].Type.ShouldBe(EventType.TerminalAboutToResize);

events[1].Type.ShouldBe(EventType.TerminalResize);
((TerminalResizeEvent) events[1]).Size.ShouldBe(new(20, 10));

_cursesMock.Verify(v => v.wtouchln(_terminal.Screen.Handle, 0, 10, 1), Times.Once);
_cursesMock.Verify(v => v.clearok(_terminal.Screen.Handle, It.IsAny<bool>()), Times.Never);
_cursesMock.Verify(v => v.wrefresh(_terminal.Screen.Handle), Times.Once);
}

[TestMethod]
public void Listen1_ProcessesTerminalResizeEvents_InChild()
public void Listen1_ProcessesTerminalResizeEvents_InChild_WithoutMonitoring()
{
var otherWindow = new Window((Screen)_terminal.Screen, new(8));

Expand All @@ -411,9 +466,13 @@ public void Listen1_ProcessesTerminalResizeEvents_InChild()
_cursesMock.Setup(s => s.getmaxy(otherWindow.Handle))
.Returns(5);

var e = SimulateEvent((int) CursesKey.Yes, (uint) CursesKey.Resize);
e.Type.ShouldBe(EventType.TerminalResize);
((TerminalResizeEvent) e).Size.ShouldBe(new(20, 10));
var events = SimulateEvents(2, otherWindow, ((int) CursesKey.Yes, (uint) CursesKey.Resize));

events.Length.ShouldBe(2);
events[0].Type.ShouldBe(EventType.TerminalAboutToResize);

events[1].Type.ShouldBe(EventType.TerminalResize);
((TerminalResizeEvent) events[1]).Size.ShouldBe(new(20, 10));

_cursesMock.Verify(v => v.wtouchln(_terminal.Screen.Handle, It.IsAny<int>(), It.IsAny<int>(), 1), Times.Once);
_cursesMock.Verify(v => v.wtouchln(_window.Handle, It.IsAny<int>(), It.IsAny<int>(), 1), Times.Once);
Expand All @@ -423,6 +482,8 @@ public void Listen1_ProcessesTerminalResizeEvents_InChild()
_cursesMock.Verify(v => v.wrefresh(_terminal.Screen.Handle), Times.Once);
}



[TestMethod]
public void Listen1_SkipsInvalidMouseEvents()
{
Expand Down
71 changes: 71 additions & 0 deletions Sharpie.Tests/TerminalAboutToResizeEventTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
Copyright (c) 2022, Alexandru Ciobanu
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

namespace Sharpie.Tests;

[TestClass]
public class TerminalAboutToResizeEventTests
{
private readonly TerminalAboutToResizeEvent _event1 = new();

[TestMethod]
public void Ctr_InitializesPropertiesCorrectly()
{
_event1.Type.ShouldBe(EventType.TerminalAboutToResize);
}

[TestMethod]
public void ToString_ProperlyFormats()
{
_event1.ToString()
.ShouldBe("Resizing");
}

[TestMethod, DataRow(null), DataRow("")]
public void Equals_ReturnsFalse_IfNotSameType(object? b)
{
_event1.Equals(b)
.ShouldBeFalse();
}

[TestMethod]
public void Equals_ReturnsTrue_IfSameType()
{
_event1.Equals(new TerminalAboutToResizeEvent())
.ShouldBeTrue();
}

[TestMethod]
public void GetHashCode_IsEqual_Always()
{
_event1.GetHashCode()
.ShouldBe(new TerminalAboutToResizeEvent().GetHashCode());
}
}
2 changes: 2 additions & 0 deletions Sharpie/Abstractions/ICursesProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -444,4 +444,6 @@ int wborder_set(IntPtr window, CursesComplexChar leftSide, CursesComplexChar rig
void set_title(string title);

void set_unicode_locale();

bool monitor_pending_resize(Action action, [NotNullWhen(true)] out IDisposable? handle);
}
48 changes: 45 additions & 3 deletions Sharpie/Backend/NativeCursesProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,20 @@ namespace Sharpie.Backend;
/// implementation.
/// </summary>
[PublicAPI, SuppressMessage("ReSharper", "IdentifierTypo"), ExcludeFromCodeCoverage]
public sealed class NativeCursesProvider: ICursesProvider
public sealed class NativeCursesProvider: ICursesProvider, IDisposable
{
private const string CursesLibraryName = "ncurses";
private const string LibCLibraryName = "libc";

private static readonly ICursesProvider? LazyInstance = new NativeCursesProvider().ValidOrNull();

private int _resizePending;
private PosixSignalRegistration? _signalRegistration;

private NativeCursesProvider()
{
}

/// <summary>
/// Returns the instance of the Curses backend.
/// </summary>
Expand Down Expand Up @@ -517,10 +524,29 @@ bool ICursesProvider.wmouse_trafo(IntPtr window, ref int line, ref int col, bool

void ICursesProvider.set_unicode_locale()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
if (OperatingSystem.IsLinux() || OperatingSystem.IsFreeBSD())
{
setlocale(6, "");
} else if (OperatingSystem.IsMacOS())
{
setlocale(RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? 0 : 6, "");
setlocale(0, "");
}
}

bool ICursesProvider.monitor_pending_resize(Action action, [NotNullWhen(true)] out IDisposable? handle)
{
if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD())
{
handle = PosixSignalRegistration.Create(PosixSignal.SIGWINCH, _ =>
{
action();
});

return true;
}

handle = null;
return false;
}

[DllImport(CursesLibraryName, CallingConvention = CallingConvention.Cdecl)]
Expand Down Expand Up @@ -1132,4 +1158,20 @@ private static extern int wgetn_wstr(IntPtr window, [MarshalAs(UnmanagedType.LPW

[DllImport(LibCLibraryName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int setlocale(int cate, string locale);

public void Dispose()
{
if (_signalRegistration != null)
{
_signalRegistration?.Dispose();
_signalRegistration = null;
}

GC.SuppressFinalize(this);
}

~NativeCursesProvider()
{
Dispose();
}
}
25 changes: 24 additions & 1 deletion Sharpie/EventPump.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ internal bool UseInternalMouseEventResolver
var (result, keyCode) = ReadNext(windowHandle, quickWait);
if (result.Failed())
{
_terminal.Update();
return null;
}

Expand Down Expand Up @@ -97,11 +96,28 @@ public IEnumerable<Event> Listen(ISurface surface, CancellationToken cancellatio
throw new ArgumentNullException(nameof(surface));
}

var hasPendingResize = false;
var monitorsResizes = _terminal.Curses.monitor_pending_resize(() =>
{
hasPendingResize = true;
}, out var monitorHandle);

var escapeSequence = new List<KeyEvent>();

while (!cancellationToken.IsCancellationRequested)
{
var @event = ReadNextEvent(surface.Handle, escapeSequence.Count > 0);
if (!monitorsResizes && @event == null || hasPendingResize)
{
if (hasPendingResize)
{
@event = new TerminalAboutToResizeEvent();
}

_terminal.Update();
hasPendingResize = false;
}

if (@event is KeyEvent ke)
{
escapeSequence.Add(ke);
Expand Down Expand Up @@ -159,6 +175,11 @@ public IEnumerable<Event> Listen(ISurface surface, CancellationToken cancellatio
// Flush the event if anything in there.
if (@event is not null)
{
if (@event.Type == EventType.TerminalResize && !monitorsResizes)
{
yield return new TerminalAboutToResizeEvent();
}

yield return @event;

if (@event.Type == EventType.TerminalResize)
Expand All @@ -167,6 +188,8 @@ public IEnumerable<Event> Listen(ISurface surface, CancellationToken cancellatio
}
}
}

monitorHandle?.Dispose();
}

/// <inheritdoc cref="IEventPump.Listen(System.Threading.CancellationToken)"/>
Expand Down
5 changes: 5 additions & 0 deletions Sharpie/EventType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ public enum EventType
/// The terminal has been resized.
/// </summary>
TerminalResize,

/// <summary>
/// The terminal is about to be resized.
/// </summary>
TerminalAboutToResize,

/// <summary>
/// A key has been pressed.
Expand Down
Loading