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

Advanced CLI #1344

Closed
wants to merge 2 commits into from
Closed
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
15 changes: 14 additions & 1 deletion LenovoLegionToolkit.CLI.Lib/IpcRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,18 @@

public class IpcRequest
{
public string Name { get; init; } = "";
public enum OperationType
{
QuickAction,
ListFeatures,
ListFeatureValues,
SetFeature,
GetFeature,
}

public OperationType? Operation { get; init; }

public string? Name { get; init; }

public string? Value { get; init; }
}
62 changes: 60 additions & 2 deletions LenovoLegionToolkit.CLI/IpcClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,64 @@ public static class IpcClient
{
private static bool PipeExists => Directory.GetFiles(@"\\.\pipe\", Constants.PIPE_NAME).Length > 0;

public static async Task RunQuickActionAsync(string name)
public static async Task<string> ListFeatures()
{
var req = new IpcRequest
{
Operation = IpcRequest.OperationType.ListFeatures,
};

return await SendRequestAsync(req).ConfigureAwait(false)
?? throw new IpcException("Missing return message.");
}
public static async Task<string> ListFeatureValues(string name)
{
var req = new IpcRequest
{
Operation = IpcRequest.OperationType.ListFeatureValues,
Name = name,
};

return await SendRequestAsync(req).ConfigureAwait(false)
?? throw new IpcException("Missing return message.");
}

public static Task SetFeature(string name, string value)
{
var req = new IpcRequest
{
Operation = IpcRequest.OperationType.SetFeature,
Name = name,
Value = value
};

return SendRequestAsync(req);
}

public static async Task<string> GetFeature(string name)
{
var req = new IpcRequest
{
Operation = IpcRequest.OperationType.GetFeature,
Name = name
};

return await SendRequestAsync(req).ConfigureAwait(false)
?? throw new IpcException("Missing return message.");
}

public static Task RunQuickActionAsync(string name)
{
var req = new IpcRequest
{
Operation = IpcRequest.OperationType.QuickAction,
Name = name
};

return SendRequestAsync(req);
}

private static async Task<string?> SendRequestAsync(IpcRequest req)
{
if (!PipeExists)
throw new IpcException("Server unavailable");
Expand All @@ -21,12 +78,13 @@ public static async Task RunQuickActionAsync(string name)

await ConnectAsync(pipe).ConfigureAwait(false);

var req = new IpcRequest { Name = name };
await pipe.WriteObjectAsync(req).ConfigureAwait(false);
var res = await pipe.ReadObjectAsync<IpcResponse>().ConfigureAwait(false);

if (res is null || !res.Success)
throw new IpcException(res?.Message ?? "Unknown failure");

return res.Message;
}

private static async Task ConnectAsync(NamedPipeClientStream pipe)
Expand Down
3 changes: 3 additions & 0 deletions LenovoLegionToolkit.CLI/LenovoLegionToolkit.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LenovoLegionToolkit.CLI.Lib\LenovoLegionToolkit.CLI.Lib.csproj" />
</ItemGroup>
Expand Down
107 changes: 66 additions & 41 deletions LenovoLegionToolkit.CLI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
using System;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Invocation;
using System.CommandLine.IO;
using System.CommandLine.Parsing;
using System.Threading.Tasks;
using LenovoLegionToolkit.CLI.Lib;

Expand All @@ -8,55 +13,75 @@ public class Program
{
public static async Task<int> Main(string[] args)
{
var flags = Flags.Create(args);
var root = new RootCommand("Control LLT");

try
{
if (flags.Help)
PrintHelp(flags);
else if (flags.QuickActionRunName is { } name)
await IpcClient.RunQuickActionAsync(name);
else
throw new InvalidOperationException();

return 0;
}
catch (IpcException ex)
var builder = new CommandLineBuilder(root)
.UseDefaults()
.UseExceptionHandler(OnException);

var quickActionNameArgument = new Argument<string>("name", "Name of the QuickAction") { Arity = ArgumentArity.ExactlyOne };
var featureArgument = new Argument<string>("feature", "Name of the feature") { Arity = ArgumentArity.ExactlyOne };
var valueArgument = new Argument<string>("value", "Value of the feature") { Arity = ArgumentArity.ExactlyOne };

var runQuickActionCommand = new Command("quick-action", "Run Quick Action with specified name");
runQuickActionCommand.AddAlias("qa");
runQuickActionCommand.AddArgument(quickActionNameArgument);
runQuickActionCommand.SetHandler(IpcClient.RunQuickActionAsync, quickActionNameArgument);
root.AddCommand(runQuickActionCommand);

var listFeaturesCommand = new Command("feature-list", "List supported features");
listFeaturesCommand.AddAlias("fl");
listFeaturesCommand.SetHandler(async _ =>
{
PrintLine(flags, ex.Message);
return 3;
}
catch (InvalidOperationException)
var value = await IpcClient.ListFeatures();
Console.WriteLine(value);
});
root.AddCommand(listFeaturesCommand);

var listFeatureValuesCommand = new Command("feature-list-values", "List values supported by a feature");
listFeatureValuesCommand.AddAlias("flv");
listFeatureValuesCommand.SetHandler(async name =>
{
PrintHelp(flags);
return 2;
}
catch (Exception ex)
var value = await IpcClient.ListFeatureValues(name);
Console.WriteLine(value);
}, featureArgument);
listFeatureValuesCommand.AddArgument(featureArgument);
root.AddCommand(listFeatureValuesCommand);

var setFeatureCommand = new Command("feature-set-value", "Set feature with value");
setFeatureCommand.AddAlias("fsv");
setFeatureCommand.AddArgument(featureArgument);
setFeatureCommand.AddArgument(valueArgument);
setFeatureCommand.SetHandler(IpcClient.SetFeature, featureArgument, valueArgument);
root.AddCommand(setFeatureCommand);

var getFeatureCommand = new Command("feature-get-value", "Get feature value");
getFeatureCommand.AddAlias("fgv");
getFeatureCommand.AddArgument(featureArgument);
getFeatureCommand.SetHandler(async name =>
{
PrintLine(flags, ex.Message);
return 1;
}
}
var value = await IpcClient.GetFeature(name);
Console.WriteLine(value);
}, featureArgument);
root.AddCommand(getFeatureCommand);

