1
0
mirror of https://github.com/chylex/Query.git synced 2025-06-08 17:34:03 +02:00

Fix Rider inspections

This commit is contained in:
chylex 2024-07-29 18:09:24 +02:00
parent 356d66121b
commit 4e950b73a3
Signed by: chylex
GPG Key ID: 4DE42C8F19A80548
35 changed files with 1429 additions and 1450 deletions

View File

@ -6,19 +6,29 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Base; using Base;
namespace AppCalc { 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);
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", "calc",
"calculate", "calculate",
"calculator" "calculator"
}; ];
public MatchConfidence GetConfidence(Command cmd) { public MatchConfidence GetConfidence(Command cmd) {
return RegexValidCharacters.IsMatch(cmd.Text) ? MatchConfidence.Possible : MatchConfidence.None; return RegexValidCharacters.IsMatch(cmd.Text) ? MatchConfidence.Possible : MatchConfidence.None;
@ -31,7 +41,7 @@ namespace AppCalc {
private static string ParseAndProcessExpression(string text) { private static string ParseAndProcessExpression(string text) {
// text = RegexBalancedParentheses.Replace(text, match => " "+ParseAndProcessExpression(match.Groups[1].Value)+" "); // parens are handled as apps // 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); string[] tokens = expression.Split(SplitSpace, StringSplitOptions.RemoveEmptyEntries);
decimal result = ProcessExpression(tokens); decimal result = ProcessExpression(tokens);
@ -44,7 +54,7 @@ namespace AppCalc {
bool hasDecimalPoint = decimal.Round(result) != result; bool hasDecimalPoint = decimal.Round(result) != result;
if (res.Length == 30 && hasDecimalPoint && res.IndexOf('.') < 15) { // Length 30 uses all available bytes 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); Match match = RegexRecurringDecimal.Match(res);
@ -58,7 +68,7 @@ namespace AppCalc {
build.Append(repeating); build.Append(repeating);
} while (build.Length + repeating.Length <= res.Length); } 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) { else if (hasDecimalPoint) {
@ -210,23 +220,21 @@ namespace AppCalc {
string str = token; string str = token;
if (str.StartsWith("-.")) { if (str.StartsWith("-.")) {
str = "-0" + str.Substring(1); str = "-0" + str[1..];
} }
else if (str[0] == '.') { else if (str[0] == '.') {
str = "0" + str; str = "0" + str;
} }
if (str.EndsWith("...")) { if (str.EndsWith("...")) {
string truncated = str.Substring(0, str.Length - 3); string truncated = str[..^3];
if (truncated.IndexOf('.') != -1) { if (truncated.Contains('.')) {
str = truncated; str = truncated;
} }
} }
decimal value; if (decimal.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out decimal value)) {
if (decimal.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out value)) {
if (value.ToString(CultureInfo.InvariantCulture) != str) { if (value.ToString(CultureInfo.InvariantCulture) != str) {
throw new CommandException("Provided number is outside of decimal range: " + token); throw new CommandException("Provided number is outside of decimal range: " + token);
} }
@ -238,4 +246,3 @@ namespace AppCalc {
} }
} }
} }
}

View File

@ -1,28 +1,18 @@
namespace AppCalc { namespace AppCalc;
static class Operators { static class Operators {
internal static readonly string[] With2Operands = { "+", "-", "*", "/", "%", "^" }; internal static readonly string[] With2Operands = [ "+", "-", "*", "/", "%", "^" ];
internal static int GetPrecedence(string token) { internal static int GetPrecedence(string token) {
switch (token) { return token switch {
case "^": "^" => 4,
return 4; "*" or "/" or "%" => 3,
"+" or "-" => 2,
case "*": _ => 1
case "/": };
case "%":
return 3;
case "+":
case "-":
return 2;
default:
return 1;
}
} }
internal static bool IsRightAssociative(string token) { internal static bool IsRightAssociative(string token) {
return token == "^"; return token == "^";
} }
} }
}

View File

@ -4,9 +4,10 @@ using AppConv.General;
using AppConv.Units; using AppConv.Units;
using Base; using Base;
namespace AppConv { namespace AppConv;
public sealed class App : IApp { public sealed class App : IApp {
private static readonly IUnitType[] Processors = { private static readonly IUnitType[] Processors = [
new Temperature(), new Temperature(),
new Weight(), new Weight(),
new Length(), new Length(),
@ -15,19 +16,19 @@ namespace AppConv {
new Angle(), new Angle(),
new Storage(), new Storage(),
new Radix() new Radix()
}; ];
public string[] RecognizedNames => new string[] { public string[] RecognizedNames => [
"conv", "conv",
"convert" "convert"
}; ];
public MatchConfidence GetConfidence(Command cmd) { 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) { 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 src = data[0].Trim();
string dst = data[1].Trim(); string dst = data[1].Trim();
@ -46,4 +47,3 @@ namespace AppConv {
return result; return result;
} }
} }
}

View File

@ -3,7 +3,8 @@ using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
namespace AppConv.General { namespace AppConv.General;
abstract class DecimalUnitConverterBase<T> : IUnitType where T : struct { abstract class DecimalUnitConverterBase<T> : IUnitType where T : struct {
internal sealed class DecimalFuncMap : Dictionary<T, Func<decimal, decimal>> { internal sealed class DecimalFuncMap : Dictionary<T, Func<decimal, decimal>> {
public DecimalFuncMap() {} public DecimalFuncMap() {}
@ -95,13 +96,11 @@ namespace AppConv.General {
} }
if (index == 0) { 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 decimal value)) {
if (decimal.TryParse(src, NumberStyle, CultureInfo.InvariantCulture, out value)) {
result = Format(Convert(value, pairs[0].Value, pairs[1].Value)); result = Format(Convert(value, pairs[0].Value, pairs[1].Value));
return true; return true;
} }
@ -111,4 +110,3 @@ namespace AppConv.General {
} }
} }
} }
}

