using System;
namespace Sandbox.UI;
///
/// A button that toggles a console variable between two given values.
///
[Library( "ConvarToggleButton" )]
public class ConvarToggleButton : Button
{
///
/// The console variable to modify using this button.
///
public string ConVar { get; set; }
///
/// The "On" value for the convar, when the button is pressed in.
///
public string ValueOn { get; set; }
///
/// The "Off" value for the convar.
///
public string ValueOff { get; set; }
public ConvarToggleButton()
{
}
public ConvarToggleButton( Panel parent, string label, string convar, string onvalue, string offvalue, string icon = null )
{
this.Parent = parent;
this.Icon = icon;
this.Text = label;
ConVar = convar;
ValueOn = onvalue;
ValueOff = offvalue;
}
public override void Tick()
{
base.Tick();
if ( ConVar == null ) return;
var val = ConsoleSystem.GetValue( ConVar );
if ( val == null ) return;
SetClass( "active", String.Equals( val, ValueOn, StringComparison.OrdinalIgnoreCase ) );
}
///
/// Toggle the value of the ConVar between ValueOn and ValueOff.
/// If the convar's value is not either one of those, it will be set to ValueOn.
///
public void Toggle()
{
if ( ConVar == null ) return;
var val = ConsoleSystem.GetValue( ConVar );
var status = String.Equals( val, ValueOn, StringComparison.OrdinalIgnoreCase );
ConsoleSystem.Run( ConVar, status ? ValueOff : ValueOn );
}
public override void SetProperty( string name, string value )
{
base.SetProperty( name, value );
if ( name == "on" ) ValueOn = value;
if ( name == "off" ) ValueOff = value;
if ( name == "convar" ) ConVar = value;
}
protected override void OnClick( MousePanelEvent e )
{
Toggle();
}
}