aboutsummaryrefslogtreecommitdiff
path: root/manager/MainWindow.axaml.cs
blob: 6abbd0ee669ebdc11cc75d2a4204eb7ef9319aa3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Media;
using Avalonia.Threading;
using Tomlyn;
using Tomlyn.Model;

namespace manager;

public partial class MainWindow : Window
{
    private readonly string _configDir;
    private readonly string _sourceToml;
    private readonly string _guiConfigPath;
    private bool _dirty;
    private bool _loading;
    private bool _promptingClose;
    private bool _dmvopRunning;
    private Process? _dmvopProcess;
    private readonly StringBuilder _dmvopOutput = new();
    private const string BaseTitle = "DumbVoiceProtocol";

    public MainWindow()
    {
        InitializeComponent();

        // Parent directory of the program location = build/
        _configDir = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, ".."));
        _sourceToml = Path.Combine(_configDir, "dmvop.toml");
        _guiConfigPath = Path.Combine(_configDir, "dmvop-gui.toml");

        DownloadModelButton.Click += OnDownloadModel;
        KeyDown += OnKeyDown;

        // Hide Unix-specific items on Windows
        if (OperatingSystem.IsWindows())
        {
            IpcCheck.IsVisible = false;
            SocketFilePanel.IsVisible = false;
        }

        // Mark dirty on all input control changes
        SubscribeChanges();

        Closing += OnClosing;

        ActionButton.Click += OnActionButton;
        _ = StartDashboardTimer();

        LoadConfig();
    }

    private void SubscribeChanges()
    {
        // TextBoxes
        DeviceBox.TextChanged += (_, _) => MarkDirty();
        FormatBox.TextChanged += (_, _) => MarkDirty();
        LangBox.TextChanged += (_, _) => MarkDirty();
        PortBox.TextChanged += (_, _) => MarkDirty();
        SubnetMaskBox.TextChanged += (_, _) => MarkDirty();
        SocketFileBox.TextChanged += (_, _) => MarkDirty();
        ModelsDirBox.TextChanged += (_, _) => MarkDirty();
        PostBox.TextChanged += (_, _) => MarkDirty();

        // ComboBox
        ModelBox.SelectionChanged += (_, _) => MarkDirty();

        // CheckBoxes
        StdoutCheck.IsCheckedChanged += (_, _) => MarkDirty();
        TcpCheck.IsCheckedChanged += (_, _) => MarkDirty();
        UdpCheck.IsCheckedChanged += (_, _) => MarkDirty();
        UdpBroadcastCheck.IsCheckedChanged += (_, _) => MarkDirty();
        IpcCheck.IsCheckedChanged += (_, _) => MarkDirty();
        InstantCheck.IsCheckedChanged += (_, _) => MarkDirty();
    }

    private void MarkDirty()
    {
        if (_loading || _dirty) return;
        _dirty = true;
        UpdateTitle();
    }

    private void ClearDirty()
    {
        if (!_dirty) return;
        _dirty = false;
        UpdateTitle();
    }

    private void UpdateTitle()
    {
        Title = _dirty ? $"{BaseTitle} *" : BaseTitle;
    }

    // ---- Dashboard ----

    private async Task StartDashboardTimer()
    {
        while (true)
        {
            await Task.Delay(2000);
            CheckDmvopStatus();
        }
    }

    private bool IsDmvopRunning()
    {
        return Process.GetProcessesByName("dmvop").Any(p => p.Id != Environment.ProcessId);
    }

    private void CheckDmvopStatus()
    {
        var running = IsDmvopRunning();
        if (running == _dmvopRunning) return;
        _dmvopRunning = running;
        Dispatcher.UIThread.Post(() =>
        {
            UpdateDashboard();
            if (!_dmvopRunning)
            {
                _dmvopProcess = null;
                _dmvopOutput.Clear();
                OutputArea.Text = "";
            }
        });
    }

    private void UpdateDashboard()
    {
        if (_dmvopRunning)
        {
            StatusLight.Fill = new SolidColorBrush(Colors.LimeGreen);
            StatusTextRight.Text = "Running";
            StatusTextRight.Foreground = new SolidColorBrush(Colors.LimeGreen);
            ActionButton.Content = "Stop";
        }
        else
        {
            StatusLight.Fill = new SolidColorBrush(Colors.Red);
            StatusTextRight.Text = "Stopped";
            StatusTextRight.Foreground = new SolidColorBrush(Colors.Gray);
            ActionButton.Content = "Start";
        }
    }

    private void OnActionButton(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        if (_dmvopRunning)
        {
            // Stop
            try { _dmvopProcess?.Kill(); } catch { }
            foreach (var proc in Process.GetProcessesByName("dmvop"))
            {
                if (proc.Id == Environment.ProcessId) continue;
                try { proc.Kill(); } catch { }
            }
            _dmvopProcess = null;
        }
        else
        {
            // Start: launch from dmvop.exe directory, no window
            var dmvopPath = Path.Combine(_configDir, "dmvop.exe");
            if (!File.Exists(dmvopPath))
            {
                StatusLabel.Text = "Cannot find dmvop.exe";
                return;
            }

            _dmvopOutput.Clear();
            OutputArea.Text = "";

            var psi = new ProcessStartInfo
            {
                FileName = dmvopPath,
                Arguments = "--config=\"./dmvop-gui.toml\" --verbose",
                WorkingDirectory = _configDir,
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8,
            };

            try
            {
                var proc = Process.Start(psi);
                if (proc == null)
                {
                    StatusLabel.Text = "Failed to start";
                    return;
                }
                _dmvopProcess = proc;

                // Read stdout and stderr in parallel
                _ = ReadStreamAsync(proc.StandardOutput);
                _ = ReadStreamAsync(proc.StandardError);

                proc.Exited += (_, _) =>
                {
                    proc.WaitForExit();
                    _dmvopRunning = false;
                    Dispatcher.UIThread.Post(() =>
                    {
                        UpdateDashboard();
                        // Don't clear output immediately so the user can see the last content
                    });
                };
                proc.EnableRaisingEvents = true;
            }
            catch (Exception ex)
            {
                StatusLabel.Text = $"Failed to start: {ex.Message}";
            }
        }
    }

    private async Task ReadStreamAsync(StreamReader reader)
    {
        var buffer = new char[4096];
        int charsRead;
        while ((charsRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
        {
            var segment = new string(buffer, 0, charsRead);
            lock (_dmvopOutput)
            {
                _dmvopOutput.Append(segment);
                // Limit max length to avoid memory blowup
                if (_dmvopOutput.Length > 100_000)
                    _dmvopOutput.Remove(0, _dmvopOutput.Length - 50_000);
            }
            Dispatcher.UIThread.Post(() =>
            {
                OutputArea.Text = _dmvopOutput.ToString();
                // OutputScroll is the ScrollViewer x:Name? Use parent ScrollViewer
                // Find the parent ScrollViewer of OutputArea directly
                if (OutputArea.Parent is ScrollViewer sv)
                    sv.ScrollToEnd();
            });
        }
    }

    private void OnClosing(object? sender, WindowClosingEventArgs e)
    {
        if (!_dirty || _promptingClose) return;

        e.Cancel = true;
        _promptingClose = true;

        Dispatcher.UIThread.Post(async () =>
        {
            var result = await MessageBox.Show(this,
                "There are unsaved changes. Do you want to save?", "DumbVoiceProtocol",
                ("Save", MessageBoxResult.Yes),
                ("Don't Save", MessageBoxResult.No),
                ("Cancel", MessageBoxResult.Cancel));

            _promptingClose = false;

            switch (result)
            {
                case MessageBoxResult.Yes:
                    OnSave();
                    if (!_dirty)
                        Close();
                    break;
                case MessageBoxResult.No:
                    _dirty = false;
                    Close();
                    break;
            }
        });
    }

    private void LoadConfig()
    {
        _loading = true;

        if (!File.Exists(_guiConfigPath))
        {
            if (File.Exists(_sourceToml))
            {
                File.Copy(_sourceToml, _guiConfigPath);
            }
            else
            {
                MessageBox.Show(this, "dmvop.toml does not exist", "Configuration Error",
                    ("OK", MessageBoxResult.Ok));
                StatusLabel.Text = "dmvop.toml does not exist";
                return;
            }
        }

        try
        {
            var text = File.ReadAllText(_guiConfigPath);
            var model = Toml.ToModel(text);

            DeviceBox.Text = GetString(model, "device") ?? "auto";
            FormatBox.Text = GetString(model, "format") ?? "%{vol},%{word}";

            var modelName = GetString(model, "model") ?? "base.en";
            SelectComboBoxItem(ModelBox, modelName);

            LangBox.Text = GetString(model, "lang") ?? "en";

            if (model.TryGetValue("output", out var outputVal) && outputVal is TomlArray outputArray)
            {
                var modes = outputArray.OfType<string>().ToList();
                StdoutCheck.IsChecked = modes.Contains("stdout");
                TcpCheck.IsChecked = modes.Contains("tcp");
                UdpCheck.IsChecked = modes.Contains("udp");
                UdpBroadcastCheck.IsChecked = modes.Contains("udp-broadcast");
                IpcCheck.IsChecked = modes.Contains("ipc");
            }

            if (model.TryGetValue("port", out var portVal) && portVal is long portLong)
                PortBox.Text = portLong.ToString();

            if (model.TryGetValue("instant", out var instantVal) && instantVal is bool instant)
                InstantCheck.IsChecked = instant;

            SubnetMaskBox.Text = GetString(model, "subnet_mask") ?? "255.255.255.0";
            SocketFileBox.Text = GetString(model, "socket_file") ?? "./dmvop.sock";
            ModelsDirBox.Text = GetString(model, "models_dir") ?? "";
            PostBox.Text = GetString(model, "post") ?? "";

            StatusLabel.Text = $"Loaded: {Path.GetFileName(_guiConfigPath)}";
        }
        catch (Exception ex)
        {
            StatusLabel.Text = $"Load error: {ex.Message}";
        }
        finally
        {
            _loading = false;
            ClearDirty();
        }
    }

    private void OnDownloadModel(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        var modelName = GetComboBoxText(ModelBox);
        if (string.IsNullOrEmpty(modelName))
        {
            StatusLabel.Text = "Please select a model first";
            return;
        }

        var dmvopPath = Path.Combine(_configDir, "dmvop.exe");
        if (!File.Exists(dmvopPath))
        {
            StatusLabel.Text = "Cannot find dmvop.exe";
            return;
        }

        var procWin = new ProcessWindow(dmvopPath, $"--download-model={modelName}", _configDir);
        procWin.ShowDialog(this);
    }

    private void OnKeyDown(object? sender, Avalonia.Input.KeyEventArgs e)
    {
        if (e.Key == Avalonia.Input.Key.S && e.KeyModifiers.HasFlag(Avalonia.Input.KeyModifiers.Control))
        {
            OnSave();
        }
    }

    private void OnSave()
    {
        try
        {
            var model = new TomlTable();

            model["device"] = DeviceBox.Text ?? "auto";
            model["format"] = FormatBox.Text ?? "%{vol},%{word}";
            model["model"] = GetComboBoxText(ModelBox) ?? "base.en";
            model["lang"] = LangBox.Text ?? "en";

            var outputArray = new TomlArray();
            if (StdoutCheck.IsChecked == true) outputArray.Add("stdout");
            if (TcpCheck.IsChecked == true) outputArray.Add("tcp");
            if (UdpCheck.IsChecked == true) outputArray.Add("udp");
            if (UdpBroadcastCheck.IsChecked == true) outputArray.Add("udp-broadcast");
            if (IpcCheck.IsChecked == true) outputArray.Add("ipc");
            model["output"] = outputArray;

            if (int.TryParse(PortBox.Text, out var port))
                model["port"] = port;

            model["instant"] = InstantCheck.IsChecked == true;

            model["subnet_mask"] = SubnetMaskBox.Text ?? "255.255.255.0";
            model["socket_file"] = SocketFileBox.Text ?? "./dmvop.sock";

            if (!string.IsNullOrWhiteSpace(ModelsDirBox.Text))
                model["models_dir"] = ModelsDirBox.Text;

            if (!string.IsNullOrWhiteSpace(PostBox.Text))
                model["post"] = PostBox.Text;

            var toml = Toml.FromModel(model);
            var header = """
                ## DMVOP Config File
                ## Generated by DMVOP Manager
                ##
                ## Name this file `dmvop.toml` and place it in the working dir to be auto-detected!
                ## DMVOP will auto-load this config file to avoid repeated CLI args

                """;

            File.WriteAllText(_guiConfigPath, header + toml);

            StatusLabel.Text = $"Saved: {Path.GetFileName(_guiConfigPath)}";
            ClearDirty();
        }
        catch (Exception ex)
        {
            StatusLabel.Text = $"Save error: {ex.Message}";
        }
    }

    // ---- Helpers ----

    private static string? GetString(TomlTable table, string key)
        => table.TryGetValue(key, out var val) ? val?.ToString() : null;

    private static void SelectComboBoxItem(ComboBox comboBox, string text)
    {
        for (var i = 0; i < comboBox.Items.Count; i++)
        {
            if (comboBox.Items[i] is ComboBoxItem cbi && cbi.Content?.ToString() == text)
            {
                comboBox.SelectedIndex = i;
                return;
            }
        }
    }

    private static string? GetComboBoxText(ComboBox comboBox)
        => comboBox.SelectedItem is ComboBoxItem cbi
            ? cbi.Content?.ToString()
            : null;
}