View File

@ -1,17 +1,17 @@
using System; using System;
namespace AppConv.General { namespace AppConv.General;
abstract class DecimalUnitConverterSimple<T> : DecimalUnitConverterBase<T> where T : struct { abstract class DecimalUnitConverterSimple<T> : DecimalUnitConverterBase<T> where T : struct {
// ReSharper disable once StaticMemberInGenericType // ReSharper disable once StaticMemberInGenericType
private static readonly Func<decimal, decimal> FuncNoChange = val => val; private static readonly Func<decimal, decimal> FuncNoChange = static val => val;
private readonly NameMap UnitNames = new NameMap(); private readonly DecimalFuncMap MapFrom = new ();
private readonly DecimalFuncMap MapFrom = new DecimalFuncMap(); private readonly DecimalFuncMap MapTo = new ();
private readonly DecimalFuncMap MapTo = new DecimalFuncMap();
private int invalidUnitObject = -1; private int invalidUnitObject = -1;
protected sealed override NameMap Names => UnitNames; protected sealed override NameMap Names { get ; } = new ();
protected sealed override DecimalFuncMap ConvertFrom => MapFrom; protected sealed override DecimalFuncMap ConvertFrom => MapFrom;
@ -23,7 +23,7 @@ namespace AppConv.General {
protected void AddUnit(T unitObject, params string[] names) { protected void AddUnit(T unitObject, params string[] names) {
foreach (string name in names) { foreach (string name in names) {
UnitNames.Add(name, unitObject); Names.Add(name, unitObject);
} }
ConvertFrom.Add(unitObject, FuncNoChange); ConvertFrom.Add(unitObject, FuncNoChange);
@ -43,4 +43,3 @@ namespace AppConv.General {
return (int) (object) value == invalidUnitObject; return (int) (object) value == invalidUnitObject;
} }
} }
}

View File

@ -1,5 +1,5 @@
namespace AppConv.General { namespace AppConv.General;
interface IUnitType { interface IUnitType {
bool TryProcess(string src, string dst, out string result); bool TryProcess(string src, string dst, out string result);
} }
}

View File

@ -1,8 +1,9 @@
using System; using System;
using AppConv.General; using AppConv.General;
namespace AppConv.Units { namespace AppConv.Units;
class Angle : DecimalUnitConverterSimple<Angle.Units> {
sealed class Angle : DecimalUnitConverterSimple<Angle.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Degree, Degree,
@ -25,4 +26,3 @@ namespace AppConv.Units {
// TODO convert degree notation 15°24'9" // TODO convert degree notation 15°24'9"
} }
}

View File

@ -1,7 +1,8 @@
using AppConv.General; using AppConv.General;
namespace AppConv.Units { namespace AppConv.Units;
class Area : DecimalUnitConverterSimple<Area.Units> {
sealed class Area : DecimalUnitConverterSimple<Area.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
SquareMM, SquareMM,
@ -55,4 +56,3 @@ namespace AppConv.Units {
SetInvalidUnitObject(Units.Invalid); SetInvalidUnitObject(Units.Invalid);
} }
} }
}

View File

