AnotherReplayReader/Debug.xaml.cs
2021-10-14 14:22:34 +02:00

85 lines
2.6 KiB
C#

using Microsoft.Win32;
using System;
using System.IO;
using System.Threading;
using System.Windows;
namespace AnotherReplayReader
{
public sealed class DebugMessageWrapper
{
public readonly struct Proxy
{
public readonly string Payload;
public Proxy(string text)
{
Payload = text;
}
public static Proxy operator +(Proxy p, string text)
{
return string.IsNullOrEmpty(p.Payload) ? new Proxy(text) : new Proxy(p.Payload + text);
}
}
public event Action<string>? NewText;
public Proxy DebugMessage
{
get => new Proxy();
set => NewText?.Invoke(value.Payload);
}
public event Action? RequestedSave;
public void RequestSave() => RequestedSave?.Invoke();
}
/// <summary>
/// Debug.xaml 的交互逻辑
/// </summary>
public sealed partial class Debug : Window
{
public static readonly DebugMessageWrapper Instance = new DebugMessageWrapper();
private static Debug? _window = null;
public static void Initialize()
{
Interlocked.CompareExchange(ref _window, new(), null);
_window.InitializeComponent();
Instance.NewText += _window.AppendText;
Instance.RequestedSave += _window.ExportInMainWindow;
}
public static new void ShowDialog() => (_window as Window)?.ShowDialog();
private Debug() { }
private void OnExport_Click(object sender, RoutedEventArgs e) => Export(this);
private void OnClear_Click(object sender, RoutedEventArgs e) => _textBox.Clear();
private void AppendText(string s) => Dispatcher.Invoke(() => _textBox.AppendText(s));
private void ExportInMainWindow() => Export(Application.Current.MainWindow);
private void Export(Window owner)
{
Dispatcher.Invoke(() =>
{
var saveFileDialog = new SaveFileDialog
{
Filter = "文本文档 (*.txt)|*.txt|所有文件 (*.*)|*.*",
OverwritePrompt = true,
};
var result = saveFileDialog.ShowDialog(owner);
if (result == true)
{
using (var file = saveFileDialog.OpenFile())
using (var writer = new StreamWriter(file))
{
writer.Write(_textBox.Text);
}
}
});
}
}
}