[PTRun]Add setting for different trigonometric units in Calculator (#36717)

* Added angle units to PowerToys Run Calculator plugin.

* Update Resources.resx

* Added GitHub SpellCheck rule for 'gradians'.

---------

Co-authored-by: Heiko <61519853+htcfreek@users.noreply.github.com>
This commit is contained in:
Nathan Gill 2025-01-17 16:13:41 +00:00 коммит произвёл GitHub
Родитель 1aaf764c14
Коммит 458e5c5509
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
7 изменённых файлов: 250 добавлений и 106 удалений

107
.github/actions/spell-check/expect.txt поставляемый
Просмотреть файл

@ -4,12 +4,10 @@ abgr
ABlocked ABlocked
ABOUTBOX ABOUTBOX
Abug Abug
accctrl
Acceleratorkeys Acceleratorkeys
ACCEPTFILES ACCEPTFILES
ACCESSDENIED ACCESSDENIED
ACCESSTOKEN ACCESSTOKEN
aclapi
AClient AClient
AColumn AColumn
acrt acrt
@ -54,12 +52,9 @@ APIENTRY
APIIs APIIs
Apm Apm
APPBARDATA APPBARDATA
appdata
APPEXECLINK APPEXECLINK
Appium
APPLICATIONFRAMEHOST APPLICATIONFRAMEHOST
appmanifest appmanifest
appmodel
APPNAME APPNAME
appref appref
appsettings appsettings
@ -83,11 +78,7 @@ ASSOCSTR
ASYNCWINDOWPLACEMENT ASYNCWINDOWPLACEMENT
ASYNCWINDOWPOS ASYNCWINDOWPOS
atl atl
atlbase
atlcom
atleast atleast
atlfile
atlstr
ATRIOX ATRIOX
aumid aumid
Authenticode Authenticode
@ -135,7 +126,6 @@ bmi
bms bms
BNumber BNumber
BODGY BODGY
bootstrapper
BOOTSTRAPPERINSTALLFOLDER BOOTSTRAPPERINSTALLFOLDER
bostrot bostrot
BOTTOMALIGN BOTTOMALIGN
@ -163,7 +153,6 @@ CALG
callbackptr callbackptr
calpwstr calpwstr
Cangjie Cangjie
caniuse
CANRENAME CANRENAME
CAPTUREBLT CAPTUREBLT
CAPTURECHANGED CAPTURECHANGED
@ -178,11 +167,9 @@ CDeclaration
CDEF CDEF
CElems CElems
CENTERALIGN CENTERALIGN
ceq
certlm certlm
certmgr certmgr
cfp cfp
cguid
CHANGECBCHAIN CHANGECBCHAIN
changecursor changecursor
CHILDACTIVATE CHILDACTIVATE
@ -207,19 +194,16 @@ CLSCTX
Clusion Clusion
cmder cmder
CMDNOTFOUNDMODULEINTERFACE CMDNOTFOUNDMODULEINTERFACE
Cmds
CMIC CMIC
CMINVOKECOMMANDINFO CMINVOKECOMMANDINFO
CMINVOKECOMMANDINFOEX CMINVOKECOMMANDINFOEX
CMock CMock
CMONITORS CMONITORS
cmph cmph
cne
CNF CNF
coclass coclass
codereview codereview
Codespaces Codespaces
codicon
COINIT COINIT
colorconv colorconv
colorformat colorformat
@ -231,18 +215,12 @@ comdef
comdlg comdlg
comexp comexp
cominterop cominterop
commandline
commctrl
commdlg
compmgmt compmgmt
COMPOSITIONFULL COMPOSITIONFULL
comutil
CONFIGW CONFIGW
CONFLICTINGMODIFIERKEY CONFLICTINGMODIFIERKEY
CONFLICTINGMODIFIERSHORTCUT CONFLICTINGMODIFIERSHORTCUT
CONOUT CONOUT
consts
contentdialog
contentfiles contentfiles
CONTEXTHELP CONTEXTHELP
CONTEXTMENUHANDLER CONTEXTMENUHANDLER
@ -257,7 +235,6 @@ countof
cph cph
cplusplus cplusplus
CPower CPower
cppwinrt
createdump createdump
CREATEPROCESS CREATEPROCESS
CREATESCHEDULEDTASK CREATESCHEDULEDTASK
@ -267,8 +244,6 @@ CRECT
CRH CRH
critsec critsec
Crossdevice Crossdevice
CRSEL
crx
CSearch CSearch
CSettings CSettings
cso cso
@ -306,11 +281,8 @@ DBLEPSILON
DCapture DCapture
DCBA DCBA
DCOM DCOM
dcommon
dcomp
DComposition DComposition
DCR DCR
DCs
ddd ddd
DDEIf DDEIf
DDevice DDevice
@ -345,7 +317,6 @@ DESIGNINFO
DESKTOPABSOLUTEEDITING DESKTOPABSOLUTEEDITING
DESKTOPABSOLUTEPARSING DESKTOPABSOLUTEPARSING
desktopshorcutinstalled desktopshorcutinstalled
desktopwindowxamlsource
devblogs devblogs
devdocs devdocs
devenum devenum
@ -353,7 +324,6 @@ devmgmt
DEVMODE DEVMODE
DEVMODEW DEVMODEW
DEVMON DEVMON
devpkey
DEVSOURCE DEVSOURCE
DGR DGR
DIALOGEX DIALOGEX
@ -423,8 +393,6 @@ DWORDLONG
dworigin dworigin
dwrite dwrite
dxgi dxgi
dxgidebug
dxgiformat
easeofaccess easeofaccess
ecount ecount
EData EData
@ -434,15 +402,12 @@ EDITSHORTCUTS
EDITTEXT EDITTEXT
EFile EFile
ekus ekus
emmintrin
Emoji
ENABLEDELAYEDEXPANSION ENABLEDELAYEDEXPANSION
ENABLEDPOPUP ENABLEDPOPUP
ENABLETAB ENABLETAB
ENABLETEMPLATE ENABLETEMPLATE
encodedlaunch encodedlaunch
encryptor encryptor
endpointvolume
ENDSESSION ENDSESSION
ENSUREVISIBLE ENSUREVISIBLE
ENTERSIZEMOVE ENTERSIZEMOVE
@ -466,7 +431,6 @@ eula
eurochange eurochange
eventlog eventlog
eventvwr eventvwr
evntrace
evt evt
EWXFORCE EWXFORCE
EWXFORCEIFHUNG EWXFORCEIFHUNG
@ -478,7 +442,6 @@ examplehandler
examplepowertoy examplepowertoy
EXAND EXAND
EXCLUDEFROMCAPTURE EXCLUDEFROMCAPTURE
exdisp
executionpolicy executionpolicy
exename exename
EXITSIZEMOVE EXITSIZEMOVE
@ -541,7 +504,6 @@ frm
Froml Froml
FROMTOUCH FROMTOUCH
fsmgmt fsmgmt
Functiondiscoverykeys
FZE FZE
gacutil gacutil
Gaeilge Gaeilge
@ -576,10 +538,10 @@ gpo
GPOCA GPOCA
gpp gpp
gpu gpu
gradians
GSM GSM
gtm gtm
guiddata guiddata
guiddef
GUITHREADINFO GUITHREADINFO
GValue GValue
gwl gwl
@ -626,7 +588,6 @@ Hif
HIMAGELIST HIMAGELIST
himl himl
hinst hinst
hinstance
HIWORD HIWORD
HKCC HKCC
HKCOMB HKCOMB
@ -659,7 +620,6 @@ hrgn
hsb hsb
HSCROLL HSCROLL
hsi hsi
hstring
HTCLIENT HTCLIENT
hthumbnail hthumbnail
HTOUCHINPUT HTOUCHINPUT
@ -737,14 +697,12 @@ installscopeperuser
INSTALLSTARTMENUSHORTCUT INSTALLSTARTMENUSHORTCUT
INSTALLSTATE INSTALLSTATE
Inste Inste
Intelli
Interlop Interlop
INTRESOURCE INTRESOURCE
INVALIDARG INVALIDARG
invalidoperatioexception invalidoperatioexception
ipcmanager ipcmanager
IPREVIEW IPREVIEW
ipreviewhandlervisualssetfont
irprops irprops
isbi isbi
ISearch ISearch
@ -769,7 +727,6 @@ jpe
jpnime jpnime
Jsons Jsons
jsonval jsonval
junja
jxr jxr
keybd keybd
KEYBDDATA KEYBDDATA
@ -787,7 +744,6 @@ keyvault
KILLFOCUS KILLFOCUS
killrunner killrunner
kmph kmph
Knownfolders
KSPROPERTY KSPROPERTY
Kybd Kybd
lastcodeanalysissucceeded lastcodeanalysissucceeded
@ -818,7 +774,6 @@ LIVEZOOM
lld lld
LLKH LLKH
llkhf llkhf
lmcons
LMEM LMEM
LMENU LMENU
lnks lnks
@ -861,7 +816,6 @@ lprc
LPSAFEARRAY LPSAFEARRAY
lpstr lpstr
lpsz lpsz
lpt
LPTHREAD LPTHREAD
LPTOP LPTOP
lptpm lptpm
@ -920,18 +874,13 @@ MERGECOPY
MERGEPAINT MERGEPAINT
Metadatas Metadatas
metafile metafile
mfapi
mfc mfc
mfidl
mfobjects
mfplat mfplat
mftransform
Mgmt Mgmt
mic mic
midl midl
mii mii
mindaro mindaro
Minimatch
Minimizable Minimizable
MINIMIZEBOX MINIMIZEBOX
MINIMIZEEND MINIMIZEEND
@ -946,10 +895,8 @@ mlcfg
mmc mmc
mmcexe mmcexe
MMdd MMdd
mmdeviceapi
mmi mmi
mmsys mmsys
mmsystem
mockapi mockapi
MODALFRAME MODALFRAME
MODESPRUNED MODESPRUNED
@ -976,7 +923,6 @@ mscorlib
msctls msctls
msdata msdata
MSDL MSDL
msedge
MSGFLT MSGFLT
msiexec msiexec
MSIFASTINSTALL MSIFASTINSTALL
@ -1030,7 +976,6 @@ netframework
netsetup netsetup
netsh netsh
newcolor newcolor
newdev
NEWDIALOGSTYLE NEWDIALOGSTYLE
NEWFILE NEWFILE
newitem newitem
@ -1057,7 +1002,6 @@ NOCOPYBITS
NOCOPYSECURITYATTRIBS NOCOPYSECURITYATTRIBS
NOCRLF NOCRLF
nodeca nodeca
nodoc
NODRAWCAPTION NODRAWCAPTION
NODRAWICON NODRAWICON
NOINHERITLAYOUT NOINHERITLAYOUT
@ -1095,7 +1039,6 @@ NOTIFICATIONSDLL
NOTIFYICONDATA NOTIFYICONDATA
NOTIFYICONDATAW NOTIFYICONDATAW
NOTIMPL NOTIMPL
notlike
NOTOPMOST NOTOPMOST
NOTRACK NOTRACK
NOTSRCCOPY NOTSRCCOPY
@ -1108,15 +1051,12 @@ NResize
nsunt nsunt
NTAPI NTAPI
ntdll ntdll
ntfs
NTSTATUS NTSTATUS
NTSYSAPI NTSYSAPI
NULLCURSOR NULLCURSOR
nullonfailure nullonfailure
numberbox numberbox
nwc nwc
Objbase
objidl
ocr ocr
Ocrsettings Ocrsettings
odbccp odbccp
@ -1148,7 +1088,6 @@ osvi
OUTOFCONTEXT OUTOFCONTEXT
outpin outpin
Outptr Outptr
outputtype
outsettings outsettings
OVERLAPPEDWINDOW OVERLAPPEDWINDOW
overlaywindow overlaywindow
@ -1167,7 +1106,6 @@ PARENTRELATIVEPARSING
parray parray
PARTIALCONFIRMATIONDIALOGTITLE PARTIALCONFIRMATIONDIALOGTITLE
PATCOPY PATCOPY
pathcch
PATHMUSTEXIST PATHMUSTEXIST
PATINVERT PATINVERT
PATPAINT PATPAINT
@ -1255,7 +1193,6 @@ pptal
ppv ppv
prc prc
Prefixer Prefixer
Preinstalled
prependpath prependpath
prevhost prevhost
previewer previewer
@ -1272,7 +1209,6 @@ prm
proactively proactively
PROCESSENTRY PROCESSENTRY
PROCESSKEY PROCESSKEY
processthreadsapi
PROCESSTRACE PROCESSTRACE
procmon procmon
PRODEXT PRODEXT
@ -1282,7 +1218,6 @@ programdata
projectname projectname
PROPBAG PROPBAG
PROPERTYKEY PROPERTYKEY
propkey
PROPVARIANT PROPVARIANT
propvarutil propvarutil
PRTL PRTL
@ -1346,7 +1281,6 @@ rectp
RECTSOURCE RECTSOURCE
recyclebin recyclebin
Redist Redist
redistributable
reencode reencode
reencoded reencoded
REFCLSID REFCLSID
@ -1375,10 +1309,8 @@ remoteip
Removelnk Removelnk
renamable renamable
RENAMEONCOLLISION RENAMEONCOLLISION
Renamer
reparented reparented
reparenting reparenting
reparse
reportfileaccesses reportfileaccesses
requery requery
requerying requerying
@ -1390,7 +1322,6 @@ RESIZETOFIT
resmimetype resmimetype
RESOURCEID RESOURCEID
RESTORETOMAXIMIZED RESTORETOMAXIMIZED
restrictederrorinfo
resultlist resultlist
RETURNONLYFSDIRS RETURNONLYFSDIRS
RGBQUAD RGBQUAD
@ -1405,7 +1336,6 @@ riid
ringbuffer ringbuffer
RKey RKey
RNumber RNumber
roadmap
rop rop
ROUNDSMALL ROUNDSMALL
rpcrt rpcrt
@ -1418,14 +1348,12 @@ rstringalpha
rstringdigit rstringdigit
RTB RTB
RTLREADING RTLREADING
ruleset
runas runas
rundll rundll
rungameid rungameid
RUNLEVEL RUNLEVEL
runtimeclass runtimeclass
runtimepack runtimepack
runtimes
ruuid ruuid
rvm rvm
rwin rwin
@ -1486,21 +1414,17 @@ SHCNE
SHCNF SHCNF
SHCONTF SHCONTF
Shcore Shcore
shellapi
SHELLDETAILS SHELLDETAILS
SHELLDLL SHELLDLL
shellex shellex
SHELLEXECUTEINFO SHELLEXECUTEINFO
SHELLEXECUTEINFOW SHELLEXECUTEINFOW
shellscalingapi
SHFILEINFO SHFILEINFO
SHFILEOPSTRUCT SHFILEOPSTRUCT
SHGDN SHGDN
SHGDNF SHGDNF
SHGFI SHGFI
shinfo shinfo
shldisp
shlobj
shlwapi shlwapi
shmem shmem
SHNAMEMAPPING SHNAMEMAPPING
@ -1628,7 +1552,6 @@ SVGIn
SVGIO SVGIO
svgz svgz
SVSI SVSI
SWC
SWFO SWFO
SWP SWP
SWRESTORE SWRESTORE
@ -1652,8 +1575,6 @@ SYSMENU
SYSTEMAPPS SYSTEMAPPS
SYSTEMMODAL SYSTEMMODAL
SYSTEMTIME SYSTEMTIME
tailwindcss
tapp
TApplication TApplication
TApplied TApplied
targ targ
@ -1694,7 +1615,6 @@ THH
THICKFRAME THICKFRAME
THISCOMPONENT THISCOMPONENT
THotkey THotkey
thumbcache
TILEDWINDOW TILEDWINDOW
TILLSON TILLSON
timedate timedate
@ -1708,17 +1628,14 @@ tkconverters
TLayout TLayout
tlb tlb
tlbimp tlbimp
tlhelp
TMPVAR TMPVAR
TNP TNP
Toolhelp Toolhelp
toolkitconverters toolkitconverters
Toolset
toolwindow toolwindow
TOPDOWNDIB TOPDOWNDIB
TOUCHEVENTF TOUCHEVENTF
TOUCHINPUT TOUCHINPUT
touchpad
TRACEHANDLE TRACEHANDLE
tracelogging tracelogging
tracerpt tracerpt
@ -1731,7 +1648,6 @@ triaging
trl trl
trx trx
tsa tsa
Tsd
TServer TServer
tstoi tstoi
TStr TStr
@ -1761,15 +1677,11 @@ UNCPRIORITY
UNDNAME UNDNAME
unhiding unhiding
UNICODETEXT UNICODETEXT
uninstantiated
uniquifier
Uniquifies Uniquifies
unitconverter unitconverter
unittests unittests
Unknwn
UNLEN UNLEN
UNORM UNORM
unregistering
unremapped unremapped
unvirtualized unvirtualized
unwide unwide
@ -1783,11 +1695,9 @@ updown
UPGRADINGPRODUCTCODE UPGRADINGPRODUCTCODE
Uptool Uptool
urld urld
urlmon
Usb Usb
USEDEFAULT USEDEFAULT
USEFILEATTRIBUTES USEFILEATTRIBUTES
USERDATA
USESHOWWINDOW USESHOWWINDOW
USESTDHANDLES USESTDHANDLES
USRDLL USRDLL
@ -1814,7 +1724,6 @@ vdupq
VERBSONLY VERBSONLY
VERBW VERBW
VERIFYCONTEXT VERIFYCONTEXT
verrsrc
VERSIONINFO VERSIONINFO
VERTRES VERTRES
VERTSIZE VERTSIZE
@ -1862,7 +1771,6 @@ WANTPALM
wbem wbem
WBounds WBounds
Wca Wca
wcautil
WCE WCE
wcex wcex
WClass WClass
@ -1884,10 +1792,7 @@ wifi
wil wil
winapi winapi
winappsdk winappsdk
wincodec
Wincodecsdk
wincolor wincolor
windef
windir windir
WINDOWCREATED WINDOWCREATED
WINDOWEDGE WINDOWEDGE
@ -1896,18 +1801,12 @@ WINDOWNAME
WINDOWPLACEMENT WINDOWPLACEMENT
WINDOWPOSCHANGED WINDOWPOSCHANGED
WINDOWPOSCHANGING WINDOWPOSCHANGING
windowsapp
WINDOWSBUILDNUMBER WINDOWSBUILDNUMBER
windowssearch windowssearch
windowssettings windowssettings
WINDOWSTYLES WINDOWSTYLES
WINDOWSTYLESICON WINDOWSTYLESICON
windowsx
winerror
WINEVENT WINEVENT
winevt
winexe
winforms
winget winget
wingetcreate wingetcreate
Winhook Winhook
@ -1918,9 +1817,7 @@ WINNT
winres winres
winrt winrt
winsdk winsdk
winsdkver
winsta winsta
winternl
WINTHRESHOLD WINTHRESHOLD
WINVER WINVER
winxamlmanager winxamlmanager
@ -1966,14 +1863,12 @@ wrl
wscui wscui
wsf wsf
wsh wsh
wsl
wstr wstr
wsz wsz
WTA WTA
WTNCA WTNCA
wtoi wtoi
WTS WTS
wtsapi
WTSAT WTSAT
Wubi Wubi
WVC WVC

Просмотреть файл

@ -279,5 +279,67 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator.UnitTests
Assert.IsNotNull(result); Assert.IsNotNull(result);
Assert.AreEqual(expectedResult, result.Result); Assert.AreEqual(expectedResult, result.Result);
} }
[DataTestMethod]
[DataRow("sin(90)", "sin((pi / 180) * (90))")]
[DataRow("arcsin(0.5)", "(180 / pi) * (arcsin(0.5))")]
[DataRow("sin(sin(30))", "sin((pi / 180) * (sin((pi / 180) * (30))))")]
[DataRow("cos(tan(45))", "cos((pi / 180) * (tan((pi / 180) * (45))))")]
[DataRow("arctan(sin(30))", "(180 / pi) * (arctan(sin((pi / 180) * (30))))")]
[DataRow("sin(cos(tan(30)))", "sin((pi / 180) * (cos((pi / 180) * (tan((pi / 180) * (30))))))")]
[DataRow("sin(arcsin(0.5))", "sin((pi / 180) * ((180 / pi) * (arcsin(0.5))))")]
[DataRow("sin(30) + cos(60)", "sin((pi / 180) * (30)) + cos((pi / 180) * (60))")]
[DataRow("sin(30 + 15)", "sin((pi / 180) * (30 + 15))")]
[DataRow("sin(45) * cos(45) - tan(30)", "sin((pi / 180) * (45)) * cos((pi / 180) * (45)) - tan((pi / 180) * (30))")]
[DataRow("arcsin(arccos(0.5))", "(180 / pi) * (arcsin((180 / pi) * (arccos(0.5))))")]
[DataRow("sin(sin(sin(30)))", "sin((pi / 180) * (sin((pi / 180) * (sin((pi / 180) * (30))))))")]
[DataRow("log(10)", "log(10)")]
[DataRow("sin(30) + pi", "sin((pi / 180) * (30)) + pi")]
[DataRow("sin(-30)", "sin((pi / 180) * (-30))")]
[DataRow("sin((30))", "sin((pi / 180) * ((30)))")]
[DataRow("arcsin(1) * 2", "(180 / pi) * (arcsin(1)) * 2")]
[DataRow("cos(1/2)", "cos((pi / 180) * (1/2))")]
[DataRow("sin ( 90 )", "sin ((pi / 180) * ( 90 ))")]
[DataRow("cos(arcsin(sin(45)))", "cos((pi / 180) * ((180 / pi) * (arcsin(sin((pi / 180) * (45))))))")]
public void UpdateTrigFunctions_Degrees(string input, string expectedResult)
{
// Call UpdateTrigFunctions in degrees mode
string result = CalculateHelper.UpdateTrigFunctions(input, CalculateEngine.TrigMode.Degrees);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(expectedResult, result);
}
[DataTestMethod]
[DataRow("sin(90)", "sin((pi / 200) * (90))")]
[DataRow("arcsin(0.5)", "(200 / pi) * (arcsin(0.5))")]
[DataRow("sin(sin(30))", "sin((pi / 200) * (sin((pi / 200) * (30))))")]
[DataRow("cos(tan(45))", "cos((pi / 200) * (tan((pi / 200) * (45))))")]
[DataRow("arctan(sin(30))", "(200 / pi) * (arctan(sin((pi / 200) * (30))))")]
[DataRow("sin(cos(tan(30)))", "sin((pi / 200) * (cos((pi / 200) * (tan((pi / 200) * (30))))))")]
[DataRow("sin(arcsin(0.5))", "sin((pi / 200) * ((200 / pi) * (arcsin(0.5))))")]
[DataRow("sin(30) + cos(60)", "sin((pi / 200) * (30)) + cos((pi / 200) * (60))")]
[DataRow("sin(30 + 15)", "sin((pi / 200) * (30 + 15))")]
[DataRow("sin(45) * cos(45) - tan(30)", "sin((pi / 200) * (45)) * cos((pi / 200) * (45)) - tan((pi / 200) * (30))")]
[DataRow("arcsin(arccos(0.5))", "(200 / pi) * (arcsin((200 / pi) * (arccos(0.5))))")]
[DataRow("sin(sin(sin(30)))", "sin((pi / 200) * (sin((pi / 200) * (sin((pi / 200) * (30))))))")]
[DataRow("log(10)", "log(10)")]
[DataRow("sin(30) + pi", "sin((pi / 200) * (30)) + pi")]
[DataRow("sin(-30)", "sin((pi / 200) * (-30))")]
[DataRow("sin((30))", "sin((pi / 200) * ((30)))")]
[DataRow("arcsin(1) * 2", "(200 / pi) * (arcsin(1)) * 2")]
[DataRow("cos(1/2)", "cos((pi / 200) * (1/2))")]
[DataRow("sin ( 90 )", "sin ((pi / 200) * ( 90 ))")]
[DataRow("cos(arcsin(sin(45)))", "cos((pi / 200) * ((200 / pi) * (arcsin(sin((pi / 200) * (45))))))")]
public void UpdateTrigFunctions_Gradians(string input, string expectedResult)
{
// Call UpdateTrigFunctions in gradians mode
string result = CalculateHelper.UpdateTrigFunctions(input, CalculateEngine.TrigMode.Gradians);
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(expectedResult, result);
}
} }
} }

