sledgemapper/Sledgemapper/ExtensionMethods.cs
Michele Scandura 333c6c4046
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
stability improvements
2021-09-22 16:16:46 +01:00

96 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Myra.Graphics2D.Brushes;
using Myra.Graphics2D.UI;
namespace Sledgemapper
{
public static class ExtensionMethods
{
public static Point AbsPoint(this Point point)
{
return new Point(Math.Abs(point.X), Math.Abs(point.Y));
}
public static Window GetContainingWindow(this Widget widget)
{
var container = widget.Parent;
while (container is not Window or null) container = container.Parent;
return container as Window;
}
public static (Window Window, TC Content) GetParentContentInWindow<TC>(this Widget widget) where TC : Widget
{
var container = widget.Parent;
while (container is not Window) container = container.Parent;
var localWindow = (Window)container;
var localContent = localWindow.Content as TC;
return (localWindow, localContent);
}
public static Dictionary<string, T> LoadContentFolder<T>(this ContentManager contentManager, string contentFolder)
{
DirectoryInfo dir = new(contentManager.RootDirectory + "/" + contentFolder);
if (!dir.Exists)
{
throw new DirectoryNotFoundException();
}
Dictionary<string, T> result = new();
var files = dir.GetFiles("*.*");
foreach (var file in files.Where(f => f.Extension != ".ttf" && f.Extension != ".otf"))
{
result.Add(file.Name.Split('.')[0], contentManager.Load<T>(contentFolder + "/" + file.Name.Split('.')[0]));
}
return result;
}
public static void ShowInModalWindow(this Widget widget, Desktop desktop, string title)
{
Window window = new()
{
Title = title,
Content = widget
};
window.ShowModal(desktop);
}
public static IEnumerable<string> Split(this string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}
public static void Toast(this Widget widget, Desktop desktop)
{
widget.Left = desktop.BoundsFetcher().Center.X - widget.Width.Value / 2;
widget.Top = desktop.BoundsFetcher().Height - 90;
widget.ZIndex = 1000;
desktop.Widgets.Add(widget);
Task.Delay(2000).ContinueWith(_ => { desktop.Widgets.Remove(widget); }
).SafeFireAndForget();
}
public static bool ValidateTextbox(this TextBox textBox)
{
var valid = !string.IsNullOrWhiteSpace(textBox.Text);
textBox.Background = valid ? new SolidBrush(new Color(51, 51, 51)) : new SolidBrush(Color.Red);
return valid;
}
}
}