using Avalonia.Controls; using Avalonia.Interactivity; using Avalonia.Platform.Storage; using Nonemm.Core; namespace Nonemm.App.Dialogs; /// The function key messages as the text of an N1MM `.mc` file. Editing them as /// the file rather than as twelve boxes is what makes import and export the /// same thing as what is on the screen. /// /// It closes with the text, or with null when nothing is to be changed. public sealed partial class MessagesDialog : Window { private static readonly FilePickerFileType MessageFiles = new("Function key files") { Patterns = ["*.mc"], }; private readonly ModeCategory mode; public MessagesDialog(ModeCategory mode, string text, string what = "Function key messages") { this.mode = mode; InitializeComponent(); Title = $"{what} — {(mode == ModeCategory.Phone ? "phone" : "CW")}"; TextArea.Text = text.Trim().Length > 0 ? text : Messages.DefaultFor(mode); } private async void OnImport(object? sender, RoutedEventArgs e) { IReadOnlyList files = await StorageProvider.OpenFilePickerAsync( new FilePickerOpenOptions { Title = "Import a function key file", AllowMultiple = false, FileTypeFilter = [MessageFiles], }); if (files.FirstOrDefault()?.TryGetLocalPath() is not { } path) { return; } try { TextArea.Text = await File.ReadAllTextAsync(path); } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { TextArea.Text = $"# {path} could not be read: {error.Message}\n{TextArea.Text}"; } } private async void OnExport(object? sender, RoutedEventArgs e) { IStorageFile? file = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Export the function key file", SuggestedFileName = mode == ModeCategory.Phone ? "phone.mc" : "cw.mc", DefaultExtension = "mc", FileTypeChoices = [MessageFiles], }); if (file?.TryGetLocalPath() is not { } path) { return; } try { await File.WriteAllTextAsync(path, TextArea.Text ?? ""); } catch (Exception error) when (error is IOException or UnauthorizedAccessException) { TextArea.Text = $"# {path} could not be written: {error.Message}\n{TextArea.Text}"; } } private void OnDefaults(object? sender, RoutedEventArgs e) => TextArea.Text = Messages.DefaultFor(mode); private void OnSave(object? sender, RoutedEventArgs e) => Close(TextArea.Text ?? ""); private void OnCancel(object? sender, RoutedEventArgs e) => Close(null); }