2020-09-10 05:01:30 +02:00
|
|
|
|
// Copyright (c) Microsoft Corporation
|
|
|
|
|
|
// The Microsoft Corporation licenses this file to you under the MIT license.
|
|
|
|
|
|
// See the LICENSE file in the project root for more information.
|
|
|
|
|
|
|
|
|
|
|
|
using System;
|
|
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
|
|
|
2021-01-20 11:38:52 +01:00
|
|
|
|
namespace Microsoft.PowerToys.Run.Plugin.Calculator
|
2020-09-10 05:01:30 +02:00
|
|
|
|
{
|
|
|
|
|
|
public static class CalculateHelper
|
|
|
|
|
|
{
|
|
|
|
|
|
private static readonly Regex RegValidExpressChar = new Regex(
|
|
|
|
|
|
@"^(" +
|
2021-06-22 08:54:28 -07:00
|
|
|
|
@"%|" +
|
2020-10-21 16:19:37 -07:00
|
|
|
|
@"ceil\s*\(|floor\s*\(|exp\s*\(|max\s*\(|min\s*\(|abs\s*\(|log\s*\(|ln\s*\(|sqrt\s*\(|pow\s*\(|" +
|
|
|
|
|
|
@"factorial\s*\(|sign\s*\(|round\s*\(|rand\s*\(|" +
|
|
|
|
|
|
@"sin\s*\(|cos\s*\(|tan\s*\(|arcsin\s*\(|arccos\s*\(|arctan\s*\(|" +
|
2021-01-15 16:05:56 +01:00
|
|
|
|
@"sinh\s*\(|cosh\s*\(|tanh\s*\(|arsinh\s*\(|arcosh\s*\(|artanh\s*\(|" +
|
2020-10-21 16:19:37 -07:00
|
|
|
|
@"pi|" +
|
2020-09-10 05:01:30 +02:00
|
|
|
|
@"==|~=|&&|\|\||" +
|
2021-12-13 17:01:12 +00:00
|
|
|
|
@"e|[0-9]|0x[0-9a-fA-F]+|0b[01]+|[\+\-\*\/\^\., ""]|[\(\)\|\!\[\]]" +
|
2020-09-10 05:01:30 +02:00
|
|
|
|
@")+$", RegexOptions.Compiled);
|
|
|
|
|
|
|
|
|
|
|
|
public static bool InputValid(string input)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(input))
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new ArgumentNullException(paramName: nameof(input));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2021-12-02 15:07:47 +01:00
|
|
|
|
bool singleDigitFactorial = input.EndsWith("!", StringComparison.InvariantCulture);
|
|
|
|
|
|
if (input.Length <= 2 && !singleDigitFactorial)
|
2020-09-10 05:01:30 +02:00
|
|
|
|
{
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (!RegValidExpressChar.IsMatch(input))
|
|
|
|
|
|
{
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if (!BracketHelper.IsBracketComplete(input))
|
|
|
|
|
|
{
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-10-21 16:19:37 -07:00
|
|
|
|
// If the input ends with a binary operator then it is not a valid input to mages and the Interpret function would throw an exception.
|
|
|
|
|
|
string trimmedInput = input.TrimEnd();
|
|
|
|
|
|
if (trimmedInput.EndsWith('+') || trimmedInput.EndsWith('-') || trimmedInput.EndsWith('*') || trimmedInput.EndsWith('|') || trimmedInput.EndsWith('\\') || trimmedInput.EndsWith('^') || trimmedInput.EndsWith('=') || trimmedInput.EndsWith('&'))
|
|
|
|
|
|
{
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2020-09-10 05:01:30 +02:00
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|