naps2/NAPS2.Lib/EtoForms/MenuProvider.cs

107 lines
2.6 KiB
C#
Raw Normal View History

2022-08-21 03:50:38 +03:00
using Eto.Forms;
namespace NAPS2.EtoForms;
public class MenuProvider
{
2023-12-07 07:17:50 +03:00
private readonly List<Item> _items = [];
2022-08-21 03:50:38 +03:00
public MenuProvider Dynamic(ListProvider<Command> commandListProvider)
{
_items.Add(new DynamicItem
{
CommandListProvider = commandListProvider ?? throw new ArgumentNullException(nameof(commandListProvider))
});
commandListProvider.OnChanged += () => ContentsChanged?.Invoke();
return this;
}
public MenuProvider Append(Command? command)
2022-08-21 03:50:38 +03:00
{
if (command == null)
{
return this;
}
2022-08-21 03:50:38 +03:00
_items.Add(new CommandItem
{
Command = command
2022-08-21 03:50:38 +03:00
});
return this;
}
public MenuProvider Separator()
{
_items.Add(new SeparatorItem());
return this;
}
public MenuProvider SubMenu(Command command, MenuProvider subMenu)
{
_items.Add(new SubMenuItem
{
Command = command ?? throw new ArgumentNullException(nameof(command)),
MenuProvider = subMenu
});
return this;
}
private event Action? ContentsChanged;
public class Item
{
}
private class DynamicItem : Item
{
public ListProvider<Command> CommandListProvider { get; init; } = null!;
2022-08-21 03:50:38 +03:00
}
public class CommandItem : Item
{
public Command Command { get; init; } = null!;
2022-08-21 03:50:38 +03:00
}
public class SubMenuItem : Item
{
public Command Command { get; init; } = null!;
public MenuProvider MenuProvider { get; init; } = null!;
2022-08-21 03:50:38 +03:00
}
public class SeparatorItem : Item
{
}
private List<Item> GetSubItems()
{
var actualItems = new List<Item>();
Item? lastItem = null;
foreach (var item in _items)
{
if (item is DynamicItem dynamicItem)
{
2022-11-02 22:14:04 +03:00
var dynamicItemValues =
2022-08-21 03:50:38 +03:00
dynamicItem.CommandListProvider.Value.Select(x => new CommandItem
2022-11-02 22:14:04 +03:00
{
Command = x
}).ToList();
if (dynamicItemValues.Any())
{
actualItems.AddRange(dynamicItemValues);
lastItem = item;
}
2022-08-21 03:50:38 +03:00
}
else if (item is not SeparatorItem || (lastItem != null && lastItem is not SeparatorItem))
{
actualItems.Add(item);
2022-11-02 22:14:04 +03:00
lastItem = item;
2022-08-21 03:50:38 +03:00
}
}
return actualItems;
}
public void Handle(Action<List<Item>> subItemsHandler)
{
subItemsHandler(GetSubItems());
ContentsChanged += () => subItemsHandler(GetSubItems());
}
}