Просмотреть файл

@ -23,6 +23,13 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
public const int RoundingDigits = 10; public const int RoundingDigits = 10;
public enum TrigMode
{
Radians,
Degrees,
Gradians,
}
/// <summary> /// <summary>
/// Interpret /// Interpret
/// </summary> /// </summary>
@ -52,6 +59,9 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
input = CalculateHelper.FixHumanMultiplicationExpressions(input); input = CalculateHelper.FixHumanMultiplicationExpressions(input);
// Modify trig functions depending on angle unit setting
input = CalculateHelper.UpdateTrigFunctions(input, Main.GetTrigMode());
var result = _magesEngine.Interpret(input); var result = _magesEngine.Interpret(input);
// This could happen for some incorrect queries, like pi(2) // This could happen for some incorrect queries, like pi(2)

Просмотреть файл

@ -25,6 +25,11 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
@")+$", @")+$",
RegexOptions.Compiled); RegexOptions.Compiled);
private const string DegToRad = "(pi / 180) * ";
private const string GradToRad = "(pi / 200) * ";
private const string RadToDeg = "(180 / pi) * ";
private const string RadToGrad = "(200 / pi) * ";
public static bool InputValid(string input) public static bool InputValid(string input)
{ {
if (string.IsNullOrWhiteSpace(input)) if (string.IsNullOrWhiteSpace(input))
@ -204,5 +209,86 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
return output; return output;
} }
// Gets the index of the closing bracket of a function
private static int FindClosingBracketIndex(string input, int start)
{
int bracketCount = 0; // Set count to zero
for (int i = start; i < input.Length; i++)
{
if (input[i] == '(')
{
bracketCount++;
}
else if (input[i] == ')')
{
bracketCount--;
if (bracketCount == 0)
{
return i;
}
}
}
return -1; // Unmatched brackets
}
private static string ModifyTrigFunction(string input, string function, string modification)
{
// Get the RegEx pattern to match, depending on whether the function is inverse or normal
string pattern = function.StartsWith("arc", StringComparison.Ordinal) ? string.Empty : @"(?<!c)";
pattern += $@"{function}\s*\(";
int index = 0; // Index for match to ensure that the same match is not found twice
Regex regex = new Regex(pattern);
Match match;
while ((match = regex.Match(input, index)).Success)
{
index = match.Index + match.Groups[0].Length + modification.Length; // Get the next index to look from for further matches
int endIndex = FindClosingBracketIndex(input, match.Index + match.Groups[0].Length - 1); // Find the index of the closing bracket of the function
// If no valid bracket index was found, try the next match
if (endIndex == -1)
{
continue;
}
string argument = input.Substring(match.Index + match.Groups[0].Length, endIndex - (match.Index + match.Groups[0].Length)); // Extract the argument between the brackets
string replaced = function.StartsWith("arc", StringComparison.Ordinal) ? $"{modification}({match.Groups[0].Value}{argument}))" : $"{match.Groups[0].Value}{modification}({argument}))"; // The string to substitute in, handles differing formats of inverse functions
input = input.Remove(match.Index, endIndex - match.Index + 1); // Remove the match from the input
input = input.Insert(match.Index, replaced); // Substitute with the new string
}
return input;
}
public static string UpdateTrigFunctions(string input, CalculateEngine.TrigMode mode)
{
string modifiedInput = input;
if (mode == CalculateEngine.TrigMode.Degrees)
{
modifiedInput = ModifyTrigFunction(modifiedInput, "sin", DegToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "cos", DegToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "tan", DegToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "arcsin", RadToDeg);
modifiedInput = ModifyTrigFunction(modifiedInput, "arccos", RadToDeg);
modifiedInput = ModifyTrigFunction(modifiedInput, "arctan", RadToDeg);
}
else if (mode == CalculateEngine.TrigMode.Gradians)
{
modifiedInput = ModifyTrigFunction(modifiedInput, "sin", GradToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "cos", GradToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "tan", GradToRad);
modifiedInput = ModifyTrigFunction(modifiedInput, "arcsin", RadToGrad);
modifiedInput = ModifyTrigFunction(modifiedInput, "arccos", RadToGrad);
modifiedInput = ModifyTrigFunction(modifiedInput, "arctan", RadToGrad);
}
return modifiedInput;
}
} }
} }

