mirror of
https://github.com/chylex/Query.git
synced 2025-05-23 01:34:06 +02:00
Fix Rider inspections
This commit is contained in:
parent
356d66121b
commit
4e950b73a3
@ -6,19 +6,29 @@ using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Base;
|
||||
|
||||
namespace AppCalc {
|
||||
public sealed class App : IApp {
|
||||
private static readonly Regex RegexValidCharacters = new Regex(@"^[\s\d\.\-+*/%^]+$", RegexOptions.Compiled);
|
||||
private static readonly Regex RegexTokenSeparator = new Regex(@"((?<!\d)-?(((\d+)?\.\d+(\.\.\.)?)|\d+))|[^\d\s]", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
|
||||
private static readonly Regex RegexRecurringDecimal = new Regex(@"\b(?:(\d+?\.\d{0,}?)(\d+?)\2+|([\d+?\.]*))\b", RegexOptions.Compiled);
|
||||
namespace AppCalc;
|
||||
|
||||
private static readonly char[] SplitSpace = { ' ' };
|
||||
public sealed partial class App : IApp {
|
||||
private static readonly Regex RegexValidCharacters = GetRegexValidCharacters();
|
||||
private static readonly Regex RegexTokenSeparator = GetRegexTokenSeparator();
|
||||
private static readonly Regex RegexRecurringDecimal = GetRegexRecurringDecimal();
|
||||
|
||||
public string[] RecognizedNames => new string[] {
|
||||
[GeneratedRegex(@"^[\s\d\.\-+*/%^]+$", RegexOptions.Compiled)]
|
||||
private static partial Regex GetRegexValidCharacters();
|
||||
|
||||
[GeneratedRegex(@"((?<!\d)-?(((\d+)?\.\d+(\.\.\.)?)|\d+))|[^\d\s]", RegexOptions.ExplicitCapture | RegexOptions.Compiled)]
|
||||
private static partial Regex GetRegexTokenSeparator();
|
||||
|
||||
[GeneratedRegex(@"\b(?:(\d+?\.\d{0,}?)(\d+?)\2+|([\d+?\.]*))\b", RegexOptions.Compiled)]
|
||||
private static partial Regex GetRegexRecurringDecimal();
|
||||
|
||||
private static readonly char[] SplitSpace = [ ' ' ];
|
||||
|
||||
public string[] RecognizedNames => [
|
||||
"calc",
|
||||
"calculate",
|
||||
"calculator"
|
||||
};
|
||||
];
|
||||
|
||||
public MatchConfidence GetConfidence(Command cmd) {
|
||||
return RegexValidCharacters.IsMatch(cmd.Text) ? MatchConfidence.Possible : MatchConfidence.None;
|
||||
@ -31,7 +41,7 @@ namespace AppCalc {
|
||||
private static string ParseAndProcessExpression(string text) {
|
||||
// text = RegexBalancedParentheses.Replace(text, match => " "+ParseAndProcessExpression(match.Groups[1].Value)+" "); // parens are handled as apps
|
||||
|
||||
string expression = RegexTokenSeparator.Replace(text, match => " " + match.Value + " ");
|
||||
string expression = RegexTokenSeparator.Replace(text, static match => " " + match.Value + " ");
|
||||
string[] tokens = expression.Split(SplitSpace, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
decimal result = ProcessExpression(tokens);
|
||||
@ -44,7 +54,7 @@ namespace AppCalc {
|
||||
bool hasDecimalPoint = decimal.Round(result) != result;
|
||||
|
||||
if (res.Length == 30 && hasDecimalPoint && res.IndexOf('.') < 15) { // Length 30 uses all available bytes
|
||||
res = res.Substring(0, res.Length - 1);
|
||||
res = res[..^1];
|
||||
|
||||
Match match = RegexRecurringDecimal.Match(res);
|
||||
|
||||
@ -58,7 +68,7 @@ namespace AppCalc {
|
||||
build.Append(repeating);
|
||||
} while (build.Length + repeating.Length <= res.Length);
|
||||
|
||||
return build.Append(repeating.Substring(0, 1 + build.Length - res.Length)).Append("...").ToString();
|
||||
return build.Append(repeating[..(1 + build.Length - res.Length)]).Append("...").ToString();
|
||||
}
|
||||
}
|
||||
else if (hasDecimalPoint) {
|
||||
@ -210,23 +220,21 @@ namespace AppCalc {
|
||||
string str = token;
|
||||
|
||||
if (str.StartsWith("-.")) {
|
||||
str = "-0" + str.Substring(1);
|
||||
str = "-0" + str[1..];
|
||||
}
|
||||
else if (str[0] == '.') {
|
||||
str = "0" + str;
|
||||
}
|
||||
|
||||
if (str.EndsWith("...")) {
|
||||
string truncated = str.Substring(0, str.Length - 3);
|
||||
string truncated = str[..^3];
|
||||
|
||||
if (truncated.IndexOf('.') != -1) {
|
||||
if (truncated.Contains('.')) {
|
||||
str = truncated;
|
||||
}
|
||||
}
|
||||
|
||||
decimal value;
|
||||
|
||||
if (decimal.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) {
|
||||
if (decimal.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal value)) {
|
||||
if (value.ToString(CultureInfo.InvariantCulture) != str) {
|
||||
throw new CommandException("Provided number is outside of decimal range: " + token);
|
||||
}
|
||||
@ -237,5 +245,4 @@ namespace AppCalc {
|
||||
throw new CommandException("Invalid token, expected a number: " + token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,28 +1,18 @@
|
||||
namespace AppCalc {
|
||||
static class Operators {
|
||||
internal static readonly string[] With2Operands = { "+", "-", "*", "/", "%", "^" };
|
||||
namespace AppCalc;
|
||||
|
||||
static class Operators {
|
||||
internal static readonly string[] With2Operands = [ "+", "-", "*", "/", "%", "^" ];
|
||||
|
||||
internal static int GetPrecedence(string token) {
|
||||
switch (token) {
|
||||
case "^":
|
||||
return 4;
|
||||
|
||||
case "*":
|
||||
case "/":
|
||||
case "%":
|
||||
return 3;
|
||||
|
||||
case "+":
|
||||
case "-":
|
||||
return 2;
|
||||
|
||||
default:
|
||||
return 1;
|
||||
}
|
||||
return token switch {
|
||||
"^" => 4,
|
||||
"*" or "/" or "%" => 3,
|
||||
"+" or "-" => 2,
|
||||
_ => 1
|
||||
};
|
||||
}
|
||||
|
||||
internal static bool IsRightAssociative(string token) {
|
||||
return token == "^";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,9 +4,10 @@ using AppConv.General;
|
||||
using AppConv.Units;
|
||||
using Base;
|
||||
|
||||
namespace AppConv {
|
||||
public sealed class App : IApp {
|
||||
private static readonly IUnitType[] Processors = {
|
||||
namespace AppConv;
|
||||
|
||||
public sealed class App : IApp {
|
||||
private static readonly IUnitType[] Processors = [
|
||||
new Temperature(),
|
||||
new Weight(),
|
||||
new Length(),
|
||||
@ -15,19 +16,19 @@ namespace AppConv {
|
||||
new Angle(),
|
||||
new Storage(),
|
||||
new Radix()
|
||||
};
|
||||
];
|
||||
|
||||
public string[] RecognizedNames => new string[] {
|
||||
public string[] RecognizedNames => [
|
||||
"conv",
|
||||
"convert"
|
||||
};
|
||||
];
|
||||
|
||||
public MatchConfidence GetConfidence(Command cmd) {
|
||||
return cmd.Text.IndexOf(" to ", StringComparison.InvariantCultureIgnoreCase) != -1 ? MatchConfidence.Possible : MatchConfidence.None;
|
||||
return cmd.Text.Contains(" to ", StringComparison.InvariantCultureIgnoreCase) ? MatchConfidence.Possible : MatchConfidence.None;
|
||||
}
|
||||
|
||||
public string ProcessCommand(Command cmd) {
|
||||
string[] data = cmd.Text.Split(new string[] { " to " }, 2, StringSplitOptions.None);
|
||||
string[] data = cmd.Text.Split([ " to " ], 2, StringSplitOptions.None);
|
||||
|
||||
string src = data[0].Trim();
|
||||
string dst = data[1].Trim();
|
||||
@ -45,5 +46,4 @@ namespace AppConv {
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,8 +3,9 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
|
||||
namespace AppConv.General {
|
||||
abstract class DecimalUnitConverterBase<T> : IUnitType where T : struct {
|
||||
namespace AppConv.General;
|
||||
|
||||
abstract class DecimalUnitConverterBase<T> : IUnitType where T : struct {
|
||||
internal sealed class DecimalFuncMap : Dictionary<T, Func<decimal, decimal>> {
|
||||
public DecimalFuncMap() {}
|
||||
public DecimalFuncMap(int capacity) : base(capacity) {}
|
||||
@ -95,13 +96,11 @@ namespace AppConv.General {
|
||||
}
|
||||
|
||||
if (index == 0) {
|
||||
src = src.Substring(0, src.Length - pairs[index].Key.Length).TrimEnd();
|
||||
src = src[..^pairs[index].Key.Length].TrimEnd();
|
||||
}
|
||||
}
|
||||
|
||||
decimal value;
|
||||
|
||||
if (decimal.TryParse(src, NumberStyle, CultureInfo.InvariantCulture, out value)) {
|
||||
if (decimal.TryParse(src, NumberStyle, CultureInfo.InvariantCulture, out decimal value)) {
|
||||
result = Format(Convert(value, pairs[0].Value, pairs[1].Value));
|
||||
return true;
|
||||
}
|
||||
@ -110,5 +109,4 @@ namespace AppConv.General {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,17 @@
|
||||
using System;
|
||||
|
||||
namespace AppConv.General {
|
||||
abstract class DecimalUnitConverterSimple<T> : DecimalUnitConverterBase<T> where T : struct {
|
||||
// ReSharper disable once StaticMemberInGenericType
|
||||
private static readonly Func<decimal, decimal> FuncNoChange = val => val;
|
||||
namespace AppConv.General;
|
||||
|
||||
private readonly NameMap UnitNames = new NameMap();
|
||||
private readonly DecimalFuncMap MapFrom = new DecimalFuncMap();
|
||||
private readonly DecimalFuncMap MapTo = new DecimalFuncMap();
|
||||
abstract class DecimalUnitConverterSimple<T> : DecimalUnitConverterBase<T> where T : struct {
|
||||
// ReSharper disable once StaticMemberInGenericType
|
||||
private static readonly Func<decimal, decimal> FuncNoChange = static val => val;
|
||||
|
||||
private readonly DecimalFuncMap MapFrom = new ();
|
||||
private readonly DecimalFuncMap MapTo = new ();
|
||||
|
||||
private int invalidUnitObject = -1;
|
||||
|
||||
protected sealed override NameMap Names => UnitNames;
|
||||
protected sealed override NameMap Names { get ; } = new ();
|
||||
|
||||
protected sealed override DecimalFuncMap ConvertFrom => MapFrom;
|
||||
|
||||
@ -23,7 +23,7 @@ namespace AppConv.General {
|
||||
|
||||
protected void AddUnit(T unitObject, params string[] names) {
|
||||
foreach (string name in names) {
|
||||
UnitNames.Add(name, unitObject);
|
||||
Names.Add(name, unitObject);
|
||||
}
|
||||
|
||||
ConvertFrom.Add(unitObject, FuncNoChange);
|
||||
@ -42,5 +42,4 @@ namespace AppConv.General {
|
||||
protected sealed override bool IsValueInvalid(T value) {
|
||||
return (int) (object) value == invalidUnitObject;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
namespace AppConv.General {
|
||||
interface IUnitType {
|
||||
namespace AppConv.General;
|
||||
|
||||
interface IUnitType {
|
||||
bool TryProcess(string src, string dst, out string result);
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
using System;
|
||||
using AppConv.General;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Angle : DecimalUnitConverterSimple<Angle.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Angle : DecimalUnitConverterSimple<Angle.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Degree,
|
||||
@ -24,5 +25,4 @@ namespace AppConv.Units {
|
||||
}
|
||||
|
||||
// TODO convert degree notation 15°24'9"
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,8 @@
|
||||
using AppConv.General;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Area : DecimalUnitConverterSimple<Area.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Area : DecimalUnitConverterSimple<Area.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
SquareMM,
|
||||
@ -54,5 +55,4 @@ namespace AppConv.Units {
|
||||
|
||||
SetInvalidUnitObject(Units.Invalid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,8 +4,9 @@ using System.Linq;
|
||||
using AppConv.General;
|
||||
using AppConv.Utils;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Length : DecimalUnitConverterSimple<Length.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Length : DecimalUnitConverterSimple<Length.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Meter,
|
||||
@ -15,8 +16,10 @@ namespace AppConv.Units {
|
||||
Mile
|
||||
}
|
||||
|
||||
private static readonly string[] NamesInch = { "in", "inch", "inches", "\"", "''" };
|
||||
private static readonly string[] NamesFoot = { "ft", "foot", "feet", "'" };
|
||||
private static readonly string[] NamesInch = [ "in", "inch", "inches", "\"", "''" ];
|
||||
private static readonly string[] NamesFoot = [ "ft", "foot", "feet", "'" ];
|
||||
|
||||
private static readonly char[] Separator = [ ' ' ];
|
||||
|
||||
public Length() {
|
||||
AddUnit(Units.Meter, "m", "meter", "metre", "meters", "metres");
|
||||
@ -32,7 +35,7 @@ namespace AppConv.Units {
|
||||
|
||||
SetInvalidUnitObject(Units.Invalid);
|
||||
|
||||
SI.AddSupport(typeof(Units), Units.Meter, new [] { "m" }, new [] { "meter", "metre", "meters", "metres" }, ConvertFrom, ConvertTo, Names);
|
||||
SI.AddSupport(Units.Meter, [ "m" ], [ "meter", "metre", "meters", "metres" ], ConvertFrom, ConvertTo, Names);
|
||||
}
|
||||
|
||||
protected override string ProcessSrc(string src) {
|
||||
@ -41,7 +44,7 @@ namespace AppConv.Units {
|
||||
updatedStr = updatedStr.Replace("&", " ");
|
||||
updatedStr = updatedStr.Replace(",", " ");
|
||||
|
||||
string inchName = NamesInch.FirstOrDefault(name => src.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
|
||||
string inchName = NamesInch.FirstOrDefault(name => src.Contains(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (inchName == null) {
|
||||
return src;
|
||||
@ -50,7 +53,7 @@ namespace AppConv.Units {
|
||||
int inchIndex = src.IndexOf(inchName, StringComparison.OrdinalIgnoreCase);
|
||||
updatedStr = updatedStr.Remove(inchIndex, inchName.Length).Insert(inchIndex, new string(' ', inchName.Length));
|
||||
|
||||
string footName = NamesFoot.FirstOrDefault(name => updatedStr.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
|
||||
string footName = NamesFoot.FirstOrDefault(name => updatedStr.Contains(name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (footName == null) {
|
||||
return src;
|
||||
@ -59,14 +62,12 @@ namespace AppConv.Units {
|
||||
int footIndex = updatedStr.IndexOf(footName, StringComparison.OrdinalIgnoreCase);
|
||||
updatedStr = updatedStr.Remove(footIndex, footName.Length).Insert(footIndex, new string(' ', footName.Length));
|
||||
|
||||
string[] tokens = updatedStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
string[] tokens = updatedStr.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
|
||||
decimal[] numbers = new decimal[2];
|
||||
int numberIndex = 0;
|
||||
|
||||
foreach (string token in tokens) {
|
||||
decimal number;
|
||||
|
||||
if (decimal.TryParse(token.Trim(), NumberStyle, CultureInfo.InvariantCulture, out number)) {
|
||||
if (decimal.TryParse(token.Trim(), NumberStyle, CultureInfo.InvariantCulture, out decimal number)) {
|
||||
if (numberIndex < numbers.Length) {
|
||||
numbers[numberIndex++] = number;
|
||||
}
|
||||
@ -85,5 +86,4 @@ namespace AppConv.Units {
|
||||
|
||||
return srcInches + srcFeet * 12M + " in";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,9 +5,10 @@ using AppConv.General;
|
||||
using AppConv.Utils;
|
||||
using Base;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Radix : IUnitType {
|
||||
private static readonly Dictionary<string, int> RadixDescriptions = new Dictionary<string, int> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Radix : IUnitType {
|
||||
private static readonly Dictionary<string, int> RadixDescriptions = new () {
|
||||
{ "UNARY", 1 },
|
||||
{ "BINARY", 2 },
|
||||
{ "BIN", 2 },
|
||||
@ -37,17 +38,12 @@ namespace AppConv.Units {
|
||||
}
|
||||
|
||||
public bool TryProcess(string src, string dst, out string result) {
|
||||
int targetBase;
|
||||
|
||||
if (!RadixDescriptions.TryGetValue(dst.ToUpperInvariant(), out targetBase)) {
|
||||
if (!RadixDescriptions.TryGetValue(dst.ToUpperInvariant(), out int targetBase)) {
|
||||
result = string.Empty;
|
||||
return false;
|
||||
}
|
||||
|
||||
string contents;
|
||||
int sourceBase;
|
||||
|
||||
if (!ParseSrc(src, out contents, out sourceBase)) {
|
||||
if (!ParseSrc(src, out string contents, out int sourceBase)) {
|
||||
result = string.Empty;
|
||||
return false;
|
||||
}
|
||||
@ -77,7 +73,7 @@ namespace AppConv.Units {
|
||||
}
|
||||
|
||||
private static bool ParseSrc(string src, out string sourceContent, out int sourceBase) {
|
||||
if (src.All(chr => chr >= '0' && chr <= '9')) {
|
||||
if (src.All(static chr => chr is >= '0' and <= '9')) {
|
||||
sourceContent = src;
|
||||
sourceBase = 10;
|
||||
return true;
|
||||
@ -86,13 +82,13 @@ namespace AppConv.Units {
|
||||
string upper = src.ToUpperInvariant();
|
||||
|
||||
if (upper.StartsWith("0X")) {
|
||||
sourceContent = upper.Substring(2);
|
||||
sourceContent = upper[2..];
|
||||
sourceBase = 16;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (upper.StartsWith("0B")) {
|
||||
sourceContent = upper.Substring(2);
|
||||
sourceContent = upper[2..];
|
||||
sourceBase = 2;
|
||||
return true;
|
||||
}
|
||||
@ -105,12 +101,12 @@ namespace AppConv.Units {
|
||||
|
||||
foreach (KeyValuePair<string, int> kvp in RadixDescriptions) {
|
||||
if (src.StartsWith(kvp.Key, StringComparison.InvariantCultureIgnoreCase)) {
|
||||
sourceContent = src.Substring(kvp.Key.Length).Trim();
|
||||
sourceContent = src[kvp.Key.Length..].Trim();
|
||||
sourceBase = kvp.Value;
|
||||
return true;
|
||||
}
|
||||
else if (src.EndsWith(kvp.Key, StringComparison.InvariantCultureIgnoreCase)) {
|
||||
sourceContent = src.Substring(0, src.Length - kvp.Key.Length).Trim();
|
||||
sourceContent = src[..^kvp.Key.Length].Trim();
|
||||
sourceBase = kvp.Value;
|
||||
return true;
|
||||
}
|
||||
@ -120,5 +116,4 @@ namespace AppConv.Units {
|
||||
sourceBase = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,18 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using AppConv.General;
|
||||
using AppConv.Utils;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Storage : DecimalUnitConverterSimple<Storage.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Storage : DecimalUnitConverterSimple<Storage.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Byte,
|
||||
Bit
|
||||
}
|
||||
|
||||
[SuppressMessage("ReSharper", "PossibleLossOfFraction")]
|
||||
public Storage() {
|
||||
AddUnit(Units.Byte, "B", "byte", "bytes");
|
||||
AddUnit(Units.Bit, "b", "bit", "bits");
|
||||
@ -19,13 +22,12 @@ namespace AppConv.Units {
|
||||
SetInvalidUnitObject(Units.Invalid);
|
||||
|
||||
var bitConversionProperties = new SI.ExtededProperties {
|
||||
FactorPredicate = factor => factor > 0 && factor % 3 == 0,
|
||||
FromFunctionGenerator = exponent => () => (decimal) Math.Pow(1024, -(int) (exponent / 3)),
|
||||
ToFunctionGenerator = exponent => () => (decimal) Math.Pow(1024, (int) (exponent / 3))
|
||||
FactorPredicate = static factor => factor > 0 && factor % 3 == 0,
|
||||
FromFunctionGenerator = static exponent => () => (decimal) Math.Pow(1024, -(exponent / 3)),
|
||||
ToFunctionGenerator = static exponent => () => (decimal) Math.Pow(1024, exponent / 3)
|
||||
};
|
||||
|
||||
SI.AddSupportCustom(typeof(Units), Units.Byte, new [] { "B" }, new [] { "byte", "bytes" }, ConvertFrom, ConvertTo, Names, bitConversionProperties);
|
||||
SI.AddSupportCustom(typeof(Units), Units.Bit, new [] { "b" }, new [] { "bit", "bits" }, ConvertFrom, ConvertTo, Names, bitConversionProperties);
|
||||
}
|
||||
SI.AddSupportCustom(Units.Byte, [ "B" ], [ "byte", "bytes" ], ConvertFrom, ConvertTo, Names, bitConversionProperties);
|
||||
SI.AddSupportCustom(Units.Bit, [ "b" ], [ "bit", "bits" ], ConvertFrom, ConvertTo, Names, bitConversionProperties);
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using AppConv.General;
|
||||
using Base.Utils;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Temperature : DecimalUnitConverterBase<Temperature.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed partial class Temperature : DecimalUnitConverterBase<Temperature.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Celsius,
|
||||
@ -17,7 +17,7 @@ namespace AppConv.Units {
|
||||
Romer
|
||||
}
|
||||
|
||||
private static readonly NameMap UnitNames = new NameMap(21) {
|
||||
private static readonly NameMap UnitNames = new (21) {
|
||||
{ "C", Units.Celsius },
|
||||
{ "Celsius", Units.Celsius },
|
||||
{ "K", Units.Kelvin },
|
||||
@ -41,29 +41,32 @@ namespace AppConv.Units {
|
||||
{ "Rømer", Units.Romer }
|
||||
};
|
||||
|
||||
private static readonly DecimalFuncMap FromCelsius = new DecimalFuncMap(8) {
|
||||
{ Units.Celsius, val => val },
|
||||
{ Units.Kelvin, val => val + 273.15M },
|
||||
{ Units.Fahrenheit, val => val * 1.8M + 32M },
|
||||
{ Units.Rankine, val => (val + 273.15M) * 1.8M },
|
||||
{ Units.Delisle, val => (100M - val) * 1.5M },
|
||||
{ Units.Newton, val => val * 0.33M },
|
||||
{ Units.Reaumur, val => val * 0.8M },
|
||||
{ Units.Romer, val => val * 0.525M + 7.5M }
|
||||
private static readonly DecimalFuncMap FromCelsius = new (8) {
|
||||
{ Units.Celsius, static val => val },
|
||||
{ Units.Kelvin, static val => val + 273.15M },
|
||||
{ Units.Fahrenheit, static val => val * 1.8M + 32M },
|
||||
{ Units.Rankine, static val => (val + 273.15M) * 1.8M },
|
||||
{ Units.Delisle, static val => (100M - val) * 1.5M },
|
||||
{ Units.Newton, static val => val * 0.33M },
|
||||
{ Units.Reaumur, static val => val * 0.8M },
|
||||
{ Units.Romer, static val => val * 0.525M + 7.5M }
|
||||
};
|
||||
|
||||
private static readonly DecimalFuncMap ToCelsius = new DecimalFuncMap(8) {
|
||||
{ Units.Celsius, val => val },
|
||||
{ Units.Kelvin, val => val - 273.15M },
|
||||
{ Units.Fahrenheit, val => (val - 32M) * 5M / 9M },
|
||||
{ Units.Rankine, val => (val - 491.67M) * 5M / 9M },
|
||||
{ Units.Delisle, val => 100M - val * 2M / 3M },
|
||||
{ Units.Newton, val => val * 100M / 33M },
|
||||
{ Units.Reaumur, val => val * 1.25M },
|
||||
{ Units.Romer, val => (val - 7.5M) * 40M / 21M }
|
||||
private static readonly DecimalFuncMap ToCelsius = new (8) {
|
||||
{ Units.Celsius, static val => val },
|
||||
{ Units.Kelvin, static val => val - 273.15M },
|
||||
{ Units.Fahrenheit, static val => (val - 32M) * 5M / 9M },
|
||||
{ Units.Rankine, static val => (val - 491.67M) * 5M / 9M },
|
||||
{ Units.Delisle, static val => 100M - val * 2M / 3M },
|
||||
{ Units.Newton, static val => val * 100M / 33M },
|
||||
{ Units.Reaumur, static val => val * 1.25M },
|
||||
{ Units.Romer, static val => (val - 7.5M) * 40M / 21M }
|
||||
};
|
||||
|
||||
private static readonly Regex RegexCleanup = new Regex("deg(?:rees?)?|°", RegexUtils.Text);
|
||||
private static readonly Regex RegexCleanup = GetRegexCleanup();
|
||||
|
||||
[GeneratedRegex("deg(?:rees?)?|°", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.CultureInvariant)]
|
||||
private static partial Regex GetRegexCleanup();
|
||||
|
||||
protected override NameMap Names => UnitNames;
|
||||
|
||||
@ -86,5 +89,4 @@ namespace AppConv.Units {
|
||||
protected override bool IsValueInvalid(Units value) {
|
||||
return value == Units.Invalid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
using AppConv.General;
|
||||
using AppConv.Utils;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Volume : DecimalUnitConverterSimple<Volume.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Volume : DecimalUnitConverterSimple<Volume.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Liter,
|
||||
@ -28,7 +29,6 @@ namespace AppConv.Units {
|
||||
|
||||
SetInvalidUnitObject(Units.Invalid);
|
||||
|
||||
SI.AddSupport(typeof(Units), Units.Liter, new [] { "l" }, new [] { "liter", "litre", "liters", "litres" }, ConvertFrom, ConvertTo, Names);
|
||||
}
|
||||
SI.AddSupport(Units.Liter, [ "l" ], [ "liter", "litre", "liters", "litres" ], ConvertFrom, ConvertTo, Names);
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
using AppConv.General;
|
||||
using AppConv.Utils;
|
||||
|
||||
namespace AppConv.Units {
|
||||
class Weight : DecimalUnitConverterSimple<Weight.Units> {
|
||||
namespace AppConv.Units;
|
||||
|
||||
sealed class Weight : DecimalUnitConverterSimple<Weight.Units> {
|
||||
internal enum Units {
|
||||
Invalid = 0,
|
||||
Gram,
|
||||
@ -23,7 +24,6 @@ namespace AppConv.Units {
|
||||
|
||||
SetInvalidUnitObject(Units.Invalid);
|
||||
|
||||
SI.AddSupport(typeof(Units), Units.Gram, new [] { "g" }, new [] { "gram", "grams" }, ConvertFrom, ConvertTo, Names);
|
||||
}
|
||||
SI.AddSupport(Units.Gram, [ "g" ], [ "gram", "grams" ], ConvertFrom, ConvertTo, Names);
|
||||
}
|
||||
}
|
||||
|
@ -3,21 +3,22 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace AppConv.Utils {
|
||||
static class RadixConversion {
|
||||
namespace AppConv.Utils;
|
||||
|
||||
static class RadixConversion {
|
||||
private const string Characters = "0123456789ABCDEF";
|
||||
|
||||
public static bool IsBaseValid(int checkedBase) {
|
||||
return checkedBase >= 1 && checkedBase <= 16;
|
||||
return checkedBase is >= 1 and <= 16;
|
||||
}
|
||||
|
||||
public static bool IsNumberValid(string contents, int checkedBase) {
|
||||
if (checkedBase == 1) {
|
||||
return contents.All(chr => chr == '1');
|
||||
return contents.All(static chr => chr == '1');
|
||||
}
|
||||
|
||||
if (IsBaseValid(checkedBase)) {
|
||||
return contents.Select(chr => Characters.IndexOf(char.ToUpper(chr))).All(index => index != -1 && index < checkedBase);
|
||||
return contents.Select(static chr => Characters.IndexOf(char.ToUpper(chr))).All(index => index != -1 && index < checkedBase);
|
||||
}
|
||||
|
||||
return false;
|
||||
@ -68,11 +69,10 @@ namespace AppConv.Utils {
|
||||
int index = (int) (wip % toBase);
|
||||
converted.Insert(0, Characters[index]);
|
||||
|
||||
wip = wip / toBase;
|
||||
wip /= toBase;
|
||||
}
|
||||
|
||||
return converted.Insert(0, Characters[(int) wip]).ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,9 +2,10 @@
|
||||
using System.Collections.Generic;
|
||||
using AppConv.General;
|
||||
|
||||
namespace AppConv.Utils {
|
||||
static class SI {
|
||||
private static readonly List<Tuple<string, string, int>> Factors = new List<Tuple<string, string, int>> {
|
||||
namespace AppConv.Utils;
|
||||
|
||||
static class SI {
|
||||
private static readonly List<Tuple<string, string, int>> Factors = [
|
||||
new Tuple<string, string, int>("yotta", "Y", 24),
|
||||
new Tuple<string, string, int>("zetta", "Z", 21),
|
||||
new Tuple<string, string, int>("exa", "E", 18),
|
||||
@ -25,24 +26,23 @@ namespace AppConv.Utils {
|
||||
new Tuple<string, string, int>("atto", "a", -18),
|
||||
new Tuple<string, string, int>("zepto", "z", -21),
|
||||
new Tuple<string, string, int>("yocto", "y", -24)
|
||||
};
|
||||
];
|
||||
|
||||
public static void AddSupport<T>(Type enumType, T unitObject, string[] unitShortNames, string[] unitLongNames, DecimalUnitConverterBase<T>.DecimalFuncMap funcFrom, DecimalUnitConverterBase<T>.DecimalFuncMap funcTo, DecimalUnitConverterBase<T>.NameMap nameMap) where T : struct {
|
||||
public static void AddSupport<T>(T unitObject, string[] unitShortNames, string[] unitLongNames, DecimalUnitConverterBase<T>.DecimalFuncMap funcFrom, DecimalUnitConverterBase<T>.DecimalFuncMap funcTo, DecimalUnitConverterBase<T>.NameMap nameMap) where T : struct {
|
||||
int enumCounter = 1000 + Factors.Count * (int) (object) unitObject;
|
||||
|
||||
Func<decimal, decimal> convertFrom = funcFrom[unitObject];
|
||||
Func<decimal, decimal> convertTo = funcTo[unitObject];
|
||||
|
||||
foreach (Tuple<string, string, int> factor in Factors) {
|
||||
foreach ((string unitLongNamePrefix, string unitShotNamePrefix, int exponent) in Factors) {
|
||||
T enumObject = (T) (object) enumCounter++;
|
||||
int exponent = factor.Item3;
|
||||
|
||||
foreach (string unitShortName in unitShortNames) {
|
||||
nameMap.Add(factor.Item2 + unitShortName, enumObject);
|
||||
nameMap.Add(unitShotNamePrefix + unitShortName, enumObject);
|
||||
}
|
||||
|
||||
foreach (string unitLongName in unitLongNames) {
|
||||
nameMap.Add(factor.Item1 + unitLongName, enumObject);
|
||||
nameMap.Add(unitLongNamePrefix + unitLongName, enumObject);
|
||||
}
|
||||
|
||||
funcFrom.Add(enumObject, val => convertFrom(val) * (decimal) Math.Pow(10, -exponent));
|
||||
@ -50,26 +50,25 @@ namespace AppConv.Utils {
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddSupportCustom<T>(Type enumType, T unitObject, string[] unitShortNames, string[] unitLongNames, DecimalUnitConverterBase<T>.DecimalFuncMap funcFrom, DecimalUnitConverterBase<T>.DecimalFuncMap funcTo, DecimalUnitConverterBase<T>.NameMap nameMap, ExtededProperties extendedProps) where T : struct {
|
||||
public static void AddSupportCustom<T>(T unitObject, string[] unitShortNames, string[] unitLongNames, DecimalUnitConverterBase<T>.DecimalFuncMap funcFrom, DecimalUnitConverterBase<T>.DecimalFuncMap funcTo, DecimalUnitConverterBase<T>.NameMap nameMap, ExtededProperties extendedProps) where T : struct {
|
||||
int enumCounter = 1000 + Factors.Count * (int) (object) unitObject;
|
||||
|
||||
Func<decimal, decimal> convertFrom = funcFrom[unitObject];
|
||||
Func<decimal, decimal> convertTo = funcTo[unitObject];
|
||||
|
||||
foreach (Tuple<string, string, int> factor in Factors) {
|
||||
if (extendedProps.FactorPredicate != null && !extendedProps.FactorPredicate(factor.Item3)) {
|
||||
foreach ((string unitLongNamePrefix, string unitShortNamePrefix, int exponent) in Factors) {
|
||||
if (extendedProps.FactorPredicate != null && !extendedProps.FactorPredicate(exponent)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
T enumObject = (T) (object) enumCounter++;
|
||||
int exponent = factor.Item3;
|
||||
|
||||
foreach (string unitShortName in unitShortNames) {
|
||||
nameMap.Add(factor.Item2 + unitShortName, enumObject);
|
||||
nameMap.Add(unitShortNamePrefix + unitShortName, enumObject);
|
||||
}
|
||||
|
||||
foreach (string unitLongName in unitLongNames) {
|
||||
nameMap.Add(factor.Item1 + unitLongName, enumObject);
|
||||
nameMap.Add(unitLongNamePrefix + unitLongName, enumObject);
|
||||
}
|
||||
|
||||
Func<decimal> genFrom = extendedProps.FromFunctionGenerator(exponent);
|
||||
@ -80,10 +79,9 @@ namespace AppConv.Utils {
|
||||
}
|
||||
}
|
||||
|
||||
internal class ExtededProperties {
|
||||
public Predicate<int> FactorPredicate { get; set; }
|
||||
public Func<int, Func<decimal>> FromFunctionGenerator { get; set; }
|
||||
public Func<int, Func<decimal>> ToFunctionGenerator { get; set; }
|
||||
}
|
||||
internal sealed class ExtededProperties {
|
||||
public Predicate<int> FactorPredicate { get; init; }
|
||||
public Func<int, Func<decimal>> FromFunctionGenerator { get; init; }
|
||||
public Func<int, Func<decimal>> ToFunctionGenerator { get; init; }
|
||||
}
|
||||
}
|
||||
|
@ -1,18 +1,19 @@
|
||||
using System.Collections.Generic;
|
||||
using Base;
|
||||
|
||||
namespace AppMeme {
|
||||
public sealed class App : IApp {
|
||||
private static readonly Dictionary<string, string> Map = new Dictionary<string, string> {
|
||||
namespace AppMeme;
|
||||
|
||||
public sealed class App : IApp {
|
||||
private static readonly Dictionary<string, string> Map = new () {
|
||||
{ "shrug", @"¯\_(ツ)_/¯" },
|
||||
{ "lenny", @"( ͡° ͜ʖ ͡°)" },
|
||||
{ "flip", @"(╯°□°)╯︵ ┻━┻" },
|
||||
{ "tableflip", @"(╯°□°)╯︵ ┻━┻" }
|
||||
};
|
||||
|
||||
public string[] RecognizedNames => new string[] {
|
||||
public string[] RecognizedNames => [
|
||||
"meme"
|
||||
};
|
||||
];
|
||||
|
||||
public MatchConfidence GetConfidence(Command cmd) {
|
||||
return Map.ContainsKey(cmd.Text) ? MatchConfidence.Full : MatchConfidence.None;
|
||||
@ -21,5 +22,4 @@ namespace AppMeme {
|
||||
public string ProcessCommand(Command cmd) {
|
||||
return Map[cmd.Text];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,18 +2,19 @@
|
||||
using AppSys.Handlers;
|
||||
using Base;
|
||||
|
||||
namespace AppSys {
|
||||
public sealed class App : IApp {
|
||||
private static readonly IHandler[] Handlers = {
|
||||
namespace AppSys;
|
||||
|
||||
public sealed class App : IApp {
|
||||
private static readonly IHandler[] Handlers = [
|
||||
new HandlerProcesses(),
|
||||
new HandlerApps()
|
||||
};
|
||||
];
|
||||
|
||||
public string[] RecognizedNames => new string[] {
|
||||
public string[] RecognizedNames => [
|
||||
"sys",
|
||||
"os",
|
||||
"win"
|
||||
};
|
||||
];
|
||||
|
||||
public MatchConfidence GetConfidence(Command cmd) {
|
||||
return Handlers.Any(handler => handler.Matches(cmd)) ? MatchConfidence.Full : MatchConfidence.None;
|
||||
@ -22,5 +23,4 @@ namespace AppSys {
|
||||
public string ProcessCommand(Command cmd) {
|
||||
return Handlers.First(handler => handler.Matches(cmd)).Handle(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4,11 +4,12 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using Base;
|
||||
|
||||
namespace AppSys.Handlers {
|
||||
class HandlerApps : IHandler {
|
||||
namespace AppSys.Handlers;
|
||||
|
||||
sealed class HandlerApps : IHandler {
|
||||
private static readonly string PathSystem = Environment.GetFolderPath(Environment.SpecialFolder.System);
|
||||
|
||||
private static readonly Dictionary<string, ProcessStartInfo> Mappings = new Dictionary<string, ProcessStartInfo> {
|
||||
private static readonly Dictionary<string, ProcessStartInfo> Mappings = new () {
|
||||
{
|
||||
"audio", new ProcessStartInfo {
|
||||
FileName = Path.Combine(PathSystem, "control.exe"),
|
||||
@ -32,7 +33,7 @@ namespace AppSys.Handlers {
|
||||
}
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, string> Substitutions = new Dictionary<string, string> {
|
||||
private static readonly Dictionary<string, string> Substitutions = new () {
|
||||
{ "sounds", "audio" },
|
||||
{ "apps", "programs" },
|
||||
{ "appwiz", "programs" },
|
||||
@ -47,9 +48,7 @@ namespace AppSys.Handlers {
|
||||
}
|
||||
|
||||
public string Handle(Command cmd) {
|
||||
string key;
|
||||
|
||||
if (!Substitutions.TryGetValue(cmd.Text, out key)) {
|
||||
if (!Substitutions.TryGetValue(cmd.Text, out string key)) {
|
||||
key = cmd.Text;
|
||||
}
|
||||
|
||||
@ -57,5 +56,4 @@ namespace AppSys.Handlers {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,19 +3,20 @@ using System.Diagnostics;
|
||||
using System.Text;
|
||||
using Base;
|
||||
|
||||
namespace AppSys.Handlers {
|
||||
class HandlerProcesses : IHandler {
|
||||
namespace AppSys.Handlers;
|
||||
|
||||
sealed class HandlerProcesses : IHandler {
|
||||
public bool Matches(Command cmd) {
|
||||
return cmd.Text.StartsWith("kill ", StringComparison.InvariantCultureIgnoreCase);
|
||||
}
|
||||
|
||||
public string Handle(Command cmd) {
|
||||
string[] processNames = cmd.Text.Substring("kill ".Length).Split(',', ';');
|
||||
string[] processNames = cmd.Text["kill ".Length..].Split(',', ';');
|
||||
int succeeded = 0, failed = 0;
|
||||
|
||||
foreach (string processName in processNames) {
|
||||
try {
|
||||
Process[] processes = Process.GetProcessesByName(processName.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase) ? processName.Substring(0, processName.Length - 4) : processName);
|
||||
Process[] processes = Process.GetProcessesByName(processName.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase) ? processName[..^4] : processName);
|
||||
|
||||
foreach (Process process in processes) {
|
||||
try {
|
||||
@ -45,5 +46,4 @@ namespace AppSys.Handlers {
|
||||
|
||||
return build.Append('.').ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
using Base;
|
||||
|
||||
namespace AppSys {
|
||||
interface IHandler {
|
||||
namespace AppSys;
|
||||
|
||||
interface IHandler {
|
||||
bool Matches(Command cmd);
|
||||
string Handle(Command cmd);
|
||||
}
|
||||
}
|
||||
|
@ -2,12 +2,13 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Base.Utils;
|
||||
|
||||
namespace Base {
|
||||
public sealed class Command {
|
||||
private static readonly Regex RegexBalancedBrackets = new Regex(RegexUtils.Balance(@"\[", @"\]"), RegexOptions.Compiled);
|
||||
private static readonly Regex RegexBalancedParentheses = new Regex(RegexUtils.Balance(@"\(", @"\)"), RegexOptions.Compiled);
|
||||
namespace Base;
|
||||
|
||||
public string Text { get; private set; }
|
||||
public sealed class Command(string text) {
|
||||
private static readonly Regex RegexBalancedBrackets = new (RegexUtils.Balance(@"\[", @"\]"), RegexOptions.Compiled);
|
||||
private static readonly Regex RegexBalancedParentheses = new (RegexUtils.Balance(@"\(", @"\)"), RegexOptions.Compiled);
|
||||
|
||||
public string Text { get; } = text;
|
||||
|
||||
public string PotentialAppName {
|
||||
get {
|
||||
@ -17,7 +18,7 @@ namespace Base {
|
||||
return null;
|
||||
}
|
||||
|
||||
string firstToken = Text.Substring(0, firstSpace);
|
||||
string firstToken = Text[..firstSpace];
|
||||
|
||||
if (!firstToken.All(char.IsLetter)) {
|
||||
return null;
|
||||
@ -27,14 +28,9 @@ namespace Base {
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsSingleToken => Text.IndexOf(' ') == -1;
|
||||
|
||||
public Command(string text) {
|
||||
Text = text;
|
||||
}
|
||||
public bool IsSingleToken => !Text.Contains(' ');
|
||||
|
||||
public Command ReplaceBrackets(MatchEvaluator evaluator) {
|
||||
return new Command(RegexBalancedParentheses.Replace(RegexBalancedBrackets.Replace(Text, evaluator), evaluator));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +1,7 @@
|
||||
using System;
|
||||
|
||||
namespace Base {
|
||||
public class CommandEventArgs : EventArgs {
|
||||
public Command Command { get; private set; }
|
||||
namespace Base;
|
||||
|
||||
public CommandEventArgs(string text) {
|
||||
Command = new Command(text);
|
||||
}
|
||||
}
|
||||
public sealed class CommandEventArgs(string text) : EventArgs {
|
||||
public Command Command { get; private set; } = new (text);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
using System;
|
||||
|
||||
namespace Base {
|
||||
public class CommandException : Exception {
|
||||
namespace Base;
|
||||
|
||||
public sealed class CommandException : Exception {
|
||||
public CommandException(string message) : base(message) {}
|
||||
public CommandException(string message, Exception innerException) : base(message, innerException) {}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
namespace Base {
|
||||
public interface IApp {
|
||||
namespace Base;
|
||||
|
||||
public interface IApp {
|
||||
string[] RecognizedNames { get; }
|
||||
|
||||
MatchConfidence GetConfidence(Command cmd);
|
||||
string ProcessCommand(Command cmd);
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
namespace Base {
|
||||
public enum MatchConfidence {
|
||||
namespace Base;
|
||||
|
||||
public enum MatchConfidence {
|
||||
None = 0,
|
||||
Low = 1,
|
||||
Possible = 2,
|
||||
Full = 3
|
||||
}
|
||||
}
|
||||
|
@ -1,23 +1,23 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Base.Utils {
|
||||
public static class RegexUtils {
|
||||
public static readonly RegexOptions Text = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled;
|
||||
namespace Base.Utils;
|
||||
|
||||
public static string Balance(string escapedStart, string escapedEnd) { // \(((?>[^()]+|\((?<n>)|\)(?<-n>))+(?(n)(?!)))\)
|
||||
public static class RegexUtils {
|
||||
public const RegexOptions Text = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled;
|
||||
|
||||
internal static string Balance(string escapedStart, string escapedEnd) { // \(((?>[^()]+|\((?<n>)|\)(?<-n>))+(?(n)(?!)))\)
|
||||
return new StringBuilder()
|
||||
.Append(escapedStart)
|
||||
.Append(@"((?>[^")
|
||||
.Append("((?>[^")
|
||||
.Append(escapedStart)
|
||||
.Append(escapedEnd)
|
||||
.Append(@"]+|")
|
||||
.Append("]+|")
|
||||
.Append(escapedStart)
|
||||
.Append(@"(?<n>)|")
|
||||
.Append("(?<n>)|")
|
||||
.Append(escapedEnd)
|
||||
.Append(@"(?<-n>))+(?(n)(?!)))")
|
||||
.Append("(?<-n>))+(?(n)(?!)))")
|
||||
.Append(escapedEnd)
|
||||
.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,8 +2,9 @@
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Query.Controls {
|
||||
sealed partial class QueryHistoryLog : UserControl {
|
||||
namespace Query.Controls;
|
||||
|
||||
sealed partial class QueryHistoryLog : UserControl {
|
||||
public enum EntryType {
|
||||
UserInput,
|
||||
CommandResult,
|
||||
@ -11,7 +12,7 @@ namespace Query.Controls {
|
||||
Error
|
||||
}
|
||||
|
||||
private static readonly Dictionary<EntryType, Color> EntryColorMap = new Dictionary<EntryType, Color> {
|
||||
private static readonly Dictionary<EntryType, Color> EntryColorMap = new () {
|
||||
{ EntryType.UserInput, Color.FromArgb(160, 160, 160) },
|
||||
{ EntryType.CommandResult, Color.FromArgb(240, 240, 240) },
|
||||
{ EntryType.Information, Color.FromArgb(160, 255, 140) },
|
||||
@ -42,5 +43,4 @@ namespace Query.Controls {
|
||||
public void ClearEntries() {
|
||||
container.Controls.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,8 +5,9 @@ using System.Windows.Forms;
|
||||
using Base;
|
||||
using Query.Core;
|
||||
|
||||
namespace Query.Controls {
|
||||
sealed partial class QueryTextBox : UserControl {
|
||||
namespace Query.Controls;
|
||||
|
||||
sealed partial class QueryTextBox : UserControl {
|
||||
public event EventHandler<CommandEventArgs> CommandRan;
|
||||
|
||||
private CommandHistory history;
|
||||
@ -39,7 +40,7 @@ namespace Query.Controls {
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e) {
|
||||
QueryTextBox input = (QueryTextBox) Parent;
|
||||
CommandHistory history = input.history;
|
||||
CommandHistory history = input!.history;
|
||||
|
||||
Keys key = e.KeyCode;
|
||||
bool handled = false;
|
||||
@ -154,5 +155,4 @@ namespace Query.Controls {
|
||||
return wasClamped;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,10 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Query.Core {
|
||||
sealed class CommandHistory {
|
||||
private readonly List<string> queries = new List<string>();
|
||||
private readonly List<string> results = new List<string>();
|
||||
namespace Query.Core;
|
||||
|
||||
sealed class CommandHistory {
|
||||
private readonly List<string> queries = [];
|
||||
private readonly List<string> results = [];
|
||||
|
||||
public IList<string> Queries => queries;
|
||||
|
||||
@ -21,5 +22,4 @@ namespace Query.Core {
|
||||
queries.Clear();
|
||||
results.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,12 +3,13 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Base;
|
||||
|
||||
namespace Query.Core {
|
||||
sealed class CommandProcessor {
|
||||
private readonly Dictionary<string, IApp> appNames = new Dictionary<string, IApp>(8);
|
||||
private readonly HashSet<IApp> appSet = new HashSet<IApp>();
|
||||
namespace Query.Core;
|
||||
|
||||
public Func<string, bool> SingleTokenProcessor { get; set; }
|
||||
sealed class CommandProcessor {
|
||||
private readonly Dictionary<string, IApp> appNames = new (8);
|
||||
private readonly HashSet<IApp> appSet = [];
|
||||
|
||||
public Func<string, bool> SingleTokenProcessor { get; init; }
|
||||
|
||||
public void AddApp<T>() where T : IApp, new() {
|
||||
IApp app = new T();
|
||||
@ -23,17 +24,16 @@ namespace Query.Core {
|
||||
cmd = cmd.ReplaceBrackets(match => Run(new Command(match.Groups[1].Value)));
|
||||
|
||||
string appName = cmd.PotentialAppName;
|
||||
IApp app;
|
||||
|
||||
if (appName != null && appNames.TryGetValue(appName.ToLowerInvariant(), out app)) {
|
||||
return app.ProcessCommand(new Command(cmd.Text.Substring(appName.Length + 1)));
|
||||
if (appName != null && appNames.TryGetValue(appName.ToLowerInvariant(), out IApp app)) {
|
||||
return app.ProcessCommand(new Command(cmd.Text[(appName.Length + 1)..]));
|
||||
}
|
||||
|
||||
if (cmd.IsSingleToken && SingleTokenProcessor != null && SingleTokenProcessor(cmd.Text)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var list = appSet.Select(iapp => new { App = iapp, Confidence = iapp.GetConfidence(cmd) }).OrderByDescending(obj => obj.Confidence).Where(obj => obj.Confidence != MatchConfidence.None).ToList();
|
||||
var list = appSet.Select(iapp => new { App = iapp, Confidence = iapp.GetConfidence(cmd) }).OrderByDescending(static obj => obj.Confidence).Where(static obj => obj.Confidence != MatchConfidence.None).ToList();
|
||||
|
||||
if (list.Count == 0) {
|
||||
throw new CommandException("Could not find any suitable app, please write the app name and press Up Arrow.");
|
||||
@ -42,7 +42,7 @@ namespace Query.Core {
|
||||
app = list[0].App;
|
||||
}
|
||||
else {
|
||||
List<IApp> plausible = new List<IApp> { list[0].App };
|
||||
List<IApp> plausible = [list[0].App];
|
||||
MatchConfidence topConfidence = list[0].Confidence;
|
||||
|
||||
for (int index = 1; index < list.Count; index++) {
|
||||
@ -55,11 +55,10 @@ namespace Query.Core {
|
||||
app = plausible.First();
|
||||
}
|
||||
else {
|
||||
throw new CommandException("Command is ambiguous, please write the app name and press Up Arrow. Suggested apps: " + string.Join(", ", plausible.Select(iapp => iapp.RecognizedNames.First())));
|
||||
throw new CommandException("Command is ambiguous, please write the app name and press Up Arrow. Suggested apps: " + string.Join(", ", plausible.Select(static iapp => iapp.RecognizedNames.First())));
|
||||
}
|
||||
}
|
||||
|
||||
return app.ProcessCommand(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,8 +2,9 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Query.Core {
|
||||
sealed class KeyboardHook {
|
||||
namespace Query.Core;
|
||||
|
||||
sealed class KeyboardHook {
|
||||
public event EventHandler Triggered;
|
||||
|
||||
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
|
||||
@ -30,10 +31,10 @@ namespace Query.Core {
|
||||
}
|
||||
|
||||
private IntPtr KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam) {
|
||||
if (wParam == (IntPtr) NativeMethods.WM_KEYDOWN) {
|
||||
if (wParam == NativeMethods.WM_KEYDOWN) {
|
||||
Keys key = (Keys) Marshal.ReadInt32(lParam);
|
||||
|
||||
if ((key == Keys.LWin || key == Keys.RWin) && Control.ModifierKeys.HasFlag(Keys.Control)) {
|
||||
if (key is Keys.LWin or Keys.RWin && Control.ModifierKeys.HasFlag(Keys.Control)) {
|
||||
Triggered?.Invoke(this, EventArgs.Empty);
|
||||
return NativeMethods.HookHandled;
|
||||
}
|
||||
@ -45,9 +46,8 @@ namespace Query.Core {
|
||||
private static class NativeMethods {
|
||||
public const int WH_KEYBOARD_LL = 13;
|
||||
public const int WM_KEYDOWN = 0x0100;
|
||||
public const int WM_KEYUP = 0x0101;
|
||||
|
||||
public static readonly IntPtr HookHandled = new IntPtr(-1);
|
||||
public static readonly IntPtr HookHandled = new (-1);
|
||||
|
||||
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
@ -60,5 +60,4 @@ namespace Query.Core {
|
||||
[DllImport("user32.dll")]
|
||||
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
2
Query/MainForm.Designer.cs
generated
2
Query/MainForm.Designer.cs
generated
@ -1,5 +1,5 @@
|
||||
namespace Query {
|
||||
partial class MainForm {
|
||||
sealed partial class MainForm {
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
|
@ -5,8 +5,9 @@ using Base;
|
||||
using Query.Controls;
|
||||
using Query.Core;
|
||||
|
||||
namespace Query {
|
||||
partial class MainForm : Form {
|
||||
namespace Query;
|
||||
|
||||
sealed partial class MainForm : Form {
|
||||
private readonly CommandProcessor processor;
|
||||
private readonly CommandHistory history;
|
||||
|
||||
@ -142,5 +143,4 @@ namespace Query {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,13 +1,13 @@
|
||||
using System;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace Query {
|
||||
static class Program {
|
||||
namespace Query;
|
||||
|
||||
static class Program {
|
||||
[STAThread]
|
||||
private static void Main() {
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new MainForm());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user