using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.Windows; using System.Windows.Controls; using System.IO; namespace WGneu { public static class Utils { public static void SetInputChanged(Control input) { input.BorderBrush = Brushes.Orange; } public static void SetInputInvalid(Control input) { input.BorderBrush = Brushes.Red; } public static void ClearInputState(Control input) { input.ClearValue(Control.BorderBrushProperty); } public static IEnumerable FindVisualChilds(DependencyObject depObj) where T : DependencyObject { if (depObj == null) yield return (T)Enumerable.Empty(); for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject ithChild = VisualTreeHelper.GetChild(depObj, i); if (ithChild == null) continue; if (ithChild is T t) yield return t; foreach (T childOfChild in FindVisualChilds(ithChild)) yield return childOfChild; } } public static IEnumerable FindVisualChilds(DependencyObject depObj, IEnumerable exempt) where T : DependencyObject { return FindVisualChilds(depObj).Where(c => !exempt.Contains(c)); } public static int Modulo(string a, int b) { if (!a.All(char.IsDigit)) throw new ArgumentException("First argument has to be a decimal string"); return a.Select(ch => ch - '0').Aggregate((sum, n) => (sum * 10 + n) % b); } public static void RunBackground(string title, Func a) { Task.Run(async () => { try { await a(); } catch (Exception e) { MessageBox.Show(e.ToString(), title, MessageBoxButton.OK, MessageBoxImage.Error); } }); } public sealed class TemporaryFile : IDisposable { private int Usages = 0; public string FilePath { get; private set; } public TemporaryFile() : this(null) {} public TemporaryFile(string? ext) : this(Path.Combine(Path.GetTempPath(), "Kelwin"), ext) {} public TemporaryFile(string dir, string? ext) { FilePath = Path.Combine(dir, Path.GetRandomFileName().Replace(".", "") + (ext != null ? $".{ext}" : "")); Usages++; Create(); } ~TemporaryFile() { Delete(); } public void Dispose() { if (--Usages == 0) { Delete(); GC.SuppressFinalize(this); } } public TemporaryFile NewReference() { Usages++; return this; } private void Create() { using (File.Create(FilePath)) {}; } private void Delete() { if (FilePath == null) return; File.Delete(FilePath); FilePath = null; } } } }