Просмотреть файл

@ -21,6 +21,7 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
private const string InputUseEnglishFormat = nameof(InputUseEnglishFormat); private const string InputUseEnglishFormat = nameof(InputUseEnglishFormat);
private const string OutputUseEnglishFormat = nameof(OutputUseEnglishFormat); private const string OutputUseEnglishFormat = nameof(OutputUseEnglishFormat);
private const string ReplaceInput = nameof(ReplaceInput); private const string ReplaceInput = nameof(ReplaceInput);
private const string TrigMode = nameof(TrigMode);
private static readonly CalculateEngine CalculateEngine = new CalculateEngine(); private static readonly CalculateEngine CalculateEngine = new CalculateEngine();
@ -31,6 +32,7 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
private bool _inputUseEnglishFormat; private bool _inputUseEnglishFormat;
private bool _outputUseEnglishFormat; private bool _outputUseEnglishFormat;
private bool _replaceInput; private bool _replaceInput;
private static CalculateEngine.TrigMode _trigMode;
public string Name => Resources.wox_plugin_calculator_plugin_name; public string Name => Resources.wox_plugin_calculator_plugin_name;
@ -67,6 +69,20 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
DisplayDescription = Resources.wox_plugin_calculator_replace_input_description, DisplayDescription = Resources.wox_plugin_calculator_replace_input_description,
Value = true, Value = true,
}, },
new PluginAdditionalOption
{
Key = TrigMode,
DisplayLabel = Resources.wox_plugin_calculator_trig_unit_mode,
DisplayDescription = Resources.wox_plugin_calculator_trig_unit_mode_description,
PluginOptionType = PluginAdditionalOption.AdditionalOptionType.Combobox,
ComboBoxValue = (int)CalculateEngine.TrigMode.Radians,
ComboBoxItems =
[
new KeyValuePair<string, string>(Resources.wox_plugin_calculator_trig_unit_radians, "0"),
new KeyValuePair<string, string>(Resources.wox_plugin_calculator_trig_unit_degrees, "1"),
new KeyValuePair<string, string>(Resources.wox_plugin_calculator_trig_unit_gradians, "2"),
],
},
}; };
public List<Result> Query(Query query) public List<Result> Query(Query query)
@ -183,6 +199,7 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
var inputUseEnglishFormat = false; var inputUseEnglishFormat = false;
var outputUseEnglishFormat = false; var outputUseEnglishFormat = false;
var replaceInput = true; var replaceInput = true;
var trigMode = CalculateEngine.TrigMode.Radians;
if (settings != null && settings.AdditionalOptions != null) if (settings != null && settings.AdditionalOptions != null)
{ {
@ -194,11 +211,20 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator
var optionReplaceInput = settings.AdditionalOptions.FirstOrDefault(x => x.Key == ReplaceInput); var optionReplaceInput = settings.AdditionalOptions.FirstOrDefault(x => x.Key == ReplaceInput);
replaceInput = optionReplaceInput?.Value ?? replaceInput; replaceInput = optionReplaceInput?.Value ?? replaceInput;
var optionTrigMode = settings.AdditionalOptions.FirstOrDefault(x => x.Key == TrigMode);
trigMode = (CalculateEngine.TrigMode)int.Parse(optionTrigMode.ComboBoxValue.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
} }
_inputUseEnglishFormat = inputUseEnglishFormat; _inputUseEnglishFormat = inputUseEnglishFormat;
_outputUseEnglishFormat = outputUseEnglishFormat; _outputUseEnglishFormat = outputUseEnglishFormat;
_replaceInput = replaceInput; _replaceInput = replaceInput;
_trigMode = trigMode;
}
public static CalculateEngine.TrigMode GetTrigMode()
{
return _trigMode;
} }
public void Dispose() public void Dispose()