@ -4,8 +4,9 @@ using System.Linq;
using AppConv.General; using AppConv.General;
using AppConv.Utils; using AppConv.Utils;
namespace AppConv.Units { namespace AppConv.Units;
class Length : DecimalUnitConverterSimple<Length.Units> {
sealed class Length : DecimalUnitConverterSimple<Length.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Meter, Meter,
@ -15,8 +16,10 @@ namespace AppConv.Units {
Mile Mile
} }
private static readonly string[] NamesInch = { "in", "inch", "inches", "\"", "''" }; private static readonly string[] NamesInch = [ "in", "inch", "inches", "\"", "''" ];
private static readonly string[] NamesFoot = { "ft", "foot", "feet", "'" }; private static readonly string[] NamesFoot = [ "ft", "foot", "feet", "'" ];
private static readonly char[] Separator = [ ' ' ];
public Length() { public Length() {
AddUnit(Units.Meter, "m", "meter", "metre", "meters", "metres"); AddUnit(Units.Meter, "m", "meter", "metre", "meters", "metres");
@ -32,7 +35,7 @@ namespace AppConv.Units {
SetInvalidUnitObject(Units.Invalid); 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) { protected override string ProcessSrc(string src) {
@ -41,7 +44,7 @@ namespace AppConv.Units {
updatedStr = updatedStr.Replace("&", " "); updatedStr = updatedStr.Replace("&", " ");
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) { if (inchName == null) {
return src; return src;
@ -50,7 +53,7 @@ namespace AppConv.Units {
int inchIndex = src.IndexOf(inchName, StringComparison.OrdinalIgnoreCase); int inchIndex = src.IndexOf(inchName, StringComparison.OrdinalIgnoreCase);
updatedStr = updatedStr.Remove(inchIndex, inchName.Length).Insert(inchIndex, new string(' ', inchName.Length)); 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) { if (footName == null) {
return src; return src;
@ -59,14 +62,12 @@ namespace AppConv.Units {
int footIndex = updatedStr.IndexOf(footName, StringComparison.OrdinalIgnoreCase); int footIndex = updatedStr.IndexOf(footName, StringComparison.OrdinalIgnoreCase);
updatedStr = updatedStr.Remove(footIndex, footName.Length).Insert(footIndex, new string(' ', footName.Length)); 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]; decimal[] numbers = new decimal[2];
int numberIndex = 0; int numberIndex = 0;
foreach (string token in tokens) { foreach (string token in tokens) {
decimal number; if (decimal.TryParse(token.Trim(), NumberStyle, CultureInfo.InvariantCulture, out decimal number)) {
if (decimal.TryParse(token.Trim(), NumberStyle, CultureInfo.InvariantCulture, out number)) {
if (numberIndex < numbers.Length) { if (numberIndex < numbers.Length) {
numbers[numberIndex++] = number; numbers[numberIndex++] = number;
} }
@ -86,4 +87,3 @@ namespace AppConv.Units {
return srcInches + srcFeet * 12M + " in"; return srcInches + srcFeet * 12M + " in";
} }
} }
}

View File

@ -5,9 +5,10 @@ using AppConv.General;
using AppConv.Utils; using AppConv.Utils;
using Base; using Base;
namespace AppConv.Units { namespace AppConv.Units;
class Radix : IUnitType {
private static readonly Dictionary<string, int> RadixDescriptions = new Dictionary<string, int> { sealed class Radix : IUnitType {
private static readonly Dictionary<string, int> RadixDescriptions = new () {
{ "UNARY", 1 }, { "UNARY", 1 },
{ "BINARY", 2 }, { "BINARY", 2 },
{ "BIN", 2 }, { "BIN", 2 },
@ -37,17 +38,12 @@ namespace AppConv.Units {
} }
public bool TryProcess(string src, string dst, out string result) { public bool TryProcess(string src, string dst, out string result) {
int targetBase; if (!RadixDescriptions.TryGetValue(dst.ToUpperInvariant(), out int targetBase)) {
if (!RadixDescriptions.TryGetValue(dst.ToUpperInvariant(), out targetBase)) {
result = string.Empty; result = string.Empty;
return false; return false;
} }
string contents; if (!ParseSrc(src, out string contents, out int sourceBase)) {
int sourceBase;
if (!ParseSrc(src, out contents, out sourceBase)) {
result = string.Empty; result = string.Empty;
return false; return false;
} }
@ -77,7 +73,7 @@ namespace AppConv.Units {
} }
private static bool ParseSrc(string src, out string sourceContent, out int sourceBase) { 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; sourceContent = src;
sourceBase = 10; sourceBase = 10;
return true; return true;
@ -86,13 +82,13 @@ namespace AppConv.Units {
string upper = src.ToUpperInvariant(); string upper = src.ToUpperInvariant();
if (upper.StartsWith("0X")) { if (upper.StartsWith("0X")) {
sourceContent = upper.Substring(2); sourceContent = upper[2..];
sourceBase = 16; sourceBase = 16;
return true; return true;
} }
if (upper.StartsWith("0B")) { if (upper.StartsWith("0B")) {
sourceContent = upper.Substring(2); sourceContent = upper[2..];
sourceBase = 2; sourceBase = 2;
return true; return true;
} }
@ -105,12 +101,12 @@ namespace AppConv.Units {
foreach (KeyValuePair<string, int> kvp in RadixDescriptions) { foreach (KeyValuePair<string, int> kvp in RadixDescriptions) {
if (src.StartsWith(kvp.Key, StringComparison.InvariantCultureIgnoreCase)) { if (src.StartsWith(kvp.Key, StringComparison.InvariantCultureIgnoreCase)) {
sourceContent = src.Substring(kvp.Key.Length).Trim(); sourceContent = src[kvp.Key.Length..].Trim();
sourceBase = kvp.Value; sourceBase = kvp.Value;
return true; return true;
} }
else if (src.EndsWith(kvp.Key, StringComparison.InvariantCultureIgnoreCase)) { 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; sourceBase = kvp.Value;
return true; return true;
} }
@ -121,4 +117,3 @@ namespace AppConv.Units {
return false; return false;
} }
} }
}

View File

@ -1,15 +1,18 @@
using System; using System;
using System.Diagnostics.CodeAnalysis;
using AppConv.General; using AppConv.General;
using AppConv.Utils; using AppConv.Utils;
namespace AppConv.Units { namespace AppConv.Units;
class Storage : DecimalUnitConverterSimple<Storage.Units> {
sealed class Storage : DecimalUnitConverterSimple<Storage.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Byte, Byte,
Bit Bit
} }
[SuppressMessage("ReSharper", "PossibleLossOfFraction")]
public Storage() { public Storage() {
AddUnit(Units.Byte, "B", "byte", "bytes"); AddUnit(Units.Byte, "B", "byte", "bytes");
AddUnit(Units.Bit, "b", "bit", "bits"); AddUnit(Units.Bit, "b", "bit", "bits");
@ -19,13 +22,12 @@ namespace AppConv.Units {
SetInvalidUnitObject(Units.Invalid); SetInvalidUnitObject(Units.Invalid);
var bitConversionProperties = new SI.ExtededProperties { var bitConversionProperties = new SI.ExtededProperties {
FactorPredicate = factor => factor > 0 && factor % 3 == 0, FactorPredicate = static factor => factor > 0 && factor % 3 == 0,
FromFunctionGenerator = exponent => () => (decimal) Math.Pow(1024, -(int) (exponent / 3)), FromFunctionGenerator = static exponent => () => (decimal) Math.Pow(1024, -(exponent / 3)),
ToFunctionGenerator = exponent => () => (decimal) Math.Pow(1024, (int) (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(Units.Byte, [ "B" ], [ "byte", "bytes" ], ConvertFrom, ConvertTo, Names, bitConversionProperties);
SI.AddSupportCustom(typeof(Units), Units.Bit, new [] { "b" }, new [] { "bit", "bits" }, ConvertFrom, ConvertTo, Names, bitConversionProperties); SI.AddSupportCustom(Units.Bit, [ "b" ], [ "bit", "bits" ], ConvertFrom, ConvertTo, Names, bitConversionProperties);
}
} }
} }

View File

@ -1,10 +1,10 @@
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using AppConv.General; using AppConv.General;
using Base.Utils;
namespace AppConv.Units { namespace AppConv.Units;
class Temperature : DecimalUnitConverterBase<Temperature.Units> {
sealed partial class Temperature : DecimalUnitConverterBase<Temperature.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Celsius, Celsius,
@ -17,7 +17,7 @@ namespace AppConv.Units {
Romer Romer
} }
private static readonly NameMap UnitNames = new NameMap(21) { private static readonly NameMap UnitNames = new (21) {
{ "C", Units.Celsius }, { "C", Units.Celsius },
{ "Celsius", Units.Celsius }, { "Celsius", Units.Celsius },
{ "K", Units.Kelvin }, { "K", Units.Kelvin },
@ -41,29 +41,32 @@ namespace AppConv.Units {
{ "Rømer", Units.Romer } { "Rømer", Units.Romer }
}; };
private static readonly DecimalFuncMap FromCelsius = new DecimalFuncMap(8) { private static readonly DecimalFuncMap FromCelsius = new (8) {
{ Units.Celsius, val => val }, { Units.Celsius, static val => val },
{ Units.Kelvin, val => val + 273.15M }, { Units.Kelvin, static val => val + 273.15M },
{ Units.Fahrenheit, val => val * 1.8M + 32M }, { Units.Fahrenheit, static val => val * 1.8M + 32M },
{ Units.Rankine, val => (val + 273.15M) * 1.8M }, { Units.Rankine, static val => (val + 273.15M) * 1.8M },
{ Units.Delisle, val => (100M - val) * 1.5M }, { Units.Delisle, static val => (100M - val) * 1.5M },
{ Units.Newton, val => val * 0.33M }, { Units.Newton, static val => val * 0.33M },
{ Units.Reaumur, val => val * 0.8M }, { Units.Reaumur, static val => val * 0.8M },
{ Units.Romer, val => val * 0.525M + 7.5M } { Units.Romer, static val => val * 0.525M + 7.5M }
}; };
private static readonly DecimalFuncMap ToCelsius = new DecimalFuncMap(8) { private static readonly DecimalFuncMap ToCelsius = new (8) {
{ Units.Celsius, val => val }, { Units.Celsius, static val => val },
{ Units.Kelvin, val => val - 273.15M }, { Units.Kelvin, static val => val - 273.15M },
{ Units.Fahrenheit, val => (val - 32M) * 5M / 9M }, { Units.Fahrenheit, static val => (val - 32M) * 5M / 9M },
{ Units.Rankine, val => (val - 491.67M) * 5M / 9M }, { Units.Rankine, static val => (val - 491.67M) * 5M / 9M },
{ Units.Delisle, val => 100M - val * 2M / 3M }, { Units.Delisle, static val => 100M - val * 2M / 3M },
{ Units.Newton, val => val * 100M / 33M }, { Units.Newton, static val => val * 100M / 33M },
{ Units.Reaumur, val => val * 1.25M }, { Units.Reaumur, static val => val * 1.25M },
{ Units.Romer, val => (val - 7.5M) * 40M / 21M } { 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; protected override NameMap Names => UnitNames;
@ -87,4 +90,3 @@ namespace AppConv.Units {
return value == Units.Invalid; return value == Units.Invalid;
} }
} }
}

View File

@ -1,8 +1,9 @@
using AppConv.General; using AppConv.General;
using AppConv.Utils; using AppConv.Utils;
namespace AppConv.Units { namespace AppConv.Units;
class Volume : DecimalUnitConverterSimple<Volume.Units> {
sealed class Volume : DecimalUnitConverterSimple<Volume.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Liter, Liter,
@ -28,7 +29,6 @@ namespace AppConv.Units {
SetInvalidUnitObject(Units.Invalid); 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);
}
} }
} }

View File

@ -1,8 +1,9 @@
using AppConv.General; using AppConv.General;
using AppConv.Utils; using AppConv.Utils;
namespace AppConv.Units { namespace AppConv.Units;
class Weight : DecimalUnitConverterSimple<Weight.Units> {
sealed class Weight : DecimalUnitConverterSimple<Weight.Units> {
internal enum Units { internal enum Units {
Invalid = 0, Invalid = 0,
Gram, Gram,
@ -23,7 +24,6 @@ namespace AppConv.Units {
SetInvalidUnitObject(Units.Invalid); 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);
}
} }
} }

View File

@ -3,21 +3,22 @@ using System.Globalization;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace AppConv.Utils { namespace AppConv.Utils;
static class RadixConversion { static class RadixConversion {
private const string Characters = "0123456789ABCDEF"; private const string Characters = "0123456789ABCDEF";
public static bool IsBaseValid(int checkedBase) { 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) { public static bool IsNumberValid(string contents, int checkedBase) {
if (checkedBase == 1) { if (checkedBase == 1) {
return contents.All(chr => chr == '1'); return contents.All(static chr => chr == '1');
} }
if (IsBaseValid(checkedBase)) { 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; return false;
@ -68,11 +69,10 @@ namespace AppConv.Utils {
int index = (int) (wip % toBase); int index = (int) (wip % toBase);
converted.Insert(0, Characters[index]); converted.Insert(0, Characters[index]);
wip = wip / toBase; wip /= toBase;
} }
return converted.Insert(0, Characters[(int) wip]).ToString(); return converted.Insert(0, Characters[(int) wip]).ToString();
} }
} }
} }
}

View File

@ -2,9 +2,10 @@
using System.Collections.Generic; using System.Collections.Generic;
using AppConv.General; using AppConv.General;
namespace AppConv.Utils { namespace AppConv.Utils;
static class SI { static class SI {
private static readonly List<Tuple<string, string, int>> Factors = new List<Tuple<string, string, int>> { private static readonly List<Tuple<string, string, int>> Factors = [
new Tuple<string, string, int>("yotta", "Y", 24), new Tuple<string, string, int>("yotta", "Y", 24),
new Tuple<string, string, int>("zetta", "Z", 21), new Tuple<string, string, int>("zetta", "Z", 21),
new Tuple<string, string, int>("exa", "E", 18), 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>("atto", "a", -18),
new Tuple<string, string, int>("zepto", "z", -21), new Tuple<string, string, int>("zepto", "z", -21),
new Tuple<string, string, int>("yocto", "y", -24) 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; int enumCounter = 1000 + Factors.Count * (int) (object) unitObject;
Func<decimal, decimal> convertFrom = funcFrom[unitObject]; Func<decimal, decimal> convertFrom = funcFrom[unitObject];
Func<decimal, decimal> convertTo = funcTo[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++; T enumObject = (T) (object) enumCounter++;
int exponent = factor.Item3;
foreach (string unitShortName in unitShortNames) { foreach (string unitShortName in unitShortNames) {
nameMap.Add(factor.Item2 + unitShortName, enumObject); nameMap.Add(unitShotNamePrefix + unitShortName, enumObject);
} }
foreach (string unitLongName in unitLongNames) { 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)); 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; int enumCounter = 1000 + Factors.Count * (int) (object) unitObject;
Func<decimal, decimal> convertFrom = funcFrom[unitObject]; Func<decimal, decimal> convertFrom = funcFrom[unitObject];
Func<decimal, decimal> convertTo = funcTo[unitObject]; Func<decimal, decimal> convertTo = funcTo[unitObject];
foreach (Tuple<string, string, int> factor in Factors) { foreach ((string unitLongNamePrefix, string unitShortNamePrefix, int exponent) in Factors) {
if (extendedProps.FactorPredicate != null && !extendedProps.FactorPredicate(factor.Item3)) { if (extendedProps.FactorPredicate != null && !extendedProps.FactorPredicate(exponent)) {
continue; continue;
} }
T enumObject = (T) (object) enumCounter++; T enumObject = (T) (object) enumCounter++;
int exponent = factor.Item3;
foreach (string unitShortName in unitShortNames) { foreach (string unitShortName in unitShortNames) {
nameMap.Add(factor.Item2 + unitShortName, enumObject); nameMap.Add(unitShortNamePrefix + unitShortName, enumObject);
} }
foreach (string unitLongName in unitLongNames) { foreach (string unitLongName in unitLongNames) {
nameMap.Add(factor.Item1 + unitLongName, enumObject); nameMap.Add(unitLongNamePrefix + unitLongName, enumObject);
} }
Func<decimal> genFrom = extendedProps.FromFunctionGenerator(exponent); Func<decimal> genFrom = extendedProps.FromFunctionGenerator(exponent);
@ -80,10 +79,9 @@ namespace AppConv.Utils {
} }
} }
internal class ExtededProperties { internal sealed class ExtededProperties {
public Predicate<int> FactorPredicate { get; set; } public Predicate<int> FactorPredicate { get; init; }
public Func<int, Func<decimal>> FromFunctionGenerator { get; set; } public Func<int, Func<decimal>> FromFunctionGenerator { get; init; }
public Func<int, Func<decimal>> ToFunctionGenerator { get; set; } public Func<int, Func<decimal>> ToFunctionGenerator { get; init; }
}
} }
} }

View File

@ -1,18 +1,19 @@
using System.Collections.Generic; using System.Collections.Generic;
using Base; using Base;
namespace AppMeme { namespace AppMeme;
public sealed class App : IApp { public sealed class App : IApp {
private static readonly Dictionary<string, string> Map = new Dictionary<string, string> { private static readonly Dictionary<string, string> Map = new () {
{ "shrug", @"¯\_(ツ)_/¯" }, { "shrug", @"¯\_(ツ)_/¯" },
{ "lenny", @"( ͡° ͜ʖ ͡°)" }, { "lenny", @"( ͡° ͜ʖ ͡°)" },
{ "flip", @"(╯°□°)╯︵ ┻━┻" }, { "flip", @"(╯°□°)╯︵ ┻━┻" },
{ "tableflip", @"(╯°□°)╯︵ ┻━┻" } { "tableflip", @"(╯°□°)╯︵ ┻━┻" }
}; };
public string[] RecognizedNames => new string[] { public string[] RecognizedNames => [
"meme" "meme"
}; ];
public MatchConfidence GetConfidence(Command cmd) { public MatchConfidence GetConfidence(Command cmd) {
return Map.ContainsKey(cmd.Text) ? MatchConfidence.Full : MatchConfidence.None; return Map.ContainsKey(cmd.Text) ? MatchConfidence.Full : MatchConfidence.None;
@ -22,4 +23,3 @@ namespace AppMeme {
return Map[cmd.Text]; return Map[cmd.Text];
} }
} }
}

View File

@ -2,18 +2,19 @@
using AppSys.Handlers; using AppSys.Handlers;
using Base; using Base;
namespace AppSys { namespace AppSys;
public sealed class App : IApp { public sealed class App : IApp {
private static readonly IHandler[] Handlers = { private static readonly IHandler[] Handlers = [
new HandlerProcesses(), new HandlerProcesses(),
new HandlerApps() new HandlerApps()
}; ];
public string[] RecognizedNames => new string[] { public string[] RecognizedNames => [
"sys", "sys",
"os", "os",
"win" "win"
}; ];
public MatchConfidence GetConfidence(Command cmd) { public MatchConfidence GetConfidence(Command cmd) {
return Handlers.Any(handler => handler.Matches(cmd)) ? MatchConfidence.Full : MatchConfidence.None; return Handlers.Any(handler => handler.Matches(cmd)) ? MatchConfidence.Full : MatchConfidence.None;
@ -23,4 +24,3 @@ namespace AppSys {
return Handlers.First(handler => handler.Matches(cmd)).Handle(cmd); return Handlers.First(handler => handler.Matches(cmd)).Handle(cmd);
} }
} }
}

View File

@ -4,11 +4,12 @@ using System.Diagnostics;
using System.IO; using System.IO;
using Base; using Base;
namespace AppSys.Handlers { namespace AppSys.Handlers;
class HandlerApps : IHandler {
sealed class HandlerApps : IHandler {
private static readonly string PathSystem = Environment.GetFolderPath(Environment.SpecialFolder.System); 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 { "audio", new ProcessStartInfo {
FileName = Path.Combine(PathSystem, "control.exe"), 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" }, { "sounds", "audio" },
{ "apps", "programs" }, { "apps", "programs" },
{ "appwiz", "programs" }, { "appwiz", "programs" },
@ -47,9 +48,7 @@ namespace AppSys.Handlers {
} }
public string Handle(Command cmd) { public string Handle(Command cmd) {
string key; if (!Substitutions.TryGetValue(cmd.Text, out string key)) {
if (!Substitutions.TryGetValue(cmd.Text, out key)) {
key = cmd.Text; key = cmd.Text;
} }
@ -58,4 +57,3 @@ namespace AppSys.Handlers {
return null; return null;
} }
} }
}

View File

@ -3,19 +3,20 @@ using System.Diagnostics;
using System.Text; using System.Text;
using Base; using Base;
namespace AppSys.Handlers { namespace AppSys.Handlers;
class HandlerProcesses : IHandler {
sealed class HandlerProcesses : IHandler {
public bool Matches(Command cmd) { public bool Matches(Command cmd) {
return cmd.Text.StartsWith("kill ", StringComparison.InvariantCultureIgnoreCase); return cmd.Text.StartsWith("kill ", StringComparison.InvariantCultureIgnoreCase);
} }
public string Handle(Command cmd) { 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; int succeeded = 0, failed = 0;
foreach (string processName in processNames) { foreach (string processName in processNames) {
try { 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) { foreach (Process process in processes) {
try { try {
@ -46,4 +47,3 @@ namespace AppSys.Handlers {
return build.Append('.').ToString(); return build.Append('.').ToString();
} }
} }
}

View File

@ -1,8 +1,8 @@
using Base; using Base;
namespace AppSys { namespace AppSys;
interface IHandler { interface IHandler {
bool Matches(Command cmd); bool Matches(Command cmd);
string Handle(Command cmd); string Handle(Command cmd);
} }
}

View File

@ -2,12 +2,13 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Base.Utils; using Base.Utils;
namespace Base { 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);
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 { public string PotentialAppName {
get { get {
@ -17,7 +18,7 @@ namespace Base {
return null; return null;
} }
string firstToken = Text.Substring(0, firstSpace); string firstToken = Text[..firstSpace];
if (!firstToken.All(char.IsLetter)) { if (!firstToken.All(char.IsLetter)) {
return null; return null;
@ -27,14 +28,9 @@ namespace Base {
} }
} }
public bool IsSingleToken => Text.IndexOf(' ') == -1; public bool IsSingleToken => !Text.Contains(' ');
public Command(string text) {
Text = text;
}
public Command ReplaceBrackets(MatchEvaluator evaluator) { public Command ReplaceBrackets(MatchEvaluator evaluator) {
return new Command(RegexBalancedParentheses.Replace(RegexBalancedBrackets.Replace(Text, evaluator), evaluator)); return new Command(RegexBalancedParentheses.Replace(RegexBalancedBrackets.Replace(Text, evaluator), evaluator));
} }
} }
}

View File

@ -1,11 +1,7 @@
using System; using System;
namespace Base { namespace Base;
public class CommandEventArgs : EventArgs {
public Command Command { get; private set; }
public CommandEventArgs(string text) { public sealed class CommandEventArgs(string text) : EventArgs {
Command = new Command(text); public Command Command { get; private set; } = new (text);
}
}
} }

View File

@ -1,8 +1,8 @@
using System; using System;
namespace Base { namespace Base;
public class CommandException : Exception {
public sealed class CommandException : Exception {
public CommandException(string message) : base(message) {} public CommandException(string message) : base(message) {}
public CommandException(string message, Exception innerException) : base(message, innerException) {} public CommandException(string message, Exception innerException) : base(message, innerException) {}
} }
}

View File

@ -1,8 +1,8 @@
namespace Base { namespace Base;
public interface IApp { public interface IApp {
string[] RecognizedNames { get; } string[] RecognizedNames { get; }
MatchConfidence GetConfidence(Command cmd); MatchConfidence GetConfidence(Command cmd);
string ProcessCommand(Command cmd); string ProcessCommand(Command cmd);
} }
}

View File

@ -1,8 +1,8 @@
namespace Base { namespace Base;
public enum MatchConfidence { public enum MatchConfidence {
None = 0, None = 0,
Low = 1, Low = 1,
Possible = 2, Possible = 2,
Full = 3 Full = 3
} }
}

View File

@ -1,23 +1,23 @@
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Base.Utils { namespace Base.Utils;
public static class RegexUtils {
public static readonly RegexOptions Text = RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled;
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() return new StringBuilder()
.Append(escapedStart) .Append(escapedStart)
.Append(@"((?>[^") .Append("((?>[^")
.Append(escapedStart) .Append(escapedStart)
.Append(escapedEnd) .Append(escapedEnd)
.Append(@"]+|") .Append("]+|")
.Append(escapedStart) .Append(escapedStart)
.Append(@"(?<n>)|") .Append("(?<n>)|")
.Append(escapedEnd) .Append(escapedEnd)
.Append(@"(?<-n>))+(?(n)(?!)))") .Append("(?<-n>))+(?(n)(?!)))")
.Append(escapedEnd) .Append(escapedEnd)
.ToString(); .ToString();
} }
} }
}

View File

@ -2,7 +2,8 @@
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
namespace Query.Controls { namespace Query.Controls;
sealed partial class QueryHistoryLog : UserControl { sealed partial class QueryHistoryLog : UserControl {
public enum EntryType { public enum EntryType {
UserInput, UserInput,
@ -11,7 +12,7 @@ namespace Query.Controls {
Error 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.UserInput, Color.FromArgb(160, 160, 160) },
{ EntryType.CommandResult, Color.FromArgb(240, 240, 240) }, { EntryType.CommandResult, Color.FromArgb(240, 240, 240) },
{ EntryType.Information, Color.FromArgb(160, 255, 140) }, { EntryType.Information, Color.FromArgb(160, 255, 140) },
@ -43,4 +44,3 @@ namespace Query.Controls {
container.Controls.Clear(); container.Controls.Clear();
} }
} }
}

View File

@ -5,7 +5,8 @@ using System.Windows.Forms;
using Base; using Base;
using Query.Core; using Query.Core;
namespace Query.Controls { namespace Query.Controls;
sealed partial class QueryTextBox : UserControl { sealed partial class QueryTextBox : UserControl {
public event EventHandler<CommandEventArgs> CommandRan; public event EventHandler<CommandEventArgs> CommandRan;
@ -39,7 +40,7 @@ namespace Query.Controls {
protected override void OnKeyDown(KeyEventArgs e) { protected override void OnKeyDown(KeyEventArgs e) {
QueryTextBox input = (QueryTextBox) Parent; QueryTextBox input = (QueryTextBox) Parent;
CommandHistory history = input.history; CommandHistory history = input!.history;
Keys key = e.KeyCode; Keys key = e.KeyCode;
bool handled = false; bool handled = false;
@ -155,4 +156,3 @@ namespace Query.Controls {
} }
} }
} }
}

View File

@ -1,9 +1,10 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace Query.Core { namespace Query.Core;
sealed class CommandHistory { sealed class CommandHistory {
private readonly List<string> queries = new List<string>(); private readonly List<string> queries = [];
private readonly List<string> results = new List<string>(); private readonly List<string> results = [];
public IList<string> Queries => queries; public IList<string> Queries => queries;
@ -22,4 +23,3 @@ namespace Query.Core {
results.Clear(); results.Clear();
} }
} }
}

View File

@ -3,12 +3,13 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Base; using Base;
namespace Query.Core { 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>();
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() { public void AddApp<T>() where T : IApp, new() {
IApp app = new T(); IApp app = new T();
@ -23,17 +24,16 @@ namespace Query.Core {
cmd = cmd.ReplaceBrackets(match => Run(new Command(match.Groups[1].Value))); cmd = cmd.ReplaceBrackets(match => Run(new Command(match.Groups[1].Value)));
string appName = cmd.PotentialAppName; string appName = cmd.PotentialAppName;
IApp app;
if (appName != null && appNames.TryGetValue(appName.ToLowerInvariant(), out app)) { if (appName != null && appNames.TryGetValue(appName.ToLowerInvariant(), out IApp app)) {
return app.ProcessCommand(new Command(cmd.Text.Substring(appName.Length + 1))); return app.ProcessCommand(new Command(cmd.Text[(appName.Length + 1)..]));
} }
if (cmd.IsSingleToken && SingleTokenProcessor != null && SingleTokenProcessor(cmd.Text)) { if (cmd.IsSingleToken && SingleTokenProcessor != null && SingleTokenProcessor(cmd.Text)) {
return null; 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) { if (list.Count == 0) {
throw new CommandException("Could not find any suitable app, please write the app name and press Up Arrow."); 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; app = list[0].App;
} }
else { else {
List<IApp> plausible = new List<IApp> { list[0].App }; List<IApp> plausible = [list[0].App];
MatchConfidence topConfidence = list[0].Confidence; MatchConfidence topConfidence = list[0].Confidence;
for (int index = 1; index < list.Count; index++) { for (int index = 1; index < list.Count; index++) {
@ -55,11 +55,10 @@ namespace Query.Core {
app = plausible.First(); app = plausible.First();
} }
else { 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); return app.ProcessCommand(cmd);
} }
} }
}

View File

@ -2,7 +2,8 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
namespace Query.Core { namespace Query.Core;
sealed class KeyboardHook { sealed class KeyboardHook {
public event EventHandler Triggered; public event EventHandler Triggered;
@ -30,10 +31,10 @@ namespace Query.Core {
} }
private IntPtr KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { 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); 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); Triggered?.Invoke(this, EventArgs.Empty);
return NativeMethods.HookHandled; return NativeMethods.HookHandled;
} }
@ -45,9 +46,8 @@ namespace Query.Core {
private static class NativeMethods { private static class NativeMethods {
public const int WH_KEYBOARD_LL = 13; public const int WH_KEYBOARD_LL = 13;
public const int WM_KEYDOWN = 0x0100; 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); public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
@ -61,4 +61,3 @@ namespace Query.Core {
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam); public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
} }
} }
}

View File

@ -1,5 +1,5 @@
namespace Query { namespace Query {
partial class MainForm { sealed partial class MainForm {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>

View File

@ -5,8 +5,9 @@ using Base;
using Query.Controls; using Query.Controls;
using Query.Core; using Query.Core;
namespace Query { namespace Query;
partial class MainForm : Form {
sealed partial class MainForm : Form {
private readonly CommandProcessor processor; private readonly CommandProcessor processor;
private readonly CommandHistory history; private readonly CommandHistory history;
@ -143,4 +144,3 @@ namespace Query {
} }
} }
} }
}

View File

@ -1,7 +1,8 @@
using System; using System;
using System.Windows.Forms; using System.Windows.Forms;
namespace Query { namespace Query;
static class Program { static class Program {
[STAThread] [STAThread]
private static void Main() { private static void Main() {
@ -10,4 +11,3 @@ namespace Query {
Application.Run(new MainForm()); Application.Run(new MainForm());
} }
} }
}