-
-
Notifications
You must be signed in to change notification settings - Fork 615
Expand file tree
/
Copy pathMain.cs
More file actions
477 lines (409 loc) · 17.7 KB
/
Copy pathMain.cs
File metadata and controls
477 lines (409 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using Flow.Launcher.Plugin.Calculator.Storage;
using Flow.Launcher.Plugin.Calculator.ViewModels;
using Flow.Launcher.Plugin.Calculator.Views;
using Mages.Core;
namespace Flow.Launcher.Plugin.Calculator
{
public class Main : IPlugin, IPluginI18n, ISettingProvider
{
private static readonly Regex ThousandGroupRegex = MainRegexHelper.GetThousandGroupRegex();
private static readonly Regex NumberRegex = MainRegexHelper.GetNumberRegex();
private static readonly Regex PowRegex = MainRegexHelper.GetPowRegex();
private static readonly Regex LogRegex = MainRegexHelper.GetLogRegex();
private static readonly Regex LnRegex = MainRegexHelper.GetLnRegex();
private static readonly Regex FunctionRegex = MainRegexHelper.GetFunctionRegex();
private static Engine MagesEngine;
private const string Comma = ",";
private const string Dot = ".";
private const string IcoPath = "Images/calculator.png";
private static readonly List<Result> EmptyResults = [];
private History History { get; set; } = null!;
internal static PluginInitContext Context { get; private set; } = null!;
private Settings _settings;
private SettingsViewModel _viewModel;
public void Init(PluginInitContext context)
{
Context = context;
_settings = context.API.LoadSettingJsonStorage<Settings>();
History = context.API.LoadSettingJsonStorage<History>();
_viewModel = new SettingsViewModel(_settings);
MagesEngine = new Engine(new Configuration
{
Scope = new Dictionary<string, object>
{
{ "e", Math.E }, // e is not contained in the default mages engine
}
});
}
public List<Result> Query(Query query)
{
if (string.IsNullOrWhiteSpace(query.Search))
{
return EmptyResults;
}
try
{
var search = query.Search;
bool isFunctionPresent = FunctionRegex.IsMatch(search);
bool isValidResultToAddHistory = true;
// Mages is case sensitive, so we need to convert all function names to lower case.
search = FunctionRegex.Replace(search, m => m.Value.ToLowerInvariant());
var decimalSep = GetDecimalSeparator();
var groupSep = GetGroupSeparator(decimalSep);
var expression = NumberRegex.Replace(search, m => NormalizeNumber(m.Value, isFunctionPresent, decimalSep, groupSep));
// WORKAROUND START: The 'pow' function in Mages v3.0.0 is broken.
// https://github.com/FlorianRappl/Mages/issues/132
// We bypass it by rewriting any pow(x,y) expression to the equivalent (x^y) expression
// before the engine sees it. This loop handles nested calls.
{
string previous;
do
{
previous = expression;
expression = PowRegex.Replace(previous, PowMatchEvaluator);
} while (previous != expression);
}
// WORKAROUND END
// WORKAROUND START: The 'log' & 'ln' function in Mages v3.0.0 are broken.
// https://github.com/FlorianRappl/Mages/issues/137
// We bypass it by rewriting any log & ln expression to the equivalent (log10 & log) expression
// before the engine sees it. This loop handles nested calls.
{
string previous;
do
{
previous = expression;
expression = LogRegex.Replace(previous, LogMatchEvaluator);
} while (previous != expression);
}
{
string previous;
do
{
previous = expression;
expression = LnRegex.Replace(previous, LnMatchEvaluator);
} while (previous != expression);
}
// WORKAROUND END
var result = MagesEngine.Interpret(expression);
if (result == null || string.IsNullOrEmpty(result.ToString()))
{
if (!_settings.ShowErrorMessage) return EmptyResults;
return
[
new Result
{
Title = Localize.flowlauncher_plugin_calculator_expression_not_complete(),
IcoPath = IcoPath
}
];
}
if (result.ToString() == "NaN")
{
result = Localize.flowlauncher_plugin_calculator_not_a_number();
isValidResultToAddHistory = false;
}
if (result is Function)
{
result = Localize.flowlauncher_plugin_calculator_expression_not_complete();
isValidResultToAddHistory = false;
}
if (!string.IsNullOrEmpty(result.ToString()))
{
decimal roundedResult = Math.Round(Convert.ToDecimal(result), _settings.MaxDecimalPlaces, MidpointRounding.AwayFromZero);
string newResult = FormatResult(roundedResult);
var results = new List<Result>();
var action = CreateClipboardAction(newResult);
var resultObject = new Result
{
Title = newResult,
IcoPath = IcoPath,
Score = 300,
// Check context nullability for unit testing
SubTitle = Context == null
? string.Empty
: Localize.flowlauncher_plugin_calculator_copy_number_to_clipboard(),
CopyText = newResult,
Action = action
};
if (isValidResultToAddHistory)
{
var item = CreatePendingHistoryItem(resultObject, newResult, expression, action);
History.AddOrUpdate(item);
}
results.Add(resultObject);
var historyItems = _settings.EnableHistory
? History.GetItemsExcluding(expression)
: [];
return results.Concat(historyItems).ToList();
}
}
catch (Exception)
{
// Mages engine can throw various exceptions, for simplicity we catch them all and show a generic message.
if (!_settings.ShowErrorMessage) return EmptyResults;
return
[
new Result
{
Title = Localize.flowlauncher_plugin_calculator_expression_not_complete(),
IcoPath = IcoPath
}
];
}
return EmptyResults;
}
private PendingHistoryItem CreatePendingHistoryItem(Result result, string calcResult, string expression,
Func<ActionContext, bool> action)
{
var calculatedAt = DateTime.Now;
var copyToClipboard = Context == null
? "Copy this number to the clipboard"
: Localize.flowlauncher_plugin_calculator_copy_number_to_clipboard();
var historySubtitle = Context == null
? string.Format(CultureInfo.CurrentCulture, "Calculated at {0}", calculatedAt)
: Localize.flowlauncher_plugin_calculator_history_subtitle(calculatedAt);
var subtitle =
$"{calcResult} - {copyToClipboard}" +
$"\n{historySubtitle}";
return new PendingHistoryItem(result, expression, action, subtitle, calculatedAt);
}
private Func<ActionContext, bool> CreateClipboardAction(string newResult)
{
return (_) =>
{
try
{
Context.API.CopyToClipboard(newResult);
return true;
}
catch (ExternalException)
{
Context.API.ShowMsgBox(
Localize.flowlauncher_plugin_calculator_failed_to_copy()
);
return false;
}
};
}
private static string PowMatchEvaluator(Match m)
{
// m.Groups[1].Value will be `(...)` with parens
var contentWithParen = m.Groups[1].Value;
// remove outer parens. `(min(2,3), 4)` becomes `min(2,3), 4`
var argsContent = contentWithParen[1..^1];
var bracketCount = 0;
var splitIndex = -1;
// Find the top-level comma that separates the two arguments of pow.
for (var i = 0; i < argsContent.Length; i++)
{
switch (argsContent[i])
{
case '(':
case '[':
bracketCount++;
break;
case ')':
case ']':
bracketCount--;
break;
case ',' when bracketCount == 0:
splitIndex = i;
break;
}
if (splitIndex != -1)
break;
}
if (splitIndex == -1)
{
// This indicates malformed arguments for pow, e.g., pow(5) or pow().
// Return original string to let Mages handle the error.
return m.Value;
}
var arg1 = argsContent[..splitIndex].Trim();
var arg2 = argsContent[(splitIndex + 1)..].Trim();
// Check for empty arguments which can happen with stray commas, e.g., pow(,5)
if (string.IsNullOrEmpty(arg1) || string.IsNullOrEmpty(arg2))
{
return m.Value;
}
return $"({arg1}^{arg2})";
}
private static string LogMatchEvaluator(Match m)
{
// m.Groups[1].Value will be `(...)` with parens
var contentWithParen = m.Groups[1].Value;
var argsContent = contentWithParen[1..^1];
// log is unary — if malformed, return original to let Mages handle it
var arg = argsContent.Trim();
if (string.IsNullOrEmpty(arg)) return m.Value;
// log(x) -> log10(x) (natural log)
return $"(log10({arg}))";
}
private static string LnMatchEvaluator(Match m)
{
// m.Groups[1].Value will be `(...)` with parens
var contentWithParen = m.Groups[1].Value;
var argsContent = contentWithParen[1..^1];
// ln is unary — if malformed, return original to let Mages handle it
var arg = argsContent.Trim();
if (string.IsNullOrEmpty(arg)) return m.Value;
// ln(x) -> log(x) (natural log)
return $"(log({arg}))";
}
private static string NormalizeNumber(string numberStr, bool isFunctionPresent, string decimalSep, string groupSep)
{
if (isFunctionPresent)
{
// STRICT MODE: When functions are present, ',' is ALWAYS an argument separator.
if (numberStr.Contains(','))
{
return numberStr;
}
string processedStr = numberStr;
// Handle group separator, with special care for ambiguous dot.
if (!string.IsNullOrEmpty(groupSep))
{
if (groupSep == ".")
{
var parts = processedStr.Split('.');
if (parts.Length > 1)
{
var culture = CultureInfo.CurrentCulture;
if (IsValidGrouping(parts, culture.NumberFormat.NumberGroupSizes))
{
processedStr = processedStr.Replace(groupSep, "");
}
// If not grouped, it's likely a decimal number, so we don't strip dots.
}
}
else
{
processedStr = processedStr.Replace(groupSep, "");
}
}
// Handle decimal separator.
if (decimalSep != ".")
{
processedStr = processedStr.Replace(decimalSep, ".");
}
return processedStr;
}
else
{
// LENIENT MODE: No functions are present, so we can be flexible.
string processedStr = numberStr;
if (!string.IsNullOrEmpty(groupSep))
{
processedStr = processedStr.Replace(groupSep, "");
}
if (decimalSep != ".")
{
processedStr = processedStr.Replace(decimalSep, ".");
}
return processedStr;
}
}
private static bool IsValidGrouping(string[] parts, int[] groupSizes)
{
if (parts.Length <= 1) return true;
if (groupSizes is null || groupSizes.Length == 0 || groupSizes[0] == 0)
return false; // has groups, but culture defines none.
var firstPart = parts[0];
if (firstPart.StartsWith('-')) firstPart = firstPart[1..];
if (firstPart.Length == 0) return false; // e.g. ",123"
if (firstPart.Length > groupSizes[0]) return false;
var lastGroupSize = groupSizes.Last();
var canRepeatLastGroup = lastGroupSize != 0;
int groupIndex = 0;
for (int i = parts.Length - 1; i > 0; i--)
{
int expectedSize;
if (groupIndex < groupSizes.Length)
{
expectedSize = groupSizes[groupIndex];
}
else if (canRepeatLastGroup)
{
expectedSize = lastGroupSize;
}
else
{
return false;
}
if (parts[i].Length != expectedSize) return false;
groupIndex++;
}
return true;
}
private string FormatResult(decimal roundedResult)
{
string decimalSeparator = GetDecimalSeparator();
string groupSeparator = GetGroupSeparator(decimalSeparator);
string resultStr = roundedResult.ToString(CultureInfo.InvariantCulture);
string[] parts = resultStr.Split('.');
string integerPart = parts[0];
string fractionalPart = parts.Length > 1 ? parts[1] : string.Empty;
if (_settings.UseThousandsSeparator && integerPart.Length > 3)
{
integerPart = ThousandGroupRegex.Replace(integerPart, groupSeparator);
}
if (!string.IsNullOrEmpty(fractionalPart))
{
return integerPart + decimalSeparator + fractionalPart;
}
return integerPart;
}
private string GetGroupSeparator(string decimalSeparator)
{
var culture = CultureInfo.CurrentCulture;
var systemGroupSeparator = culture.NumberFormat.NumberGroupSeparator;
if (_settings.DecimalSeparator == DecimalSeparator.UseSystemLocale)
{
return systemGroupSeparator;
}
// When a custom decimal separator is used,
// use the system's group separator unless it conflicts with the custom decimal separator.
if (decimalSeparator == systemGroupSeparator)
{
// Conflict: use the opposite of the decimal separator as a fallback.
return decimalSeparator == Dot ? Comma : Dot;
}
return systemGroupSeparator;
}
private string GetDecimalSeparator()
{
string systemDecimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
return _settings.DecimalSeparator switch
{
DecimalSeparator.UseSystemLocale => systemDecimalSeparator,
DecimalSeparator.Dot => Dot,
DecimalSeparator.Comma => Comma,
_ => systemDecimalSeparator,
};
}
public string GetTranslatedPluginTitle()
{
return Localize.flowlauncher_plugin_calculator_plugin_name();
}
public string GetTranslatedPluginDescription()
{
return Localize.flowlauncher_plugin_calculator_plugin_description();
}
public Control CreateSettingPanel()
{
return new CalculatorSettings(_settings);
}
public void OnCultureInfoChanged(CultureInfo newCulture)
{
DecimalSeparatorLocalized.UpdateLabels(_viewModel.AllDecimalSeparator);
}
}
}