private static void PrintHelp(Flags flags)
{
PrintLine(flags, [
"Lenovo Legion Toolkit CLI",
"",
"Usage:",
" --quickAction=<name>, -qa=<name> - run Quick Action with specified name",
" --silent, -s - suppress output",
" --help, -h - display this help",
""
]);
return await builder.Build().InvokeAsync(args);
}

private static void PrintLine(Flags flags, params string[] messages)
private static void OnException(Exception ex, InvocationContext context)
{
if (flags.Silent)
return;
var message = ex switch
{
IpcException => ex.Message,
_ => ex.ToString()
};
var exitCode = ex switch
{
IpcException => -1,
_ => -99
};

foreach (var message in messages)
Console.WriteLine(message);
context.Console.Error.WriteLine(message);
context.ExitCode = exitCode;
}
}
60 changes: 60 additions & 0 deletions LenovoLegionToolkit.WPF/CLI/Features/FeatureRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LenovoLegionToolkit.Lib;
using LenovoLegionToolkit.Lib.Features;

namespace LenovoLegionToolkit.WPF.CLI.Features;

public readonly struct FeatureRegistration<T>() : IFeatureRegistration where T : struct
{
public string Name { get; } = typeof(T).Name.Replace("State", null).ToLowerInvariant();

private readonly Func<IFeature<T>> _feature = IoCContainer.Resolve<IFeature<T>>;

public Task<bool> IsSupportedAsync()
{
return _feature().IsSupportedAsync();
}

public async Task<IEnumerable<string>> GetValuesAsync()
{
var feature = _feature();

if (!await feature.IsSupportedAsync().ConfigureAwait(false))
throw new InvalidOperationException("Feature is not supported");

var states = await feature.GetAllStatesAsync().ConfigureAwait(false);
return states.Select(s => s.ToString()?.ToLowerInvariant()).OfType<string>();
}

public async Task SetValueAsync(string value)
{
var feature = _feature();

if (!await feature.IsSupportedAsync().ConfigureAwait(false))
throw new InvalidOperationException("Feature is not supported");

var states = await feature.GetAllStatesAsync().ConfigureAwait(false);
var state = Enum.TryParse<T>(value, true, out var s)
? s
: throw new InvalidOperationException("State is not supported");

if (!states.Contains(state))
throw new InvalidOperationException("State is not supported");

await feature.SetStateAsync(state).ConfigureAwait(false);
}

public async Task<string> GetValueAsync()
{
var feature = _feature();

if (!await feature.IsSupportedAsync().ConfigureAwait(false))
throw new InvalidOperationException("Feature is not supported");

var state = await feature.GetStateAsync().ConfigureAwait(false);
return state.ToString()?.ToLowerInvariant() ?? throw new InvalidOperationException("Null return value");
}
}
29 changes: 29 additions & 0 deletions LenovoLegionToolkit.WPF/CLI/Features/FeatureRegistry.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using LenovoLegionToolkit.Lib;

namespace LenovoLegionToolkit.WPF.CLI.Features;

public static class FeatureRegistry
{
public static readonly List<IFeatureRegistration> All =
[
new FeatureRegistration<AlwaysOnUSBState>(),
new FeatureRegistration<BatteryState>(),
new FeatureRegistration<BatteryNightChargeState>(),
new FeatureRegistration<FlipToStartState>(),
new FeatureRegistration<FnLockState>(),
new FeatureRegistration<HDRState>(),
new FeatureRegistration<HybridModeState>(),
new FeatureRegistration<InstantBootState>(),
new FeatureRegistration<MicrophoneState>(),
new FeatureRegistration<OneLevelWhiteKeyboardBacklightState>(),
new FeatureRegistration<OverDriveState>(),
new FeatureRegistration<PanelLogoBacklightState>(),
new FeatureRegistration<PortsBacklightState>(),
new FeatureRegistration<PowerModeState>(),
new FeatureRegistration<SpeakerState>(),
new FeatureRegistration<TouchpadLockState>(),
new FeatureRegistration<WinKeyState>(),
new FeatureRegistration<WhiteKeyboardBacklightState>(),
];
}
13 changes: 13 additions & 0 deletions LenovoLegionToolkit.WPF/CLI/Features/IFeatureRegistration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LenovoLegionToolkit.WPF.CLI.Features;

public interface IFeatureRegistration
{
string Name { get; }
Task<bool> IsSupportedAsync();
Task<IEnumerable<string>> GetValuesAsync();
Task SetValueAsync(string value);
Task<string> GetValueAsync();
}
Loading
Loading