JD2022-TU1/main/tools/thirdparty/DccToolToTempoBlasterPlugin/DccToTempoBlasterPlugin.cs

150 lines
No EOL
4.2 KiB
C#

using System;
using System.Threading;
using System.Windows.Forms;
using JD.Remoting;
using JD.Remoting.Connections;
namespace DccToolToTempoBlasterPlugin
{
public class DccToTempoBlasterPlugin : Plugin
{
private readonly IDccTool _dccTool;
private TimeSpan _currentTime;
private bool _isPlaying;
public DccToTempoBlasterPlugin(IDccTool dccTool)
: base("TempoBlasterDccPlugin")
{
_dccTool = dccTool;
RegisterHandler("getTrack", blob => this.Send("SetASlaveOfDccTool"));
RegisterHandler("setBeat", SetBeat);
RegisterHandler("setSongDuration", SetSongDuration);
RegisterHandler("setIsPlaying", SetIsPlaying);
Start(new EndPointId("127.0.0.1", 1002));
StartPollingThread();
}
private void SetSongDuration(IBlob obj)
{
TimeSpan duration = TimeSpan.FromSeconds(obj.ExtractFloat());
if (_dccTool.Duration != duration)
{
string message = $"The current Tempoblaster song file lasts for {duration}. Would you like to auto adjust your max scene?";
if (MessageBox.Show(message, "Auto adjust duration?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_dccTool.Duration = duration;
}
}
}
private void StartPollingThread()
{
ThreadPool.QueueUserWorkItem(state =>
{
bool quit = false;
CurrentBeatChanged += (s, e) =>
{
try
{
_dccTool.Time = CurrentTime;
}
catch (Exception)
{
quit = true;
}
};
IsPlayingChanged += (s, e) =>
{
try
{
_dccTool.IsPlaying = IsPlaying;
}
catch (Exception)
{
quit = true;
}
};
while (!quit)
{
Thread.Sleep(30);
CurrentTime = _dccTool.Time;
IsPlaying = _dccTool.IsPlaying;
}
});
}
private void SetIsPlaying(IBlob blob)
{
_isPlaying = blob.ExtractBool();
OnIsPlayingChanged();
}
private void SetBeat(IBlob blob)
{
_currentTime = TimeSpan.FromSeconds(blob.ExtractFloat());
OnCurrentBeatChanged();
}
private void SendPlayingState()
{
this.Send("getPlayingState", blob =>
{
blob.Push(_isPlaying);
blob.Push((float)_currentTime.TotalSeconds);
blob.Push(0f); // Absolute start beat.
blob.Push(1f); // Playing state.
});
}
public TimeSpan CurrentTime
{
get { return _currentTime; }
set
{
if (value != _currentTime)
{
_currentTime = value;
SendPlayingState();
}
}
}
public bool IsPlaying
{
get { return _isPlaying; }
set
{
if (value != _isPlaying)
{
_isPlaying = value;
SendPlayingState();
}
}
}
public event EventHandler IsPlayingChanged;
protected virtual void OnIsPlayingChanged()
{
var @event = IsPlayingChanged;
if (@event != null)
{
@event(this, EventArgs.Empty);
}
}
public event EventHandler CurrentBeatChanged;
protected virtual void OnCurrentBeatChanged()
{
var @event = CurrentBeatChanged;
if (@event != null)
{
@event(this, EventArgs.Empty);
}
}
}
}