feat: Add support for message attachments

- Introduced Attachment model to handle file attachments associated with messages.
- Updated ModerationController to manage message deletions and attachment cleanup.
- Enhanced ChatService to include attachments in message retrieval.
- Implemented migration for legacy single-attachment messages to the new Attachments model.
- Added unit tests for attachment handling in message formatting and parsing.
- Updated database context and migrations to support new Attachments table.
This commit is contained in:
HueByte
2026-07-16 05:02:12 +02:00
parent e05b420ce9
commit 2d33773c24
33 changed files with 1843 additions and 454 deletions
+192 -69
View File
@@ -33,6 +33,7 @@ public sealed class AppOrchestrator : IDisposable
private readonly Dictionary<string, List<UserPresenceDto>> _channelUsers = new(StringComparer.OrdinalIgnoreCase);
private readonly Lock _channelUsersLock = new();
private readonly HashSet<string> _channelsLoadingMore = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _stagedAttachments = [];
private ClientConfig _config;
private readonly UserSession _session = new();
@@ -91,6 +92,7 @@ public sealed class AppOrchestrator : IDisposable
_mainWindow.OnAudioPlayRequested += HandleAudioPlayRequested;
_mainWindow.OnFileDownloadRequested += HandleFileDownloadRequested;
_mainWindow.OnImageSaveRequested += HandleImageSaveRequested;
_mainWindow.OnDeleteMessageRequested += HandleDeleteMessageRequested;
_mainWindow.OnCheckForUpdatesRequested += HandleCheckForUpdatesRequested;
_mainWindow.OnRollbackRequested += HandleRollbackRequested;
_mainWindow.OnUserProfileRequested += HandleViewProfile;
@@ -113,6 +115,8 @@ public sealed class AppOrchestrator : IDisposable
_commandHandler.OnOpenServers += HandleCmdOpenServers;
_commandHandler.OnJoinChannel += HandleCmdJoinChannel;
_commandHandler.OnChangeRoomPassword += HandleCmdChangeRoomPassword;
_commandHandler.OnClearAttachments += HandleCmdClearAttachments;
_commandHandler.OnSetDownloadPath += HandleCmdSetDownloadPath;
_commandHandler.OnLeaveChannel += HandleCmdLeaveChannel;
_commandHandler.OnSetTopic += HandleCmdSetTopic;
_commandHandler.OnListUsers += HandleCmdListUsers;
@@ -162,85 +166,107 @@ public sealed class AppOrchestrator : IDisposable
return Task.CompletedTask;
}
private async Task HandleCmdSendFile(string target, string? size)
private Task HandleCmdSendFile(string target, string? size)
{
if (!_conn.IsAuthenticated || !_conn.IsConnected) return;
if (!_conn.IsAuthenticated || !_conn.IsConnected) return Task.CompletedTask;
var channel = _mainWindow.CurrentChannel;
if (string.IsNullOrEmpty(channel)) return;
if (string.IsNullOrEmpty(channel)) return Task.CompletedTask;
try
// A URL image is sent immediately as its own message (it can't be staged/encrypted).
if (Uri.TryCreate(target, UriKind.Absolute, out var uri)
&& (uri.Scheme == "http" || uri.Scheme == "https"))
{
var hasRoomKey = _conn.RoomKeys.TryGetKey(channel, out var roomKey);
if (_conn.RoomKeys.HasKey(channel))
{
InvokeUI(() => _mainWindow.ShowError(
"Sending by URL isn't available in encrypted channels — download the file and /send it instead."));
return Task.CompletedTask;
}
if (Uri.TryCreate(target, UriKind.Absolute, out var uri)
&& (uri.Scheme == "http" || uri.Scheme == "https"))
{
if (hasRoomKey)
{
InvokeUI(() => _mainWindow.ShowError(
"Sending by URL isn't available in encrypted channels — download the file and /send it instead."));
return;
}
await _conn.Api!.SendUrlAsync(channel, target, size);
}
else if (hasRoomKey)
{
await UploadEncryptedFileAsync(channel, target, size, roomKey);
}
else
{
await using var stream = File.OpenRead(target);
var fileName = Path.GetFileName(target);
await _conn.Api!.UploadFileAsync(channel, stream, fileName, size);
}
RunAsync(async () => await _conn.Api!.SendUrlAsync(channel, target, size), "Send failed");
return Task.CompletedTask;
}
catch (Exception ex)
// Local files are staged; the next Enter sends them with the typed caption as one message.
if (_stagedAttachments.Count >= HubConstants.MaxAttachmentsPerMessage)
{
Log.Error(ex, "File send failed for {Target}", target);
InvokeUI(() => _mainWindow.ShowError($"Send failed: {ex.Message}"));
InvokeUI(() => _mainWindow.ShowError($"You can attach at most {HubConstants.MaxAttachmentsPerMessage} files per message."));
return Task.CompletedTask;
}
_stagedAttachments.Add(target);
InvokeUI(() => _mainWindow.SetStagedAttachments(_stagedAttachments.Select(Path.GetFileName).OfType<string>().ToList()));
return Task.CompletedTask;
}
private Task HandleCmdClearAttachments()
{
_stagedAttachments.Clear();
InvokeUI(() => _mainWindow.SetStagedAttachments([]));
return Task.CompletedTask;
}
/// <summary>
/// Upload into an end-to-end encrypted channel: the blob is encrypted with the room
/// key before it leaves this machine, and for images the ASCII preview is rendered
/// locally and sent room-encrypted — the server never sees image or file contents.
/// Sends one message with the given caption plus all staged files as attachments, then
/// clears the staging tray. In encrypted channels each file is room-encrypted (blob +
/// ASCII preview) client-side before upload; the caption is room-encrypted too.
/// </summary>
private async Task UploadEncryptedFileAsync(string channel, string path, string? size, byte[] roomKey)
private void SendStagedMessage(string channel, string content)
{
var staged = _stagedAttachments.ToList();
_stagedAttachments.Clear();
InvokeUI(() => _mainWindow.SetStagedAttachments([]));
var hasRoomKey = _conn.RoomKeys.TryGetKey(channel, out var roomKey);
RunAsync(async () =>
{
var outgoing = new List<OutgoingAttachment>();
foreach (var path in staged)
outgoing.Add(await BuildOutgoingAttachmentAsync(path, hasRoomKey ? roomKey : null));
var wireContent = hasRoomKey && !string.IsNullOrEmpty(content)
? RoomCrypto.EncryptText(content, roomKey)
: content;
await _conn.Api!.SendMessageWithAttachmentsAsync(channel, wireContent, outgoing);
}, "Send failed");
}
/// <summary>
/// Reads a staged file into an <see cref="OutgoingAttachment"/>. For encrypted channels the
/// blob is AES-GCM encrypted, its kind is declared, and the image ASCII preview is rendered
/// locally and room-encrypted — so the server never sees the file or image contents.
/// </summary>
private static async Task<OutgoingAttachment> BuildOutgoingAttachmentAsync(string path, byte[]? roomKey)
{
var fileName = Path.GetFileName(path);
var bytes = await File.ReadAllBytesAsync(path);
string declaredType;
string plainContent;
if (roomKey is null)
return new OutgoingAttachment(File.OpenRead(path), fileName);
var bytes = await File.ReadAllBytesAsync(path);
string declaredKind;
string? preview = null;
using (var ms = new MemoryStream(bytes))
{
if (FileValidationHelper.IsValidImage(ms))
{
declaredType = "image";
var (w, h) = ImageToAsciiService.GetDimensions(size);
declaredKind = "image";
var (w, h) = ImageToAsciiService.GetDimensions(null);
ms.Position = 0;
plainContent = new ImageToAsciiService().ConvertToAscii(ms, w, h);
}
else if (FileValidationHelper.IsAudioFile(fileName))
{
declaredType = "audio";
plainContent = fileName;
preview = RoomCrypto.EncryptText(new ImageToAsciiService().ConvertToAscii(ms, w, h), roomKey);
}
else
{
declaredType = "file";
plainContent = fileName;
declaredKind = FileValidationHelper.IsAudioFile(fileName) ? "audio" : "file";
}
}
var encryptedContent = RoomCrypto.EncryptText(plainContent, roomKey);
var encryptedBlob = RoomCrypto.EncryptBytes(bytes, roomKey);
await using var blobStream = new MemoryStream(encryptedBlob);
await _conn.Api!.UploadFileAsync(channel, blobStream, fileName, size, declaredType, encryptedContent);
return new OutgoingAttachment(new MemoryStream(encryptedBlob), fileName, declaredKind, preview);
}
private async Task HandleCmdSetAvatar(string target)
@@ -893,11 +919,28 @@ public sealed class AppOrchestrator : IDisposable
return;
}
// Staged files → one message with the typed caption plus those attachments.
if (_stagedAttachments.Count > 0)
{
SendStagedMessage(channelName, content);
return;
}
RunAsync(
async () => await _conn.SendMessageAsync(channelName, content),
"Send failed");
}
private void HandleDeleteMessageRequested(Guid messageId)
{
if (!_conn.IsAuthenticated) return;
// The server enforces the hierarchy rule (own message, or Mod+ over a strictly
// lower role) and broadcasts the deletion; the local list updates on that event.
RunAsync(async () => await _conn.Api!.DeleteMessageAsync(messageId),
"Failed to delete message");
}
private void HandleChannelSelected(string channelName)
{
if (!_conn.IsConnected) return;
@@ -1319,20 +1362,46 @@ public sealed class AppOrchestrator : IDisposable
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Downloading {fileName}..."));
var tempPath = await DownloadAttachmentAsync(attachmentUrl, fileName);
var downloads = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
Directory.CreateDirectory(downloads);
var stem = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
var destination = Path.Combine(downloads, fileName);
for (var i = 1; File.Exists(destination); i++)
destination = Path.Combine(downloads, $"{stem} ({i}){ext}");
var destination = DedupPath(GetDownloadDir(), fileName);
File.Move(tempPath, destination);
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Image saved to: {destination}"));
}, "Failed to save image");
}
/// <summary>
/// Resolves the folder downloads are written to: the user's configured
/// <see cref="ClientConfig.DownloadPath"/> if set, otherwise the OS Downloads folder.
/// Falls back to the temp folder if neither can be created.
/// </summary>
private string GetDownloadDir()
{
var dir = _config.DownloadPath;
if (string.IsNullOrWhiteSpace(dir))
dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
try
{
Directory.CreateDirectory(dir);
return dir;
}
catch (Exception ex)
{
Log.Warning(ex, "Download folder {Dir} is not usable; falling back to temp", dir);
return Path.GetTempPath();
}
}
/// <summary>Appends " (n)" before the extension until the path doesn't collide with an existing file.</summary>
private static string DedupPath(string dir, string fileName)
{
var stem = Path.GetFileNameWithoutExtension(fileName);
var ext = Path.GetExtension(fileName);
var dest = Path.Combine(dir, fileName);
for (var i = 1; File.Exists(dest); i++)
dest = Path.Combine(dir, $"{stem} ({i}){ext}");
return dest;
}
/// <summary>
/// File extensions considered safe to open with the system default application.
/// Everything else is downloaded only — never auto-opened via UseShellExecute.
@@ -1352,27 +1421,81 @@ public sealed class AppOrchestrator : IDisposable
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Downloading {fileName}..."));
var tempPath = await DownloadAttachmentAsync(attachmentUrl, fileName);
var ext = Path.GetExtension(fileName);
if (SafeOpenExtensions.Contains(ext))
var destination = DedupPath(GetDownloadDir(), fileName);
File.Move(tempPath, destination);
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Saved to: {destination}"));
if (SafeOpenExtensions.Contains(Path.GetExtension(fileName)))
{
try
{
var psi = new System.Diagnostics.ProcessStartInfo(tempPath) { UseShellExecute = true };
var psi = new System.Diagnostics.ProcessStartInfo(destination) { UseShellExecute = true };
System.Diagnostics.Process.Start(psi);
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to open file with default app: {Path}", tempPath);
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Downloaded to: {tempPath}"));
Log.Warning(ex, "Failed to open file with default app: {Path}", destination);
}
}
else
{
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Downloaded to: {tempPath}"));
}
}, "Failed to download file");
}
/// <summary>
/// Sets the download folder. With no argument, opens the OS-native folder picker; if that
/// isn't available (headless, missing tool), tells the user to pass a path instead. With an
/// argument, sets that path directly (the fallback for machines with no native picker).
/// </summary>
private Task HandleCmdSetDownloadPath(string args)
{
var current = _config.DownloadPath ?? GetDownloadDir();
if (!string.IsNullOrWhiteSpace(args))
{
SetDownloadPath(args.Trim());
return Task.CompletedTask;
}
RunAsync(async () =>
{
var result = await NativeFolderPicker.PickFolderAsync(current);
InvokeUI(() =>
{
switch (result.Outcome)
{
case PickerOutcome.Chosen when result.Path is not null:
SetDownloadPath(result.Path);
break;
case PickerOutcome.Cancelled:
_messageManager.AddSystemMessage(_mainWindow.CurrentChannel, "Download folder unchanged.");
break;
case PickerOutcome.Unavailable:
_messageManager.AddSystemMessage(_mainWindow.CurrentChannel,
$"No native folder picker here. Current download folder: {current}\nSet one with: /downloadpath <path>");
break;
}
});
}, "Failed to open folder picker");
return Task.CompletedTask;
}
private void SetDownloadPath(string path)
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception ex)
{
InvokeUI(() => _mainWindow.ShowError($"Can't use that folder: {ex.Message}"));
return;
}
_config.DownloadPath = path;
ConfigManager.Save(_config);
InvokeUI(() => _messageManager.AddSystemMessage(_mainWindow.CurrentChannel, $"Download folder set to: {path}"));
}
private void HandleCheckForUpdatesRequested()
{
RunAsync(_updateService.CheckNowAsync, "Failed to check for updates");
+24 -1
View File
@@ -15,6 +15,8 @@ public class CommandHandler
public event Func<Task>? OnOpenServers;
public event Func<string, string?, Task>? OnJoinChannel;
public event Func<string, string, Task>? OnChangeRoomPassword;
public event Func<Task>? OnClearAttachments;
public event Func<string, Task>? OnSetDownloadPath;
public event Func<Task>? OnLeaveChannel;
public event Func<string, Task>? OnSetTopic;
public event Func<Task>? OnListUsers;
@@ -48,6 +50,8 @@ public class CommandHandler
"color" => await HandleColor(args),
"theme" => await HandleTheme(args),
"send" => await HandleSend(args),
"clear" => await HandleClear(),
"downloadpath" or "downloads" => await HandleDownloadPath(args),
"profile" => await HandleProfile(args),
"avatar" => await HandleAvatar(args),
"servers" => await HandleServers(),
@@ -165,6 +169,21 @@ public class CommandHandler
return new CommandResult(true, $"Uploading: {Path.GetFileName(target)}...");
}
private async Task<CommandResult> HandleClear()
{
if (OnClearAttachments is not null)
await OnClearAttachments();
return new CommandResult(true, "Cleared staged attachments.");
}
private async Task<CommandResult> HandleDownloadPath(string args)
{
// No argument → open the native folder picker; an argument sets the path directly.
if (OnSetDownloadPath is not null)
await OnSetDownloadPath(args.Trim());
return new CommandResult(true);
}
private async Task<CommandResult> HandleProfile(string args)
{
var username = string.IsNullOrWhiteSpace(args) ? null : args.Trim();
@@ -358,7 +377,11 @@ public class CommandHandler
/nick <name> - Set display name
/color <#hex> - Set nickname color
/theme <name> - Switch theme
/send <filepath or URL> [-s|-m|-l] - Send file/image/audio (size flag for images)
/send <filepath> [-s|-m|-l] - Stage a file to attach (Enter sends with your text)
/send <URL> [-s|-m|-l] - Send an image URL immediately
/clear - Drop all staged attachments
(Tip: copy a file and press Ctrl+V, or drag a file onto the window, to attach it.)
/downloadpath [path] - Set download folder (no path = native folder picker)
/avatar <URL or filepath> - Set your avatar
/profile [username] - View a profile
/servers - Open saved servers
@@ -6,6 +6,12 @@ public class ClientConfig
public AccountPreset DefaultPreset { get; set; } = new();
public string ActiveTheme { get; set; } = "Default";
public NotificationConfig Notifications { get; set; } = new();
/// <summary>
/// Folder where downloaded attachments and saved images are written. When null, the
/// OS Downloads folder is used. Set via the native folder picker or <c>/downloadpath</c>.
/// </summary>
public string? DownloadPath { get; set; }
}
public class NotificationConfig
+23 -13
View File
@@ -185,25 +185,35 @@ public sealed class ApiClient : IDisposable
return result?.AvatarAscii;
}
public async Task<MessageDto?> UploadFileAsync(string channelName, Stream fileStream, string fileName, string? size = null,
string? declaredType = null, string? encryptedContent = null)
/// <summary>
/// Sends one message with optional text and one or more file attachments.
/// For end-to-end encrypted channels each attachment carries a declared kind and a
/// room-encrypted preview (empty when none); the caption is likewise room-encrypted.
/// </summary>
public async Task<MessageDto?> SendMessageWithAttachmentsAsync(
string channelName, string content, IReadOnlyList<OutgoingAttachment> attachments, string? size = null)
{
EnsureAuthenticated();
using var content = new MultipartFormDataContent();
using var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue(GetContentType(fileName));
content.Add(streamContent, "file", fileName);
using var form = new MultipartFormDataContent { { new StringContent(content), "content" } };
// E2E channels: the blob is ciphertext, so the client declares the type and
// supplies the room-encrypted message content the server can't produce.
if (declaredType is not null)
content.Add(new StringContent(declaredType), "type");
if (encryptedContent is not null)
content.Add(new StringContent(encryptedContent), "content");
foreach (var att in attachments)
{
var streamContent = new StreamContent(att.Stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue(GetContentType(att.FileName));
form.Add(streamContent, "file", att.FileName);
// Encrypted channels: one kind + preview per file, in the same order, to keep
// the server's index alignment (empty preview string for non-images).
if (att.DeclaredKind is not null)
{
form.Add(new StringContent(att.DeclaredKind), "kind");
form.Add(new StringContent(att.EncryptedPreview ?? string.Empty), "preview");
}
}
var sizeQuery = size is not null ? $"?size={size}" : "";
using var response = await AuthenticatedRequestAsync(() =>
_http.PostAsync($"/api/channels/{Uri.EscapeDataString(channelName)}/upload{sizeQuery}", content));
_http.PostAsync($"/api/channels/{Uri.EscapeDataString(channelName)}/messages{sizeQuery}", form));
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<MessageDto>();
}
@@ -0,0 +1,154 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using Serilog;
namespace EchoHub.Client.Services;
/// <summary>
/// Reads file paths that live on the OS clipboard as a *file list* (e.g. after copying a file in
/// Explorer/Finder/Nautilus), which terminals do not paste as text. Lets Ctrl+V attach a copied
/// file directly instead of requiring the user to paste a raw path.
/// </summary>
public static class ClipboardFiles
{
public static bool TryGetFiles(out List<string> files)
{
files = [];
try
{
if (OperatingSystem.IsWindows())
return TryGetWindows(out files);
if (OperatingSystem.IsLinux())
return TryGetLinux(out files);
}
catch (Exception ex)
{
Log.Warning(ex, "Reading files from the clipboard failed");
}
// macOS and everything else: no file-list clipboard support (text paste still works).
return false;
}
// ── Windows: CF_HDROP via the Win32 clipboard ────────────────────────────
private const uint CfHdrop = 15;
[SupportedOSPlatform("windows")]
private static bool TryGetWindows(out List<string> files)
{
files = [];
if (!IsClipboardFormatAvailable(CfHdrop))
return false;
// The clipboard may briefly be held by another process; a few quick retries cover that.
var opened = false;
for (var attempt = 0; attempt < 5 && !opened; attempt++)
opened = OpenClipboard(IntPtr.Zero);
if (!opened)
return false;
try
{
var hDrop = GetClipboardData(CfHdrop);
if (hDrop == IntPtr.Zero)
return false;
var count = DragQueryFileW(hDrop, 0xFFFFFFFF, null, 0);
for (uint i = 0; i < count; i++)
{
var len = DragQueryFileW(hDrop, i, null, 0);
if (len == 0)
continue;
var sb = new StringBuilder((int)len + 1);
DragQueryFileW(hDrop, i, sb, (uint)sb.Capacity);
var path = sb.ToString();
if (File.Exists(path))
files.Add(path);
}
return files.Count > 0;
}
finally
{
CloseClipboard();
}
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseClipboard();
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsClipboardFormatAvailable(uint format);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern uint DragQueryFileW(IntPtr hDrop, uint iFile, StringBuilder? lpszFile, uint cch);
// ── Linux: text/uri-list from the clipboard via xclip or wl-paste ─────────
[SupportedOSPlatform("linux")]
private static bool TryGetLinux(out List<string> files)
{
files = [];
var output = RunForOutput("wl-paste", ["--type", "text/uri-list", "--no-newline"])
?? RunForOutput("xclip", ["-selection", "clipboard", "-t", "text/uri-list", "-o"]);
if (string.IsNullOrWhiteSpace(output))
return false;
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (!line.StartsWith("file://", StringComparison.Ordinal))
continue;
try
{
var path = new Uri(line).LocalPath;
if (File.Exists(path))
files.Add(path);
}
catch (UriFormatException) { /* skip malformed entry */ }
}
return files.Count > 0;
}
private static string? RunForOutput(string fileName, IEnumerable<string> args)
{
var psi = new ProcessStartInfo(fileName)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
foreach (var arg in args)
psi.ArgumentList.Add(arg);
try
{
using var process = Process.Start(psi);
if (process is null)
return null;
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit(2000);
return process.ExitCode == 0 ? output : null;
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or FileNotFoundException)
{
return null; // tool not installed
}
}
}
@@ -207,28 +207,41 @@ public sealed class EchoHubConnection : IAsyncDisposable
}
/// <summary>
/// Strips the transport encryption, then the room layer for E2E channels.
/// Without the room key the content is replaced by a locked placeholder —
/// re-fetch history after unlocking to render it.
/// Strips the transport encryption, then the room layer for E2E channels, from the
/// message content and every attachment preview. Without the room key the content is
/// replaced by a locked placeholder — re-fetch history after unlocking to render it.
/// </summary>
private MessageDto DecryptMessage(MessageDto message)
{
var content = _encryption.Decrypt(message.Content);
_roomKeys.TryGetKey(message.ChannelName, out var roomKey);
if (RoomCrypto.IsRoomCiphertext(content))
var content = DecryptField(message.Content, roomKey) ?? LockedMessagePlaceholder;
List<AttachmentDto>? attachments = null;
if (message.Attachments is { Count: > 0 })
{
if (_roomKeys.TryGetKey(message.ChannelName, out var roomKey)
&& RoomCrypto.TryDecryptText(content, roomKey, out var plaintext))
{
content = plaintext;
}
else
{
content = LockedMessagePlaceholder;
}
attachments = message.Attachments
.Select(a => a with { AsciiPreview = a.AsciiPreview is null ? null : DecryptField(a.AsciiPreview, roomKey) })
.ToList();
}
return message with { Content = content };
return message with { Content = content, Attachments = attachments };
}
/// <summary>
/// Decrypts one field: strips transport encryption, then the room layer if it is room
/// ciphertext. Returns null when it is room ciphertext but the room key is missing/wrong.
/// </summary>
private string? DecryptField(string value, byte[]? roomKey)
{
var plain = _encryption.Decrypt(value);
if (!RoomCrypto.IsRoomCiphertext(plain))
return plain;
if (roomKey is not null && RoomCrypto.TryDecryptText(plain, roomKey, out var decrypted))
return decrypted;
return null;
}
public async ValueTask DisposeAsync()
@@ -0,0 +1,141 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Serilog;
namespace EchoHub.Client.Services;
public enum PickerOutcome
{
/// <summary>The user picked a folder (<see cref="FolderPickResult.Path"/> is set).</summary>
Chosen,
/// <summary>The native dialog ran but the user cancelled it.</summary>
Cancelled,
/// <summary>No native picker is available on this machine (headless, missing tool, etc.).</summary>
Unavailable,
}
public sealed record FolderPickResult(PickerOutcome Outcome, string? Path);
/// <summary>
/// Opens the OS-native folder chooser (Windows Explorer, macOS Finder, Linux GTK/KDE) by shelling
/// out, so the TUI doesn't need a GUI toolkit reference. Returns <see cref="PickerOutcome.Unavailable"/>
/// when no native dialog can run, so callers can fall back to a configured path.
/// </summary>
public static class NativeFolderPicker
{
private const string Title = "Choose your EchoHub download folder";
public static async Task<FolderPickResult> PickFolderAsync(string? initialDir)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return await PickWindowsAsync(initialDir);
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return await PickMacAsync();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
return await PickLinuxAsync(initialDir);
}
catch (Exception ex)
{
Log.Warning(ex, "Native folder picker failed");
}
return new FolderPickResult(PickerOutcome.Unavailable, null);
}
private static async Task<FolderPickResult> PickWindowsAsync(string? initialDir)
{
var safeInit = (initialDir ?? string.Empty).Replace("'", "''");
var script = $$"""
Add-Type -AssemblyName System.Windows.Forms
$d = New-Object System.Windows.Forms.FolderBrowserDialog
$d.Description = '{{Title}}'
$d.ShowNewFolderButton = $true
$d.SelectedPath = '{{safeInit}}'
if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write($d.SelectedPath) }
""";
// -EncodedCommand avoids all quoting issues; FolderBrowserDialog needs an STA thread.
var encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(script));
var (started, _, stdout) = await RunAsync("powershell.exe",
["-STA", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded]);
if (!started)
return new FolderPickResult(PickerOutcome.Unavailable, null);
return string.IsNullOrWhiteSpace(stdout)
? new FolderPickResult(PickerOutcome.Cancelled, null)
: new FolderPickResult(PickerOutcome.Chosen, stdout);
}
private static async Task<FolderPickResult> PickMacAsync()
{
var (started, exit, stdout) = await RunAsync("osascript",
["-e", $"POSIX path of (choose folder with prompt \"{Title}\")"]);
if (!started)
return new FolderPickResult(PickerOutcome.Unavailable, null);
return exit == 0 && !string.IsNullOrWhiteSpace(stdout)
? new FolderPickResult(PickerOutcome.Chosen, stdout)
: new FolderPickResult(PickerOutcome.Cancelled, null);
}
private static async Task<FolderPickResult> PickLinuxAsync(string? initialDir)
{
// No graphical session → no native picker.
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY"))
&& string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY")))
return new FolderPickResult(PickerOutcome.Unavailable, null);
var zenityArgs = new List<string> { "--file-selection", "--directory", $"--title={Title}" };
if (!string.IsNullOrWhiteSpace(initialDir))
zenityArgs.Add($"--filename={initialDir!.TrimEnd('/')}/");
var (zStarted, zExit, zOut) = await RunAsync("zenity", zenityArgs);
if (zStarted)
return zExit == 0 && !string.IsNullOrWhiteSpace(zOut)
? new FolderPickResult(PickerOutcome.Chosen, zOut)
: new FolderPickResult(PickerOutcome.Cancelled, null);
var (kStarted, kExit, kOut) = await RunAsync("kdialog",
["--getexistingdirectory", string.IsNullOrWhiteSpace(initialDir) ? "." : initialDir!]);
if (kStarted)
return kExit == 0 && !string.IsNullOrWhiteSpace(kOut)
? new FolderPickResult(PickerOutcome.Chosen, kOut)
: new FolderPickResult(PickerOutcome.Cancelled, null);
return new FolderPickResult(PickerOutcome.Unavailable, null);
}
private static async Task<(bool Started, int ExitCode, string StdOut)> RunAsync(string fileName, IEnumerable<string> args)
{
var psi = new ProcessStartInfo(fileName)
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
foreach (var arg in args)
psi.ArgumentList.Add(arg);
try
{
using var process = Process.Start(psi);
if (process is null)
return (false, -1, string.Empty);
var stdout = await process.StandardOutput.ReadToEndAsync();
await process.WaitForExitAsync();
return (true, process.ExitCode, stdout.Trim());
}
catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or FileNotFoundException)
{
// Executable not found on PATH → treat as "no native picker".
return (false, -1, string.Empty);
}
}
}
@@ -0,0 +1,13 @@
namespace EchoHub.Client.Services;
/// <summary>
/// One file to upload as part of a message. For end-to-end encrypted channels the stream
/// is already ciphertext, <see cref="DeclaredKind"/> is set (image/audio/file), and
/// <see cref="EncryptedPreview"/> holds the room-encrypted ASCII art for images.
/// For normal channels only <see cref="Stream"/> and <see cref="FileName"/> are set.
/// </summary>
public sealed record OutgoingAttachment(
Stream Stream,
string FileName,
string? DeclaredKind = null,
string? EncryptedPreview = null);
+2 -2
View File
@@ -18,7 +18,7 @@ public partial class ChatLine
public bool IsMention { get; set; }
public string? AttachmentUrl { get; set; }
public string? AttachmentFileName { get; set; }
public MessageType? Type { get; set; }
public AttachmentKind? AttachmentKind { get; set; }
public string? SenderUsername { get; set; }
/// <summary>Number of spaces to prepend on continuation lines when this line is word-wrapped.</summary>
public int ContinuationIndent { get; set; }
@@ -124,7 +124,7 @@ public partial class ChatLine
{
wrapped.AttachmentUrl = AttachmentUrl;
wrapped.AttachmentFileName = AttachmentFileName;
wrapped.Type = Type;
wrapped.AttachmentKind = AttachmentKind;
wrapped.MessageId = MessageId;
wrapped.SenderUsername = SenderUsername;
}
@@ -238,86 +238,77 @@ public sealed class ChatMessageManager
var senderName = message.SenderUsername + ":";
var senderColor = HexColorHelper.ParseHexColor(message.SenderNicknameColor);
var indent = new string(' ', $"[{time}] {senderName} ".Length);
var pad = new string(' ', 7);
var lines = new List<ChatLine>();
var hasContent = !string.IsNullOrWhiteSpace(message.Content);
var attachments = message.Attachments ?? [];
switch (message.Type)
// Header line: caption text, or a summary when the message is attachments-only
if (hasContent)
{
case MessageType.Image:
lines.Add(BuildChatLine(time, senderName, senderColor, " [Image]"));
if (!string.IsNullOrWhiteSpace(message.Content))
{
foreach (var artLine in message.Content.Split('\n'))
var displayContent = EmojiHelper.ReplaceEmoji(message.Content);
var contentLines = displayContent.Split('\n');
lines.Add(BuildChatLineWithMentions(time, senderName, senderColor, $" {contentLines[0].TrimEnd('\r')}"));
for (int i = 1; i < contentLines.Length; i++)
lines.Add(new ChatLine(ChatColors.SplitMentions($"{indent}{contentLines[i].TrimEnd('\r')}")));
}
else
{
var summary = attachments.Count switch
{
0 => " ",
1 => $" [{attachments[0].Kind.ToString().ToLowerInvariant()}]",
_ => $" [{attachments.Count} attachments]",
};
lines.Add(BuildChatLine(time, senderName, senderColor, summary));
}
foreach (var l in lines)
l.ContinuationIndent = indent.Length;
// One block per attachment
foreach (var attachment in attachments)
{
switch (attachment.Kind)
{
case Core.Models.AttachmentKind.Image:
if (!string.IsNullOrWhiteSpace(attachment.AsciiPreview))
{
var trimmed = artLine.TrimEnd('\r');
if (ChatLine.HasColorTags(trimmed))
lines.Add(ChatLine.FromColoredText(" " + trimmed));
else
lines.Add(new ChatLine($" {trimmed}"));
foreach (var artLine in attachment.AsciiPreview.Split('\n'))
{
var trimmed = artLine.TrimEnd('\r');
lines.Add(ChatLine.HasColorTags(trimmed)
? ChatLine.FromColoredText(pad + trimmed)
: new ChatLine($"{pad}{trimmed}"));
}
}
}
lines.Add(AttachmentActionLine(pad,
$"[↓ save original] {attachment.FileName} [{FormatFileSize(attachment.FileSize)}]",
ChatColors.FileAttr, attachment));
break;
// Clickable action to download the original image below the ASCII art
if (message.AttachmentUrl is not null)
{
var imageName = message.AttachmentFileName ?? "image";
var imageSize = FormatFileSize(message.AttachmentFileSize);
var saveLine = new ChatLine(new List<ChatSegment>
{
new(" ", null),
new($"[↓ save original] {imageName} [{imageSize}]", ChatColors.FileAttr),
});
saveLine.AttachmentUrl = message.AttachmentUrl;
saveLine.AttachmentFileName = imageName;
saveLine.Type = MessageType.Image;
lines.Add(saveLine);
}
break;
case Core.Models.AttachmentKind.Audio:
lines.Add(AttachmentActionLine(pad,
$"♪ [Audio: {attachment.FileName}] [{FormatFileSize(attachment.FileSize)}]",
ChatColors.AudioAttr, attachment));
break;
case MessageType.Audio:
var audioName = message.AttachmentFileName ?? "unknown";
var audioSize = FormatFileSize(message.AttachmentFileSize);
var audioLine = BuildChatLineColored(time, senderName, senderColor,
$" \u266a [Audio: {audioName}] [{audioSize}]", ChatColors.AudioAttr);
audioLine.AttachmentUrl = message.AttachmentUrl;
audioLine.AttachmentFileName = audioName;
audioLine.Type = MessageType.Audio;
lines.Add(audioLine);
break;
default:
lines.Add(AttachmentActionLine(pad,
$"[File: {attachment.FileName}] [{FormatFileSize(attachment.FileSize)}]",
ChatColors.FileAttr, attachment));
break;
}
}
case MessageType.File:
var fileName = message.AttachmentFileName ?? "unknown";
var fileSize = FormatFileSize(message.AttachmentFileSize);
var fileLine = BuildChatLineColored(time, senderName, senderColor,
$" [File: {fileName}] [{fileSize}]", ChatColors.FileAttr);
fileLine.AttachmentUrl = message.AttachmentUrl;
fileLine.AttachmentFileName = fileName;
fileLine.Type = MessageType.File;
lines.Add(fileLine);
break;
case MessageType.Text:
default:
var displayContent = EmojiHelper.ReplaceEmoji(message.Content);
var contentLines = displayContent.Split('\n');
var firstLine = contentLines[0].TrimEnd('\r');
lines.Add(BuildChatLineWithMentions(time, senderName, senderColor, $" {firstLine}"));
var indent = new string(' ', $"[{time}] {senderName} ".Length);
for (int i = 1; i < contentLines.Length; i++)
{
var contText = $"{indent}{contentLines[i].TrimEnd('\r')}";
lines.Add(new ChatLine(ChatColors.SplitMentions(contText)));
}
foreach (var l in lines)
l.ContinuationIndent = indent.Length;
if (message.Embeds is { Count: > 0 })
{
var chatWidth = _chatWidth > 0 ? _chatWidth : 80;
foreach (var embed in message.Embeds)
lines.AddRange(FormatEmbed(embed, indent, chatWidth));
}
break;
// Link embeds (from caption URLs)
if (message.Embeds is { Count: > 0 })
{
var chatWidth = _chatWidth > 0 ? _chatWidth : 80;
foreach (var embed in message.Embeds)
lines.AddRange(FormatEmbed(embed, indent, chatWidth));
}
foreach (var line in lines)
@@ -326,7 +317,7 @@ public sealed class ChatMessageManager
line.SenderUsername = message.SenderUsername;
}
if (!string.IsNullOrEmpty(_currentUser) && message.Type == MessageType.Text)
if (hasContent && !string.IsNullOrEmpty(_currentUser))
{
var pattern = $@"@{Regex.Escape(_currentUser)}\b";
if (Regex.IsMatch(message.Content, pattern, RegexOptions.IgnoreCase))
@@ -339,6 +330,23 @@ public sealed class ChatMessageManager
return lines;
}
/// <summary>
/// Builds a clickable attachment line carrying the metadata the message list uses to
/// route activation (play audio, download file, save original image).
/// </summary>
private static ChatLine AttachmentActionLine(string pad, string text, Attribute color, AttachmentDto attachment)
{
var line = new ChatLine(new List<ChatSegment>
{
new(pad, null),
new(text, color),
});
line.AttachmentUrl = attachment.Url;
line.AttachmentFileName = attachment.FileName;
line.AttachmentKind = attachment.Kind;
return line;
}
private static ChatLine BuildChatLine(string time, string senderName, Attribute? senderColor, string suffix)
{
var segments = new List<ChatSegment>
@@ -0,0 +1,104 @@
using System.Text;
namespace EchoHub.Client.UI.Helpers;
/// <summary>
/// Recognizes a dragged-and-dropped file (or files) that a terminal delivers into the input as an
/// absolute path. Terminals differ: some paste the whole path at once, others send it character by
/// character; either way this checks whether the current input text resolves to existing file(s).
/// </summary>
public static class DroppedFileParser
{
/// <summary>
/// Cheap pre-check so callers only stat the filesystem when the input plausibly holds a path:
/// a quoted path, a Windows drive path (<c>X:\</c>/<c>X:/</c>), a UNC path (<c>\\</c>), or a
/// POSIX absolute path (<c>/</c>). Normal chat text never starts this way.
/// </summary>
public static bool LooksLikePath(string text)
{
var t = text.TrimStart();
if (t.Length < 3)
return false;
if (t[0] is '"' or '/')
return true;
if (t.StartsWith(@"\\", StringComparison.Ordinal))
return true;
return char.IsLetter(t[0]) && t[1] == ':' && (t[2] == '\\' || t[2] == '/');
}
/// <summary>
/// Returns true when <paramref name="text"/> resolves to one or more existing files.
/// Handles a single path (quoted or not, possibly containing spaces) and multiple
/// space-separated (optionally quoted) paths. <paramref name="fileExists"/> is injectable
/// for testing; production passes <see cref="File.Exists"/>.
/// </summary>
public static bool TryGetFiles(string text, out List<string> files, Func<string, bool>? fileExists = null)
{
fileExists ??= File.Exists;
files = [];
var trimmed = text.Trim();
if (trimmed.Length < 3 || trimmed.Length > 4096 || trimmed.Contains('\n'))
return false;
// Single path, possibly quoted and/or containing spaces.
var unquoted = StripQuotes(trimmed);
if (Path.IsPathFullyQualified(unquoted) && fileExists(unquoted))
{
files.Add(unquoted);
return true;
}
// Multiple files: space-separated tokens, each optionally quoted.
foreach (var token in TokenizeQuoted(trimmed))
{
if (!Path.IsPathFullyQualified(token) || !fileExists(token))
{
files.Clear();
return false;
}
files.Add(token);
}
return files.Count > 0;
}
private static string StripQuotes(string s) =>
s.Length >= 2 && ((s[0] == '"' && s[^1] == '"') || (s[0] == '\'' && s[^1] == '\''))
? s[1..^1]
: s;
private static IEnumerable<string> TokenizeQuoted(string input)
{
var current = new StringBuilder();
var quote = '\0';
foreach (var c in input)
{
if (quote != '\0')
{
if (c == quote) quote = '\0';
else current.Append(c);
}
else if (c is '"' or '\'')
{
quote = c;
}
else if (c == ' ')
{
if (current.Length > 0)
{
yield return current.ToString();
current.Clear();
}
}
else
{
current.Append(c);
}
}
if (current.Length > 0)
yield return current.ToString();
}
}
+95 -101
View File
@@ -40,7 +40,9 @@ public sealed partial class MainWindow : Runnable
private readonly UserListSource _usersListSource;
private bool _usersPanelVisible = true;
private const int UsersPanelWidth = 22;
private const string DefaultInputTitle = "Message │ Enter=send │ Ctrl+N=newline │ Tab=complete │ Ctrl+K=search";
private static readonly Key F2Key = Key.F2;
private bool _hasStagedAttachments;
internal static readonly string AppVersion =
typeof(MainWindow).Assembly.GetName().Version?.ToString(3) ?? "?";
@@ -60,7 +62,7 @@ public sealed partial class MainWindow : Runnable
private static readonly string[] SlashCommands =
[
"/status", "/nick", "/color", "/theme", "/send",
"/avatar", "/profile", "/servers", "/join", "/passwd", "/leave",
"/avatar", "/profile", "/servers", "/join", "/passwd", "/leave", "/clear", "/downloadpath",
"/topic", "/users", "/kick", "/ban", "/unban",
"/mute", "/unmute", "/role", "/nuke", "/test-sound", "/quit", "/help"
];
@@ -159,6 +161,11 @@ public sealed partial class MainWindow : Runnable
/// </summary>
public event Action<string, string>? OnImageSaveRequested;
/// <summary>
/// Fired when the user presses Delete on the selected message. Parameter is the message id.
/// </summary>
public event Action<Guid>? OnDeleteMessageRequested;
/// <summary>
/// Fired when the user activates a username (in userlist or message). Parameter is the username.
/// </summary>
@@ -240,6 +247,7 @@ public sealed partial class MainWindow : Runnable
};
_messageList.Source = new ChatListSource();
_messageList.Accepting += OnMessageListAccepting;
_messageList.KeyDown += OnMessageListKeyDown;
_messageList.VerticalScrollBar.Scrolled += OnMessageListVerticalScrollBarScrolled;
_messageList.VerticalScrollBar.Visible = true;
@@ -249,7 +257,7 @@ public sealed partial class MainWindow : Runnable
// Bottom input area
_inputFrame = new FrameView
{
Title = "Message \u2502 Enter=send \u2502 Ctrl+N=newline \u2502 Tab=complete \u2502 Ctrl+K=search",
Title = DefaultInputTitle,
X = 22,
Y = Pos.Bottom(_chatFrame),
Width = Dim.Fill(UsersPanelWidth),
@@ -321,6 +329,27 @@ public sealed partial class MainWindow : Runnable
KeyDown += OnWindowKeyDown;
}
/// <summary>
/// Updates the attachment staging indicator shown on the input frame's title.
/// Passing an empty list restores the default hint.
/// </summary>
public void SetStagedAttachments(IReadOnlyList<string> fileNames)
{
_hasStagedAttachments = fileNames.Count > 0;
if (fileNames.Count == 0)
{
_inputFrame.Title = DefaultInputTitle;
}
else
{
var names = string.Join(", ", fileNames);
if (names.Length > 60)
names = names[..57] + "...";
_inputFrame.Title = $"📎 {fileNames.Count} staged: {names} │ Enter=send │ /clear to drop";
}
_inputFrame.SetNeedsDraw();
}
/// <summary>
/// Applies the currently registered color schemes to all views.
/// Call after theme changes to refresh colors.
@@ -458,21 +487,21 @@ public sealed partial class MainWindow : Runnable
// Audio/file attachments take priority
if (line.AttachmentUrl is not null && line.AttachmentFileName is not null)
{
if (line.Type == MessageType.Audio)
if (line.AttachmentKind == AttachmentKind.Audio)
{
OnAudioPlayRequested?.Invoke(line.AttachmentUrl, line.AttachmentFileName);
e.Handled = true;
return;
}
if (line.Type == MessageType.File)
if (line.AttachmentKind == AttachmentKind.File)
{
OnFileDownloadRequested?.Invoke(line.AttachmentUrl, line.AttachmentFileName);
e.Handled = true;
return;
}
if (line.Type == MessageType.Image)
if (line.AttachmentKind == AttachmentKind.Image)
{
OnImageSaveRequested?.Invoke(line.AttachmentUrl, line.AttachmentFileName);
e.Handled = true;
@@ -510,6 +539,32 @@ public sealed partial class MainWindow : Runnable
}
}
private void OnMessageListKeyDown(object? sender, Key e)
{
if (e.KeyCode != Key.Delete.KeyCode && e.KeyCode != Key.Backspace.KeyCode)
return;
if (_messageList.Source is not ChatListSource source)
return;
var index = _messageList.SelectedItem;
if (!index.HasValue || index.Value < 0 || index.Value >= source.Count)
return;
var line = source.GetLine(index.Value);
if (line?.MessageId is not { } messageId)
return;
// Server enforces the real permission (own message, or Mod+ over a lower role);
// the client just confirms intent and lets the server reject if disallowed.
var confirm = MessageBox.Query(_app, "Delete Message",
"Delete this message?", "Delete", "Cancel");
if (confirm == 0)
OnDeleteMessageRequested?.Invoke(messageId);
e.Handled = true;
}
private void OnMessageListVerticalScrollBarScrolled(object? sender, EventArgs<int> e)
{
if (_messageList.VerticalScrollBar.Value == 0)
@@ -545,7 +600,9 @@ public sealed partial class MainWindow : Runnable
else if (e.KeyCode == EnterKey.KeyCode)
{
var text = _inputField.Text?.Trim() ?? string.Empty;
if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(_messageManager.CurrentChannel))
// Send when there's text, or when only attachments are staged (empty caption).
if ((!string.IsNullOrEmpty(text) || _hasStagedAttachments)
&& !string.IsNullOrEmpty(_messageManager.CurrentChannel))
{
OnMessageSubmitted?.Invoke(_messageManager.CurrentChannel, text);
_inputField.Text = string.Empty;
@@ -564,9 +621,13 @@ public sealed partial class MainWindow : Runnable
}
else if (e.KeyCode == CtrlVKey.KeyCode || e.KeyCode == CtrlYKey.KeyCode)
{
// Explicit paste support: terminals that don't intercept Ctrl+V themselves
// otherwise leave users with only the right-click context menu.
GuardedClipboardAction(() => _inputField.Paste(), "paste");
// If a file was copied in the OS file manager, the clipboard holds a file list
// (not text) — attach it. Otherwise paste text. This is the reliable path on
// Windows Terminal, which never pastes copied files as text.
if (ClipboardFiles.TryGetFiles(out var pastedFiles))
StageFiles(pastedFiles);
else
GuardedClipboardAction(() => _inputField.Paste(), "paste");
e.Handled = true;
}
else if (e.KeyCode == CtrlXKey.KeyCode)
@@ -599,42 +660,35 @@ public sealed partial class MainWindow : Runnable
}
private bool _suppressEmojiReplace;
private int _lastInputLength;
private void OnInputContentsChanged(object? sender, ContentsChangedEventArgs e)
{
var text = _inputField.Text;
var previousLength = _lastInputLength;
_lastInputLength = text?.Length ?? 0;
if (_suppressEmojiReplace)
return;
var text = _inputField.Text;
if (string.IsNullOrEmpty(text))
return;
// A file dropped onto the terminal arrives as a pasted absolute path.
// Detect multi-char bursts that resolve to existing files and route them
// through /send instead of leaving a raw path in the input.
if (text.Length - previousLength > 3 && TryGetDroppedFiles(text, out var droppedFiles))
// A file dropped onto the terminal is delivered as its absolute path inserted into the
// input — often character by character (this Terminal.Gui build has no bracketed-paste
// coalescing). As soon as the input resolves to existing file path(s), route them
// through /send (which stages them) instead of leaving a raw path to be sent as a message.
if (DroppedFileParser.LooksLikePath(text) && DroppedFileParser.TryGetFiles(text, out var droppedFiles)
&& !string.IsNullOrEmpty(_messageManager.CurrentChannel))
{
var channel = _messageManager.CurrentChannel;
if (!string.IsNullOrEmpty(channel))
_suppressEmojiReplace = true;
try
{
_suppressEmojiReplace = true;
try
{
_inputField.Text = string.Empty;
}
finally
{
_suppressEmojiReplace = false;
}
foreach (var file in droppedFiles)
OnMessageSubmitted?.Invoke(channel, $"/send \"{file}\"");
return;
_inputField.Text = string.Empty;
}
finally
{
_suppressEmojiReplace = false;
}
StageFiles(droppedFiles);
return;
}
var replaced = EmojiHelper.ReplaceEmoji(text);
@@ -695,77 +749,17 @@ public sealed partial class MainWindow : Runnable
}
/// <summary>
/// Interprets pasted text as one or more dropped files. Terminals deliver a file drop
/// as the absolute path (quoted when it contains spaces; multiple files space-separated).
/// Returns true only when the entire input resolves to existing files.
/// Routes files (from a drop or a file-clipboard paste) through the /send pipeline, which
/// stages them; the next Enter sends them with any typed caption.
/// </summary>
private static bool TryGetDroppedFiles(string text, out List<string> files)
private void StageFiles(IEnumerable<string> files)
{
files = [];
var channel = _messageManager.CurrentChannel;
if (string.IsNullOrEmpty(channel))
return;
var trimmed = text.Trim();
if (trimmed.Length < 3 || trimmed.Length > 4096 || trimmed.Contains('\n'))
return false;
// Single unquoted path, possibly with spaces (e.g. WSL or plain conhost drops)
var unquoted = StripQuotes(trimmed);
if (Path.IsPathFullyQualified(unquoted) && File.Exists(unquoted))
{
files.Add(unquoted);
return true;
}
// Multiple files: space-separated tokens, each optionally quoted
foreach (var token in TokenizeQuoted(trimmed))
{
if (!Path.IsPathFullyQualified(token) || !File.Exists(token))
{
files.Clear();
return false;
}
files.Add(token);
}
return files.Count > 0;
}
private static string StripQuotes(string s) =>
s.Length >= 2 && ((s[0] == '"' && s[^1] == '"') || (s[0] == '\'' && s[^1] == '\''))
? s[1..^1]
: s;
private static IEnumerable<string> TokenizeQuoted(string input)
{
var current = new System.Text.StringBuilder();
var quote = '\0';
foreach (var c in input)
{
if (quote != '\0')
{
if (c == quote) quote = '\0';
else current.Append(c);
}
else if (c is '"' or '\'')
{
quote = c;
}
else if (c == ' ')
{
if (current.Length > 0)
{
yield return current.ToString();
current.Clear();
}
}
else
{
current.Append(c);
}
}
if (current.Length > 0)
yield return current.ToString();
foreach (var file in files)
OnMessageSubmitted?.Invoke(channel, $"/send \"{file}\"");
}
private void OnChatViewportChanged()