Просмотреть файл

@ -203,5 +203,50 @@ namespace Microsoft.PowerToys.Run.Plugin.Calculator.Properties {
return ResourceManager.GetString("wox_plugin_calculator_replace_input_description", resourceCulture); return ResourceManager.GetString("wox_plugin_calculator_replace_input_description", resourceCulture);
} }
} }
/// <summary>
/// Looks up a localized string similar to Degrees.
/// </summary>
public static string wox_plugin_calculator_trig_unit_degrees {
get {
return ResourceManager.GetString("wox_plugin_calculator_trig_unit_degrees", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Gradians.
/// </summary>
public static string wox_plugin_calculator_trig_unit_gradians {
get {
return ResourceManager.GetString("wox_plugin_calculator_trig_unit_gradians", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Trigonometry Unit.
/// </summary>
public static string wox_plugin_calculator_trig_unit_mode {
get {
return ResourceManager.GetString("wox_plugin_calculator_trig_unit_mode", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Specifies the angle unit to use for trigonometry operations..
/// </summary>
public static string wox_plugin_calculator_trig_unit_mode_description {
get {
return ResourceManager.GetString("wox_plugin_calculator_trig_unit_mode_description", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Radians.
/// </summary>
public static string wox_plugin_calculator_trig_unit_radians {
get {
return ResourceManager.GetString("wox_plugin_calculator_trig_unit_radians", resourceCulture);
}
}
} }
} }

Просмотреть файл

@ -167,4 +167,24 @@
<data name="wox_plugin_calculator_replace_input_description" xml:space="preserve"> <data name="wox_plugin_calculator_replace_input_description" xml:space="preserve">
<value>When using direct activation, appending '=' to the expression will replace the input with the calculated result (e.g. '=5*3-2=' will change the query to '=13').</value> <value>When using direct activation, appending '=' to the expression will replace the input with the calculated result (e.g. '=5*3-2=' will change the query to '=13').</value>
</data> </data>
<data name="wox_plugin_calculator_trig_unit_mode" xml:space="preserve">
<value>Trigonometry Unit</value>
<comment>Title text for trig unit mode.</comment>
</data>
<data name="wox_plugin_calculator_trig_unit_mode_description" xml:space="preserve">
<value>Specifies the angle unit to use for trigonometry operations</value>
<comment>Description text for trig mode setting.</comment>
</data>
<data name="wox_plugin_calculator_trig_unit_radians" xml:space="preserve">
<value>Radians</value>
<comment>Text for angle unit.</comment>
</data>
<data name="wox_plugin_calculator_trig_unit_degrees" xml:space="preserve">
<value>Degrees</value>
<comment>Text to use for angle unit.</comment>
</data>
<data name="wox_plugin_calculator_trig_unit_gradians" xml:space="preserve">
<value>Gradians</value>
<comment>Text for angle unit.</comment>
</data>
</root> </root>