using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Audio.Midi;
namespace Content.Client.Instruments.UI;
[GenerateTypedNameReferences]
public sealed partial class ChannelsControl : BoxContainer
{
///
/// Raised when a channel is toggled.
///
public event Action? SwitchFilteredChannel;
///
/// Raised when a selector button is pressed in order to display different channel names.
///
public event Action? ChannelsUpdateRequest;
public ChannelsControl()
{
RobustXamlLoader.Load(this);
IoCManager.InjectDependencies(this);
TrackSelectorButton.OnPressed += OnSelectorButtonPressed;
InstrumentSelectorButton.OnPressed += OnSelectorButtonPressed;
ProgramSelectorButton.OnPressed += OnSelectorButtonPressed;
var group = new ButtonGroup();
TrackSelectorButton.Group = group;
InstrumentSelectorButton.Group = group;
ProgramSelectorButton.Group = group;
InitChannels();
}
protected override void VisibilityChanged(bool newVisible)
{
if (newVisible)
ChannelsUpdateRequest?.Invoke();
}
private void OnSelectorButtonPressed(BaseButton.ButtonEventArgs obj)
{
ChannelsUpdateRequest?.Invoke();
}
private void OnChannelSwitched(int id, bool state)
{
SwitchFilteredChannel?.Invoke(id, state);
}
private void InitChannels()
{
for (var i = 0; i < RobustMidiEvent.MaxChannels; i++)
{
var item = new ChannelItem
{
ChannelId = i,
};
ChannelsContainer.AddChild(item);
item.SwitchFilteredChannel += OnChannelSwitched;
}
}
private void ClearChannels()
{
TrackSelectorButton.Disabled = true;
InstrumentSelectorButton.Disabled = true;
ProgramSelectorButton.Disabled = true;
foreach (var child in ChannelsContainer.Children)
{
if (child is not ChannelItem cItem)
return;
cItem.ChannelName = "";
cItem.ChannelState = false;
cItem.Visible = false;
}
}
///
/// Replaces the current list of channels with the passed one.
///
///
/// Calling this method overrides the toggle state of all channel items. Ensure to pass correct values.
///
/// List of channels consisting of their index, display name and state.
public void SetChannels(MidiChannelInfo[] channels)
{
ClearChannels();
foreach (var channel in channels)
{
if (channel.Id < 0 || channel.Id >= RobustMidiEvent.MaxChannels)
continue;
if (channel.Id >= ChannelsContainer.ChildCount)
continue;
if (ChannelsContainer.Children[channel.Id] is not ChannelItem cItem)
continue;
if (channel.TrackName.Length > 0)
TrackSelectorButton.Disabled = false;
if (channel.InstrumentName.Length > 0)
InstrumentSelectorButton.Disabled = false;
if (channel.ProgramName.Length > 0)
ProgramSelectorButton.Disabled = false;
if (TrackSelectorButton.Pressed)
cItem.ChannelName = channel.TrackName;
if (InstrumentSelectorButton.Pressed)
cItem.ChannelName = channel.InstrumentName;
if (ProgramSelectorButton.Pressed)
cItem.ChannelName = channel.ProgramName;
cItem.ChannelState = channel.FilterState;
cItem.Visible = true;
}
}
}