mirror of
https://github.com/MCCTeam/Minecraft-Console-Client
synced 2026-08-15 13:04:36 +00:00
TUI for MCC (#2976)
* feat: implement interactive TUI inventory viewer - Added InventoryTui command to open an interactive terminal user interface for inventory management. - Introduced InventoryApp and InventoryMainView classes for TUI layout and functionality. - Created InventoryViewModel and SlotViewModel to manage inventory data and display. - Integrated Consolonia for enhanced console UI experience. - Updated McClient to support console message handling during TUI operation. These changes enhance user interaction with inventory management in Minecraft Console Client. * feat: enhance debugging workflow with mcc-debug.sh and TUI support - Introduced mcc-debug.sh for streamlined one-step build, server start, and MCC launch. - Added TUI mode for improved user experience during debugging sessions. - Updated mcc-env.sh to include new debug helpers and TUI mode functionality. - Enhanced SKILL.md with detailed instructions for using the new debugging tools and console modes. These changes significantly improve the debugging process for Minecraft Console Client, making it more efficient and user-friendly. * feat: introduce TUI console backend and related enhancements - Added ClassicConsoleBackend and TuiConsoleBackend to support different console I/O modes. - Implemented IConsoleBackend interface for better abstraction of console operations. - Enhanced ConsoleIO to utilize the new backend structure for input and output handling. - Introduced MainTuiView and MccTuiApp for a full-screen TUI experience using Avalonia. - Updated InventoryTuiHost to manage TUI lifecycle and interactions. These changes significantly improve the console experience in Minecraft Console Client, providing a more flexible and user-friendly interface. * refactor: remove InventoryTui command implementation - Deleted the InventoryTui class, which provided an interactive terminal user interface for inventory management. - This change simplifies the command structure as part of ongoing improvements to the console experience in Minecraft Console Client. The removal of this command is aligned with recent enhancements to the console backend and user interface. * refactor: update InventoryMainView and MainTuiView for improved UI handling - Changed several fields from readonly to mutable in InventoryMainView to allow for dynamic updates. - Introduced a new McColorParser class for parsing Minecraft color codes and creating colored text blocks. - Enhanced MainTuiView to support formatted log lines and improved notification handling. - Updated chat scrolling behavior to ensure better user experience during text input and log display. These changes streamline the UI components and enhance the overall console experience in Minecraft Console Client. * feat: enhance command input handling in MainTuiView - Updated command input to use event routing for better key handling. - Added support for Ctrl key shortcuts to improve text manipulation (e.g., word deletion, caret movement). - Implemented text cleaning on input change to prevent newline characters. - Improved health and food status bar rendering with a new method for building bar text. These changes significantly enhance the user experience in the TUI by providing more intuitive command input functionality. * feat: enhance TUI command suggestion functionality - Introduced a new CommandSuggestion struct for backend-independent suggestion handling. - Updated ConsoleIO to streamline suggestion updates for both Classic and TUI backends. - Enhanced MainTuiView to display command suggestions with improved visibility and interaction. - Increased the maximum number of displayed suggestions from 6 to 10 for better user experience. These changes significantly improve the command input experience in the TUI, making it more intuitive and user-friendly. * feat: enhance offline command autocomplete functionality - Introduced an OfflineAutocompleteHandler to provide command suggestions for offline commands. - Added support for tab cycling through suggestions in the TUI. - Improved command input handling to clear suggestions when necessary and manage user input more effectively. - Updated TuiConsoleBackend to integrate with the new autocomplete feature. These changes significantly enhance the user experience by making command input more intuitive and responsive in offline scenarios. * feat: enhance localization and user feedback in TUI - Updated various TUI components to utilize localized strings for improved user experience. - Enhanced debug state output with translated labels for better clarity. - Improved inventory command help messages with localized text. - Added new translations for console mode descriptions and inventory viewer prompts. These changes significantly enhance the usability and accessibility of the TUI in Minecraft Console Client, making it more user-friendly and informative. * feat: enforce localization for user-facing strings in AGENTS.md - Added guidelines to ensure all user-facing text, including log messages and error messages, is managed through the translation system. - Specified the use of `Translations.resx` and `Translations.Designer.cs` for localization, emphasizing the importance of avoiding hardcoded strings in source code. These changes improve the consistency and accessibility of user-facing content across the application.
This commit is contained in:
parent
a17b7d4bd3
commit
8456e363f5
28 changed files with 4272 additions and 145 deletions
29
MinecraftClient/Tui/InventoryApp.cs
Normal file
29
MinecraftClient/Tui/InventoryApp.cs
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Consolonia.Themes;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class InventoryApp : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
Styles.Add(new ModernTheme());
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
desktop.MainWindow = new Window
|
||||
{
|
||||
Content = new InventoryMainView(),
|
||||
Title = "MCC Inventory"
|
||||
};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
}
|
||||
752
MinecraftClient/Tui/InventoryMainView.cs
Normal file
752
MinecraftClient/Tui/InventoryMainView.cs
Normal file
|
|
@ -0,0 +1,752 @@
|
|||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using MinecraftClient.Inventory;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class InventoryMainView : UserControl
|
||||
{
|
||||
private static readonly IBrush BrSlotEmptyA = new SolidColorBrush(Color.FromRgb(40, 40, 40));
|
||||
private static readonly IBrush BrSlotEmptyB = new SolidColorBrush(Color.FromRgb(55, 55, 55));
|
||||
private static readonly IBrush BrSlotFillA = new SolidColorBrush(Color.FromRgb(60, 60, 75));
|
||||
private static readonly IBrush BrSlotFillB = new SolidColorBrush(Color.FromRgb(75, 75, 90));
|
||||
private static readonly IBrush BrSlotHover = new SolidColorBrush(Color.FromRgb(100, 100, 140));
|
||||
private static readonly IBrush BrName = Brushes.White;
|
||||
private static readonly IBrush BrCount = Brushes.Yellow;
|
||||
private static readonly IBrush BrDim = new SolidColorBrush(Color.FromRgb(80, 80, 80));
|
||||
private static readonly IBrush BrEquipLbl = Brushes.DarkCyan;
|
||||
private static readonly IBrush BrInfoHighlight = new SolidColorBrush(Color.FromRgb(40, 40, 60));
|
||||
private static readonly IBrush BrHeldItemBg = new SolidColorBrush(Color.FromRgb(60, 50, 80));
|
||||
private static readonly IBrush BrHeldItemBorder = Brushes.Yellow;
|
||||
|
||||
private int _slotW;
|
||||
private int _slotH;
|
||||
private int _nameMaxLen;
|
||||
private int _nameLines;
|
||||
private int _topGap;
|
||||
private int _termW;
|
||||
|
||||
private readonly InventoryViewModel _vm;
|
||||
private TextBlock _titleText = null!;
|
||||
private Border _infoDetailBorder = null!;
|
||||
private TextBlock _infoDetailText = null!;
|
||||
private TextBlock _cursorItemText = null!;
|
||||
private TextBlock _helpText = null!;
|
||||
|
||||
private TextBlock[] _hotbarIndicators = new TextBlock[9];
|
||||
private int _currentHotbarSlot = -1;
|
||||
|
||||
private Border? _lastHoveredSlotBorder;
|
||||
|
||||
private Canvas _overlayCanvas = null!;
|
||||
private Border _heldItemFloater = null!;
|
||||
private TextBlock _heldItemFloaterName = null!;
|
||||
private TextBlock _heldItemFloaterCount = null!;
|
||||
|
||||
private ScrollViewer _chatScrollViewer = null!;
|
||||
private ObservableCollection<string>? _chatLines;
|
||||
private int _lastTermW;
|
||||
private int _lastTermH;
|
||||
|
||||
public InventoryMainView()
|
||||
{
|
||||
var handler = InventoryTuiHost.ActiveHandler
|
||||
?? throw new InvalidOperationException("No active McClient");
|
||||
int windowId = InventoryTuiHost.ActiveWindowId;
|
||||
|
||||
_vm = new InventoryViewModel(handler, windowId);
|
||||
_currentHotbarSlot = handler.GetCurrentSlot();
|
||||
|
||||
_chatLines = TuiConsoleBackend.Instance?.GetView()?.GetRecentLogLines(50)
|
||||
?? new ObservableCollection<string>();
|
||||
|
||||
RebuildUi();
|
||||
}
|
||||
|
||||
private void RebuildUi()
|
||||
{
|
||||
int termH;
|
||||
try
|
||||
{
|
||||
_termW = System.Console.WindowWidth;
|
||||
termH = System.Console.WindowHeight;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_termW = 120;
|
||||
termH = 40;
|
||||
}
|
||||
|
||||
_lastTermW = _termW;
|
||||
_lastTermH = termH;
|
||||
|
||||
int availW = _termW - 26;
|
||||
_slotW = Math.Clamp(availW / 9, 8, 18);
|
||||
_nameMaxLen = _slotW;
|
||||
|
||||
int topUsedW = _slotW * 4 + 8 + _slotW * 2 + 4 + _slotW;
|
||||
_topGap = Math.Max(2, (_slotW * 9 - topUsedW) / 2);
|
||||
|
||||
_slotH = Math.Clamp((termH - 8) / 6, 2, 5);
|
||||
_nameLines = _slotH;
|
||||
|
||||
_vm.SetSlotDisplayParams(_nameMaxLen, _nameLines);
|
||||
|
||||
_lastHoveredSlotBorder = null;
|
||||
|
||||
_titleText = new TextBlock
|
||||
{
|
||||
FontWeight = FontWeight.Bold,
|
||||
Foreground = Brushes.Cyan,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
};
|
||||
|
||||
_infoDetailText = new TextBlock
|
||||
{
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
Foreground = Brushes.White,
|
||||
};
|
||||
|
||||
_infoDetailBorder = new Border
|
||||
{
|
||||
Background = Brushes.Transparent,
|
||||
Padding = new Thickness(0),
|
||||
Child = _infoDetailText,
|
||||
};
|
||||
|
||||
_cursorItemText = new TextBlock
|
||||
{
|
||||
Foreground = Brushes.Yellow,
|
||||
FontWeight = FontWeight.Bold,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
};
|
||||
|
||||
_helpText = new TextBlock
|
||||
{
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(140, 140, 140)),
|
||||
Text = Translations.tui_inventory_controls_help,
|
||||
};
|
||||
|
||||
_heldItemFloaterName = new TextBlock
|
||||
{
|
||||
Foreground = Brushes.White,
|
||||
FontWeight = FontWeight.Bold,
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
};
|
||||
_heldItemFloaterCount = new TextBlock
|
||||
{
|
||||
Foreground = BrCount,
|
||||
FontWeight = FontWeight.Bold,
|
||||
};
|
||||
_heldItemFloater = new Border
|
||||
{
|
||||
Background = BrHeldItemBg,
|
||||
BorderBrush = BrHeldItemBorder,
|
||||
BorderThickness = new Thickness(1),
|
||||
Padding = new Thickness(1, 0),
|
||||
IsVisible = false,
|
||||
MaxWidth = 24,
|
||||
Child = new StackPanel
|
||||
{
|
||||
Children = { _heldItemFloaterName, _heldItemFloaterCount },
|
||||
},
|
||||
};
|
||||
|
||||
_overlayCanvas = new Canvas { IsHitTestVisible = false };
|
||||
_overlayCanvas.Children.Add(_heldItemFloater);
|
||||
|
||||
var chatLines = _chatLines!;
|
||||
chatLines.CollectionChanged += (_, _) =>
|
||||
{
|
||||
Avalonia.Threading.Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
var sv = _chatScrollViewer;
|
||||
if (sv.Extent.Height > sv.Viewport.Height)
|
||||
sv.Offset = new Vector(0, sv.Extent.Height - sv.Viewport.Height);
|
||||
}, Avalonia.Threading.DispatcherPriority.Background);
|
||||
};
|
||||
var chatItemsControl = new ItemsControl
|
||||
{
|
||||
ItemsSource = chatLines,
|
||||
Focusable = false,
|
||||
ItemTemplate = new FuncDataTemplate<string>((s, _) =>
|
||||
new TextBlock
|
||||
{
|
||||
Text = s,
|
||||
Foreground = Brushes.Gray,
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
}),
|
||||
};
|
||||
_chatScrollViewer = new ScrollViewer
|
||||
{
|
||||
Content = chatItemsControl,
|
||||
Background = Brushes.Black,
|
||||
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
|
||||
VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
|
||||
Padding = new Thickness(0),
|
||||
};
|
||||
|
||||
_hotbarIndicators = new TextBlock[9];
|
||||
|
||||
Content = BuildRootLayout();
|
||||
UpdateTitle();
|
||||
UpdateInfoPanel();
|
||||
|
||||
_chatScrollToBottom = true;
|
||||
_chatScrollViewer.ScrollChanged += OnChatScrollChanged;
|
||||
}
|
||||
|
||||
private bool _chatScrollToBottom = true;
|
||||
|
||||
private void OnChatScrollChanged(object? sender, ScrollChangedEventArgs e)
|
||||
{
|
||||
if (!_chatScrollToBottom) return;
|
||||
var sv = _chatScrollViewer;
|
||||
if (sv.Extent.Height > sv.Viewport.Height)
|
||||
{
|
||||
sv.Offset = new Vector(0, sv.Extent.Height - sv.Viewport.Height);
|
||||
_chatScrollToBottom = false;
|
||||
}
|
||||
}
|
||||
|
||||
private Control BuildRootLayout()
|
||||
{
|
||||
// Layout (top-down):
|
||||
// Title
|
||||
// [InfoPanel(right)] [InventoryGrid(left)] <-- inventory area
|
||||
// ChatScrollViewer (full width, fills remaining)
|
||||
|
||||
var inventoryArea = BuildMainArea();
|
||||
DockPanel.SetDock(_titleText, Dock.Top);
|
||||
DockPanel.SetDock(inventoryArea, Dock.Top);
|
||||
|
||||
var mainContent = new DockPanel
|
||||
{
|
||||
Children = { _titleText, inventoryArea, _chatScrollViewer }
|
||||
};
|
||||
|
||||
return new Panel
|
||||
{
|
||||
Background = Brushes.Black,
|
||||
Children = { mainContent, _overlayCanvas }
|
||||
};
|
||||
}
|
||||
|
||||
private Control BuildMainArea()
|
||||
{
|
||||
var infoPanel = BuildInfoPanel();
|
||||
DockPanel.SetDock(infoPanel, Dock.Right);
|
||||
|
||||
return new DockPanel
|
||||
{
|
||||
Children = { infoPanel, BuildInventoryPanel() }
|
||||
};
|
||||
}
|
||||
|
||||
private Control BuildInfoPanel()
|
||||
{
|
||||
return new Border
|
||||
{
|
||||
BorderThickness = new Thickness(1),
|
||||
BorderBrush = Brushes.Gray,
|
||||
Padding = new Thickness(1),
|
||||
Width = 24,
|
||||
Child = new StackPanel
|
||||
{
|
||||
Children =
|
||||
{
|
||||
new TextBlock { Text = Translations.tui_inventory_item_info, FontWeight = FontWeight.Bold, Foreground = Brushes.Cyan },
|
||||
_infoDetailBorder,
|
||||
new TextBlock { Text = Translations.tui_inventory_held_item, FontWeight = FontWeight.Bold, Foreground = Brushes.Yellow, Margin = new Thickness(0, 1, 0, 0) },
|
||||
_cursorItemText,
|
||||
new TextBlock { Text = Translations.tui_inventory_controls, FontWeight = FontWeight.Bold, Foreground = Brushes.Green, Margin = new Thickness(0, 1, 0, 0) },
|
||||
_helpText,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Control BuildInventoryPanel()
|
||||
{
|
||||
var root = new StackPanel
|
||||
{
|
||||
Spacing = 0,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
};
|
||||
|
||||
root.Children.Add(BuildTopSection());
|
||||
root.Children.Add(new Border { Height = 1 });
|
||||
root.Children.Add(BuildSlotGrid(_vm.MainInventorySlots, 9));
|
||||
root.Children.Add(BuildHotbarSection());
|
||||
|
||||
return new Border
|
||||
{
|
||||
BorderThickness = new Thickness(1),
|
||||
BorderBrush = Brushes.Gray,
|
||||
Child = root,
|
||||
};
|
||||
}
|
||||
|
||||
private Control BuildTopSection()
|
||||
{
|
||||
var row = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
};
|
||||
|
||||
var offPanel = new StackPanel
|
||||
{
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(0, 0, 1, 0),
|
||||
};
|
||||
offPanel.Children.Add(new TextBlock
|
||||
{
|
||||
Text = Translations.tui_inventory_offhand,
|
||||
Foreground = BrEquipLbl,
|
||||
FontWeight = FontWeight.Bold,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
});
|
||||
offPanel.Children.Add(CreateSlotCell(_vm.OffhandSlot, 0, 0));
|
||||
row.Children.Add(offPanel);
|
||||
|
||||
var equipGrid = new Grid
|
||||
{
|
||||
RowDefinitions = new RowDefinitions("Auto,Auto"),
|
||||
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto"),
|
||||
};
|
||||
|
||||
void AddEquipSlot(int r, int gc, string label, int eqIdx)
|
||||
{
|
||||
var lbl = MakeLabel(label);
|
||||
Grid.SetRow(lbl, r); Grid.SetColumn(lbl, gc);
|
||||
equipGrid.Children.Add(lbl);
|
||||
var btn = CreateSlotCell(_vm.EquipmentSlots[eqIdx], r, gc / 2);
|
||||
Grid.SetRow(btn, r); Grid.SetColumn(btn, gc + 1);
|
||||
equipGrid.Children.Add(btn);
|
||||
}
|
||||
|
||||
AddEquipSlot(0, 0, Translations.tui_inventory_equip_head, 0);
|
||||
AddEquipSlot(0, 2, Translations.tui_inventory_equip_body, 1);
|
||||
AddEquipSlot(1, 0, Translations.tui_inventory_equip_legs, 2);
|
||||
AddEquipSlot(1, 2, Translations.tui_inventory_equip_feet, 3);
|
||||
|
||||
row.Children.Add(equipGrid);
|
||||
row.Children.Add(new Border { Width = _topGap });
|
||||
|
||||
var craftGrid = new Grid
|
||||
{
|
||||
RowDefinitions = new RowDefinitions("Auto,Auto"),
|
||||
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto"),
|
||||
};
|
||||
|
||||
for (int ci = 0; ci < 4; ci++)
|
||||
{
|
||||
int cr = ci / 2, cc = ci % 2;
|
||||
var cs = CreateSlotCell(_vm.CraftingInputSlots[ci], cr, cc);
|
||||
Grid.SetRow(cs, cr);
|
||||
Grid.SetColumn(cs, cc);
|
||||
craftGrid.Children.Add(cs);
|
||||
}
|
||||
|
||||
var arrowTb = new TextBlock
|
||||
{
|
||||
Text = "=>",
|
||||
Foreground = Brushes.White,
|
||||
FontWeight = FontWeight.Bold,
|
||||
VerticalAlignment = VerticalAlignment.Top,
|
||||
Padding = new Thickness(1, 0),
|
||||
};
|
||||
Grid.SetRow(arrowTb, 1); Grid.SetColumn(arrowTb, 2);
|
||||
craftGrid.Children.Add(arrowTb);
|
||||
|
||||
var craftOutPanel = new StackPanel
|
||||
{
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
};
|
||||
craftOutPanel.Children.Add(new TextBlock
|
||||
{
|
||||
Text = Translations.tui_inventory_output,
|
||||
Foreground = BrEquipLbl,
|
||||
FontWeight = FontWeight.Bold,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
});
|
||||
craftOutPanel.Children.Add(CreateSlotCell(_vm.CraftingOutputSlot, 0, 1));
|
||||
Grid.SetRow(craftOutPanel, 0); Grid.SetColumn(craftOutPanel, 3);
|
||||
Grid.SetRowSpan(craftOutPanel, 2);
|
||||
craftGrid.Children.Add(craftOutPanel);
|
||||
|
||||
row.Children.Add(craftGrid);
|
||||
return row;
|
||||
}
|
||||
|
||||
private Control BuildHotbarSection()
|
||||
{
|
||||
var panel = new StackPanel { Spacing = 0 };
|
||||
|
||||
var numberRow = new StackPanel
|
||||
{
|
||||
Orientation = Orientation.Horizontal,
|
||||
HorizontalAlignment = HorizontalAlignment.Center,
|
||||
};
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
bool active = i == _currentHotbarSlot;
|
||||
string label = active ? $"{i + 1} \u25bc" : $" {i + 1} ";
|
||||
|
||||
var tb = new TextBlock
|
||||
{
|
||||
Text = label,
|
||||
Width = _slotW,
|
||||
TextAlignment = TextAlignment.Center,
|
||||
Foreground = active ? Brushes.LightGreen : Brushes.DarkCyan,
|
||||
FontWeight = FontWeight.Bold,
|
||||
};
|
||||
_hotbarIndicators[i] = tb;
|
||||
numberRow.Children.Add(tb);
|
||||
}
|
||||
panel.Children.Add(numberRow);
|
||||
panel.Children.Add(BuildSlotGrid(_vm.HotbarSlots, 9));
|
||||
return panel;
|
||||
}
|
||||
|
||||
private TextBlock MakeLabel(string text)
|
||||
{
|
||||
return new TextBlock
|
||||
{
|
||||
Text = text,
|
||||
Foreground = BrEquipLbl,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
Margin = new Thickness(1, 0, 0, 0),
|
||||
FontWeight = FontWeight.Bold,
|
||||
};
|
||||
}
|
||||
|
||||
private Control BuildSlotGrid(ObservableCollection<SlotViewModel> slots, int columns)
|
||||
{
|
||||
var grid = new Grid();
|
||||
int rows = (slots.Count + columns - 1) / columns;
|
||||
|
||||
for (int r = 0; r < rows; r++)
|
||||
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
|
||||
for (int c = 0; c < columns; c++)
|
||||
grid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));
|
||||
|
||||
for (int i = 0; i < slots.Count; i++)
|
||||
{
|
||||
int row = i / columns;
|
||||
int col = i % columns;
|
||||
var cell = CreateSlotCell(slots[i], row, col);
|
||||
Grid.SetRow(cell, row);
|
||||
Grid.SetColumn(cell, col);
|
||||
grid.Children.Add(cell);
|
||||
}
|
||||
|
||||
return grid;
|
||||
}
|
||||
|
||||
private static IBrush GetSlotBg(bool isEmpty, int row, int col)
|
||||
{
|
||||
bool isA = (row + col) % 2 == 0;
|
||||
return isEmpty
|
||||
? (isA ? BrSlotEmptyA : BrSlotEmptyB)
|
||||
: (isA ? BrSlotFillA : BrSlotFillB);
|
||||
}
|
||||
|
||||
private Border CreateSlotCell(SlotViewModel slot, int row = 0, int col = 0)
|
||||
{
|
||||
var nameTb = new TextBlock
|
||||
{
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
VerticalAlignment = VerticalAlignment.Top,
|
||||
};
|
||||
|
||||
var countTb = new TextBlock
|
||||
{
|
||||
Foreground = BrCount,
|
||||
FontWeight = FontWeight.Bold,
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
VerticalAlignment = VerticalAlignment.Bottom,
|
||||
};
|
||||
|
||||
ApplySlotVisual(slot, nameTb, countTb);
|
||||
|
||||
int r = row, c = col;
|
||||
var border = new Border
|
||||
{
|
||||
Width = _slotW,
|
||||
Height = _slotH,
|
||||
Background = GetSlotBg(slot.IsEmpty, r, c),
|
||||
Child = new Panel
|
||||
{
|
||||
Children = { nameTb, countTb },
|
||||
},
|
||||
Tag = (slot, r, c),
|
||||
};
|
||||
|
||||
border.PointerPressed += OnSlotPointerPressed;
|
||||
border.PointerEntered += OnSlotPointerEnter;
|
||||
border.PointerExited += OnSlotPointerExit;
|
||||
border.PointerMoved += OnSlotPointerMoved;
|
||||
|
||||
slot.PropertyChanged += (_, _) =>
|
||||
{
|
||||
ApplySlotVisual(slot, nameTb, countTb);
|
||||
border.Background = GetSlotBg(slot.IsEmpty, r, c);
|
||||
};
|
||||
|
||||
return border;
|
||||
}
|
||||
|
||||
private void ApplySlotVisual(SlotViewModel slot, TextBlock nameTb, TextBlock countTb)
|
||||
{
|
||||
if (slot.IsEmpty)
|
||||
{
|
||||
nameTb.Text = "";
|
||||
nameTb.Foreground = BrDim;
|
||||
countTb.Text = "";
|
||||
}
|
||||
else
|
||||
{
|
||||
nameTb.Text = slot.ItemDisplayText;
|
||||
nameTb.Foreground = BrName;
|
||||
countTb.Text = slot.CountDisplay;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSlotPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
if (sender is not Border border || border.Tag is not (SlotViewModel slot, int, int))
|
||||
return;
|
||||
|
||||
SetHover(border, slot);
|
||||
|
||||
var point = e.GetCurrentPoint(border);
|
||||
bool isShift = (e.KeyModifiers & KeyModifiers.Shift) != 0;
|
||||
|
||||
WindowActionType action;
|
||||
if (point.Properties.IsRightButtonPressed)
|
||||
action = isShift ? WindowActionType.ShiftRightClick : WindowActionType.RightClick;
|
||||
else
|
||||
action = isShift ? WindowActionType.ShiftClick : WindowActionType.LeftClick;
|
||||
|
||||
_vm.PerformAction(slot.SlotId, action);
|
||||
UpdateInfoPanel();
|
||||
UpdateHeldItemFloater(e);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private void OnSlotPointerEnter(object? sender, PointerEventArgs e)
|
||||
{
|
||||
if (sender is Border b && b.Tag is (SlotViewModel slot, int, int))
|
||||
{
|
||||
SetHover(b, slot);
|
||||
UpdateHeldItemFloater(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSlotPointerMoved(object? sender, PointerEventArgs e)
|
||||
{
|
||||
if (sender is Border b && b.Tag is (SlotViewModel slot, int, int))
|
||||
{
|
||||
SetHover(b, slot);
|
||||
UpdateHeldItemFloater(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSlotPointerExit(object? sender, PointerEventArgs e)
|
||||
{
|
||||
if (sender is Border b && b.Tag is (SlotViewModel slot, int row, int col))
|
||||
b.Background = GetSlotBg(slot.IsEmpty, row, col);
|
||||
}
|
||||
|
||||
private void SetHover(Border border, SlotViewModel slot)
|
||||
{
|
||||
if (_lastHoveredSlotBorder != null && _lastHoveredSlotBorder != border)
|
||||
{
|
||||
if (_lastHoveredSlotBorder.Tag is (SlotViewModel oldSlot, int or, int oc))
|
||||
_lastHoveredSlotBorder.Background = GetSlotBg(oldSlot.IsEmpty, or, oc);
|
||||
}
|
||||
|
||||
_lastHoveredSlotBorder = border;
|
||||
border.Background = BrSlotHover;
|
||||
_vm.HoveredSlot = slot;
|
||||
UpdateInfoPanel();
|
||||
}
|
||||
|
||||
private void UpdateHeldItemFloater(PointerEventArgs e)
|
||||
{
|
||||
if (!_vm.HasCursorItem)
|
||||
{
|
||||
_heldItemFloater.IsVisible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_heldItemFloaterName.Text = _vm.CursorItemInfo;
|
||||
_heldItemFloaterCount.Text = "";
|
||||
|
||||
try
|
||||
{
|
||||
var pos = e.GetPosition(_overlayCanvas);
|
||||
double left = pos.X + 2;
|
||||
double remainingW = _termW - left - 2;
|
||||
int maxW = Math.Max(8, (int)remainingW);
|
||||
_heldItemFloater.MaxWidth = maxW;
|
||||
Canvas.SetLeft(_heldItemFloater, left);
|
||||
Canvas.SetTop(_heldItemFloater, pos.Y);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_heldItemFloater.MaxWidth = 24;
|
||||
Canvas.SetLeft(_heldItemFloater, 0);
|
||||
Canvas.SetTop(_heldItemFloater, 0);
|
||||
}
|
||||
|
||||
_heldItemFloater.IsVisible = true;
|
||||
}
|
||||
|
||||
private void UpdateInfoPanel()
|
||||
{
|
||||
_infoDetailText.Text = _vm.HoveredSlotDetailText;
|
||||
|
||||
bool hasHoveredItem = _vm.HoveredSlot != null && !_vm.HoveredSlot.IsEmpty;
|
||||
_infoDetailBorder.Background = hasHoveredItem ? BrInfoHighlight : Brushes.Transparent;
|
||||
|
||||
if (_vm.HasCursorItem)
|
||||
{
|
||||
_cursorItemText.Text = _vm.CursorItemInfo;
|
||||
_cursorItemText.Foreground = Brushes.Yellow;
|
||||
}
|
||||
else
|
||||
{
|
||||
_cursorItemText.Text = Translations.tui_inventory_cursor_empty;
|
||||
_cursorItemText.Foreground = BrDim;
|
||||
_heldItemFloater.IsVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateTitle()
|
||||
{
|
||||
_titleText.Text = _vm.Title;
|
||||
}
|
||||
|
||||
private void CloseInventory()
|
||||
{
|
||||
if (ConsoleIO.Backend is TuiConsoleBackend tuiBackend)
|
||||
tuiBackend.GetView()?.HideOverlay();
|
||||
else
|
||||
(Application.Current?.ApplicationLifetime as IControlledApplicationLifetime)?.Shutdown();
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
base.OnKeyDown(e);
|
||||
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Escape:
|
||||
case Key.E:
|
||||
CloseInventory();
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.C:
|
||||
if ((e.KeyModifiers & KeyModifiers.Shift) != 0 &&
|
||||
_vm.HoveredSlot != null && !_vm.HoveredSlot.IsEmpty)
|
||||
{
|
||||
_vm.PerformAction(_vm.HoveredSlot.SlotId, WindowActionType.ShiftClick);
|
||||
UpdateInfoPanel();
|
||||
}
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.Q:
|
||||
if (_vm.HoveredSlot != null && !_vm.HoveredSlot.IsEmpty)
|
||||
{
|
||||
var action = (e.KeyModifiers & KeyModifiers.Control) != 0
|
||||
? WindowActionType.DropItemStack
|
||||
: WindowActionType.DropItem;
|
||||
_vm.PerformAction(_vm.HoveredSlot.SlotId, action);
|
||||
UpdateInfoPanel();
|
||||
}
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.R:
|
||||
_vm.RefreshFromContainer();
|
||||
_currentHotbarSlot = _vm.Handler.GetCurrentSlot();
|
||||
UpdateHotbarIndicators();
|
||||
UpdateInfoPanel();
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateHotbarIndicators()
|
||||
{
|
||||
for (int i = 0; i < 9; i++)
|
||||
{
|
||||
bool active = i == _currentHotbarSlot;
|
||||
_hotbarIndicators[i].Text = active ? $"{i + 1} \u25bc" : $" {i + 1} ";
|
||||
_hotbarIndicators[i].Foreground = active ? Brushes.LightGreen : Brushes.DarkCyan;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
|
||||
{
|
||||
base.OnAttachedToVisualTree(e);
|
||||
Focusable = true;
|
||||
Focus();
|
||||
AddHandler(KeyDownEvent, OnTunnelKeyDown, Avalonia.Interactivity.RoutingStrategies.Tunnel);
|
||||
SizeChanged += OnViewSizeChanged;
|
||||
}
|
||||
|
||||
private void OnTunnelKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Escape)
|
||||
{
|
||||
CloseInventory();
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnViewSizeChanged(object? sender, SizeChangedEventArgs e)
|
||||
{
|
||||
int newW, newH;
|
||||
try
|
||||
{
|
||||
newW = System.Console.WindowWidth;
|
||||
newH = System.Console.WindowHeight;
|
||||
}
|
||||
catch { return; }
|
||||
|
||||
if (newW == _lastTermW && newH == _lastTermH) return;
|
||||
|
||||
_vm.RefreshFromContainer();
|
||||
_currentHotbarSlot = _vm.Handler.GetCurrentSlot();
|
||||
RebuildUi();
|
||||
Focus();
|
||||
}
|
||||
|
||||
protected override void OnGotFocus(GotFocusEventArgs e)
|
||||
{
|
||||
base.OnGotFocus(e);
|
||||
Focusable = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
182
MinecraftClient/Tui/InventoryTuiHost.cs
Normal file
182
MinecraftClient/Tui/InventoryTuiHost.cs
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
using System;
|
||||
using System.Threading;
|
||||
using Avalonia;
|
||||
using Avalonia.Threading;
|
||||
using Consolonia;
|
||||
using MinecraftClient.Inventory;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
/// <summary>
|
||||
/// Manages the lifecycle of the inventory TUI.
|
||||
/// In TUI mode: opens as a Consolonia dialog window.
|
||||
/// In classic mode: launches standalone Consolonia on a dedicated thread.
|
||||
/// </summary>
|
||||
public static class InventoryTuiHost
|
||||
{
|
||||
private static volatile bool _isRunning;
|
||||
private static bool _classicEverLaunched;
|
||||
|
||||
public static McClient? ActiveHandler { get; private set; }
|
||||
public static int ActiveWindowId { get; private set; }
|
||||
|
||||
public static bool IsRunning => _isRunning;
|
||||
|
||||
/// <summary>
|
||||
/// Whether the TUI can be launched (classic mode has a one-shot limit).
|
||||
/// </summary>
|
||||
public static bool CanLaunch
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_isRunning) return false;
|
||||
if (ConsoleIO.Backend is TuiConsoleBackend) return true;
|
||||
return !_classicEverLaunched;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called before standalone TUI takes over the terminal (classic mode only).
|
||||
/// </summary>
|
||||
public static Action? OnSuspendConsole { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Called after standalone TUI releases the terminal (classic mode only).
|
||||
/// </summary>
|
||||
public static Action? OnResumeConsole { get; set; }
|
||||
|
||||
public static bool Launch(McClient handler, int windowId)
|
||||
{
|
||||
if (_isRunning)
|
||||
return false;
|
||||
|
||||
Container? container = handler.GetInventory(windowId);
|
||||
if (container == null)
|
||||
return false;
|
||||
|
||||
_isRunning = true;
|
||||
ActiveHandler = handler;
|
||||
ActiveWindowId = windowId;
|
||||
|
||||
if (ConsoleIO.Backend is TuiConsoleBackend)
|
||||
{
|
||||
LaunchAsDialog();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_classicEverLaunched)
|
||||
{
|
||||
_isRunning = false;
|
||||
ActiveHandler = null;
|
||||
return false;
|
||||
}
|
||||
var tuiThread = new Thread(RunClassicTui) { Name = "InventoryTUI", IsBackground = false };
|
||||
tuiThread.Start();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Open inventory as an overlay panel within the main TUI view.
|
||||
/// </summary>
|
||||
private static void LaunchAsDialog()
|
||||
{
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var view = TuiConsoleBackend.Instance?.GetView();
|
||||
if (view != null)
|
||||
{
|
||||
var content = new InventoryMainView();
|
||||
view.ShowOverlay(content, () =>
|
||||
{
|
||||
ActiveHandler = null;
|
||||
_isRunning = false;
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
ActiveHandler = null;
|
||||
_isRunning = false;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ConsoleIO.WriteLineFormatted($"§c[InventoryTUI] Error: {ex.Message}");
|
||||
ConsoleIO.WriteLineFormatted($"§c[InventoryTUI] Stack: {ex.StackTrace}");
|
||||
if (ex.InnerException != null)
|
||||
ConsoleIO.WriteLineFormatted($"§c[InventoryTUI] Inner: {ex.InnerException.Message}");
|
||||
ActiveHandler = null;
|
||||
_isRunning = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Classic mode: run standalone Consolonia on a dedicated thread.
|
||||
/// </summary>
|
||||
private static void RunClassicTui()
|
||||
{
|
||||
try
|
||||
{
|
||||
OnSuspendConsole?.Invoke();
|
||||
_classicEverLaunched = true;
|
||||
|
||||
AppBuilder builder = AppBuilder.Configure<InventoryApp>()
|
||||
.UseConsolonia()
|
||||
.UseAutoDetectedConsole()
|
||||
.LogToException();
|
||||
|
||||
builder.StartWithConsoleLifetime(Array.Empty<string>());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Console.Error.WriteLine($"[InventoryTUI] Error: {ex.Message}");
|
||||
System.Console.Error.WriteLine($"[InventoryTUI] Stack: {ex.StackTrace}");
|
||||
if (ex.InnerException != null)
|
||||
System.Console.Error.WriteLine($"[InventoryTUI] Inner: {ex.InnerException}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
RestoreTerminalState();
|
||||
OnResumeConsole?.Invoke();
|
||||
ActiveHandler = null;
|
||||
_isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void RestoreTerminalState()
|
||||
{
|
||||
try
|
||||
{
|
||||
System.Console.Write("\x1b[?1049l");
|
||||
System.Console.Write("\x1b[?25h");
|
||||
System.Console.Write("\x1b[?1000l");
|
||||
System.Console.Write("\x1b[?1002l");
|
||||
System.Console.Write("\x1b[?1003l");
|
||||
System.Console.Write("\x1b[?1006l");
|
||||
System.Console.Write("\x1b[?2004l");
|
||||
System.Console.Write("\x1b[0m");
|
||||
System.Console.Write("\x1b(B");
|
||||
System.Console.Out.Flush();
|
||||
|
||||
try
|
||||
{
|
||||
using var proc = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
|
||||
{
|
||||
FileName = "stty",
|
||||
Arguments = "sane",
|
||||
UseShellExecute = false,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
});
|
||||
proc?.WaitForExit(2000);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
220
MinecraftClient/Tui/InventoryViewModel.cs
Normal file
220
MinecraftClient/Tui/InventoryViewModel.cs
Normal file
|
|
@ -0,0 +1,220 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using MinecraftClient.Inventory;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class InventoryViewModel : INotifyPropertyChanged
|
||||
{
|
||||
private SlotViewModel? _hoveredSlot;
|
||||
private string _title = "";
|
||||
private string _statusText = "";
|
||||
private string _cursorItemInfo = "";
|
||||
private bool _hasCursorItem;
|
||||
|
||||
public McClient Handler { get; }
|
||||
public int WindowId { get; }
|
||||
|
||||
public ObservableCollection<SlotViewModel> EquipmentSlots { get; } = new();
|
||||
public ObservableCollection<SlotViewModel> CraftingInputSlots { get; } = new();
|
||||
public SlotViewModel CraftingOutputSlot { get; }
|
||||
public ObservableCollection<SlotViewModel> MainInventorySlots { get; } = new();
|
||||
public ObservableCollection<SlotViewModel> HotbarSlots { get; } = new();
|
||||
public SlotViewModel OffhandSlot { get; }
|
||||
|
||||
public string Title
|
||||
{
|
||||
get => _title;
|
||||
set { _title = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public string StatusText
|
||||
{
|
||||
get => _statusText;
|
||||
set { _statusText = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public string CursorItemInfo
|
||||
{
|
||||
get => _cursorItemInfo;
|
||||
set { _cursorItemInfo = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public bool HasCursorItem
|
||||
{
|
||||
get => _hasCursorItem;
|
||||
set { _hasCursorItem = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public SlotViewModel? HoveredSlot
|
||||
{
|
||||
get => _hoveredSlot;
|
||||
set
|
||||
{
|
||||
if (_hoveredSlot != null)
|
||||
_hoveredSlot.IsHovered = false;
|
||||
_hoveredSlot = value;
|
||||
if (_hoveredSlot != null)
|
||||
_hoveredSlot.IsHovered = true;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(HoveredSlotDetailText));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Multi-line detail text for the hovered slot.
|
||||
/// </summary>
|
||||
public string HoveredSlotDetailText
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_hoveredSlot == null)
|
||||
return Translations.tui_inventory_hover_hint;
|
||||
|
||||
if (_hoveredSlot.IsEmpty)
|
||||
return $"Slot #{_hoveredSlot.SlotId}\n{Translations.tui_inventory_slot_empty}";
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine(_hoveredSlot.ItemTypeName);
|
||||
sb.AppendLine(string.Format(Translations.tui_inventory_slot_detail, _hoveredSlot.SlotId, _hoveredSlot.ItemCount));
|
||||
|
||||
string fullInfo = _hoveredSlot.FullInfo;
|
||||
if (!string.IsNullOrEmpty(fullInfo))
|
||||
{
|
||||
string[] parts = fullInfo.Split(" | ");
|
||||
for (int i = 1; i < parts.Length; i++)
|
||||
sb.AppendLine(parts[i].Trim());
|
||||
}
|
||||
|
||||
return sb.ToString().TrimEnd();
|
||||
}
|
||||
}
|
||||
|
||||
private Dictionary<int, SlotViewModel> _slotMap = new();
|
||||
private int _nameMaxLen = 9;
|
||||
private int _nameMaxLines = 1;
|
||||
|
||||
public InventoryViewModel(McClient handler, int windowId)
|
||||
{
|
||||
Handler = handler;
|
||||
WindowId = windowId;
|
||||
|
||||
CraftingOutputSlot = new SlotViewModel(0);
|
||||
OffhandSlot = new SlotViewModel(45);
|
||||
|
||||
InitializeSlots();
|
||||
RefreshFromContainer();
|
||||
}
|
||||
|
||||
public void SetSlotDisplayParams(int maxWidth, int maxLines)
|
||||
{
|
||||
_nameMaxLen = maxWidth;
|
||||
_nameMaxLines = maxLines;
|
||||
foreach (var kvp in _slotMap)
|
||||
{
|
||||
kvp.Value.NameMaxWidth = maxWidth;
|
||||
kvp.Value.NameMaxLines = maxLines;
|
||||
}
|
||||
RefreshFromContainer();
|
||||
}
|
||||
|
||||
private void InitializeSlots()
|
||||
{
|
||||
_slotMap.Clear();
|
||||
|
||||
_slotMap[0] = CraftingOutputSlot;
|
||||
|
||||
for (int i = 1; i <= 4; i++)
|
||||
{
|
||||
var slot = new SlotViewModel(i);
|
||||
CraftingInputSlots.Add(slot);
|
||||
_slotMap[i] = slot;
|
||||
}
|
||||
|
||||
for (int i = 5; i <= 8; i++)
|
||||
{
|
||||
var slot = new SlotViewModel(i);
|
||||
EquipmentSlots.Add(slot);
|
||||
_slotMap[i] = slot;
|
||||
}
|
||||
|
||||
for (int i = 9; i <= 35; i++)
|
||||
{
|
||||
var slot = new SlotViewModel(i);
|
||||
MainInventorySlots.Add(slot);
|
||||
_slotMap[i] = slot;
|
||||
}
|
||||
|
||||
for (int i = 36; i <= 44; i++)
|
||||
{
|
||||
int hotbarIdx = i - 36;
|
||||
var slot = new SlotViewModel(i, isHotbar: true, hotbarIndex: hotbarIdx);
|
||||
HotbarSlots.Add(slot);
|
||||
_slotMap[i] = slot;
|
||||
}
|
||||
|
||||
_slotMap[45] = OffhandSlot;
|
||||
}
|
||||
|
||||
public void RefreshFromContainer()
|
||||
{
|
||||
Inventory.Container? container = Handler.GetInventory(WindowId);
|
||||
if (container == null)
|
||||
{
|
||||
StatusText = Translations.tui_inventory_container_not_found;
|
||||
return;
|
||||
}
|
||||
|
||||
Title = string.Format(Translations.tui_inventory_title, WindowId, container.Title);
|
||||
|
||||
foreach (var kvp in _slotMap)
|
||||
{
|
||||
Item? item = container.Items.TryGetValue(kvp.Key, out var it) ? it : null;
|
||||
kvp.Value.Update(item);
|
||||
}
|
||||
|
||||
UpdateCursorItem(container);
|
||||
int itemCount = 0;
|
||||
foreach (var kvp in container.Items)
|
||||
{
|
||||
if (kvp.Key >= 0 && !kvp.Value.IsEmpty)
|
||||
itemCount++;
|
||||
}
|
||||
StatusText = string.Format(Translations.tui_inventory_item_count, itemCount);
|
||||
|
||||
OnPropertyChanged(nameof(HoveredSlotDetailText));
|
||||
}
|
||||
|
||||
private void UpdateCursorItem(Inventory.Container container)
|
||||
{
|
||||
if (container.Items.TryGetValue(-1, out var cursorItem) && !cursorItem.IsEmpty)
|
||||
{
|
||||
CursorItemInfo = $"x{cursorItem.Count} {cursorItem.GetTypeString()}";
|
||||
HasCursorItem = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
CursorItemInfo = "";
|
||||
HasCursorItem = false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool PerformAction(int slotId, WindowActionType action)
|
||||
{
|
||||
bool result = Handler.DoWindowAction(WindowId, slotId, action);
|
||||
RefreshFromContainer();
|
||||
return result;
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
private void OnPropertyChanged([CallerMemberName] string? name = null)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
932
MinecraftClient/Tui/MainTuiView.cs
Normal file
932
MinecraftClient/Tui/MainTuiView.cs
Normal file
|
|
@ -0,0 +1,932 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Primitives;
|
||||
using Avalonia.Controls.Templates;
|
||||
using Avalonia.Input;
|
||||
using Avalonia.Layout;
|
||||
using Avalonia.Media;
|
||||
using Avalonia.Threading;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class MainTuiView : UserControl
|
||||
{
|
||||
private const int MaxLogLines = 5000;
|
||||
private const int CtrlCDoublePressMsec = 1500;
|
||||
|
||||
private readonly ObservableCollection<string> _logLines = new();
|
||||
private readonly ObservableCollection<Control> _logControls = new();
|
||||
private readonly ItemsControl _logItemsControl;
|
||||
private readonly ScrollViewer _logScrollViewer;
|
||||
private readonly TextBox _commandInput;
|
||||
private bool _autoScroll = true;
|
||||
private bool _programmaticScroll;
|
||||
private readonly ObservableCollection<string> _commandHistory = new();
|
||||
private int _historyIndex = -1;
|
||||
|
||||
private readonly Panel _rootPanel;
|
||||
private readonly DockPanel _mainContent;
|
||||
private Control? _overlayContent;
|
||||
private Action? _overlayCloseCallback;
|
||||
|
||||
private readonly TextBlock _statusBar;
|
||||
private readonly Border _notificationBorder;
|
||||
private readonly TextBlock _notificationText;
|
||||
private long _lastCtrlCTicks;
|
||||
private long _lastLogClickTicks;
|
||||
private const int DoubleClickMsec = 500;
|
||||
|
||||
private readonly Border _suggestionBorder;
|
||||
private readonly StackPanel _suggestionPanel;
|
||||
private CommandSuggestion[] _suggestions = Array.Empty<CommandSuggestion>();
|
||||
private (int Start, int End) _suggestionRange;
|
||||
private int _selectedSuggestionIndex = -1;
|
||||
private int _suggestionViewTop;
|
||||
private bool _acceptingSuggestion;
|
||||
private bool _tabCycling;
|
||||
|
||||
private int MaxVisibleSuggestions =>
|
||||
Math.Max(1, Settings.Config.Console.CommandSuggestion.Max_Displayed_Suggestions);
|
||||
|
||||
public MainTuiView()
|
||||
{
|
||||
Background = Brushes.Black;
|
||||
|
||||
_statusBar = new TextBlock
|
||||
{
|
||||
Foreground = Brushes.Gray,
|
||||
Background = Brushes.Black,
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
IsVisible = false,
|
||||
};
|
||||
|
||||
_logItemsControl = new ItemsControl
|
||||
{
|
||||
ItemsSource = _logControls,
|
||||
Focusable = false,
|
||||
};
|
||||
|
||||
_logScrollViewer = new ScrollViewer
|
||||
{
|
||||
Content = _logItemsControl,
|
||||
Background = Brushes.Black,
|
||||
HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
|
||||
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
|
||||
Padding = new Thickness(0),
|
||||
Focusable = false,
|
||||
};
|
||||
|
||||
_logScrollViewer.ScrollChanged += OnLogScrollChanged;
|
||||
_logScrollViewer.PointerPressed += OnLogAreaPointerPressed;
|
||||
|
||||
_commandInput = new TextBox
|
||||
{
|
||||
Watermark = "",
|
||||
Foreground = Brushes.White,
|
||||
Background = Brushes.Black,
|
||||
BorderThickness = new Thickness(0),
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
MinHeight = 1,
|
||||
};
|
||||
|
||||
_commandInput.AddHandler(KeyDownEvent, OnCommandKeyDown, Avalonia.Interactivity.RoutingStrategies.Tunnel);
|
||||
_commandInput.TextChanged += OnCommandTextChanged;
|
||||
|
||||
var promptLabel = new TextBlock
|
||||
{
|
||||
Text = "> ",
|
||||
Foreground = Brushes.Cyan,
|
||||
VerticalAlignment = VerticalAlignment.Center,
|
||||
FontWeight = FontWeight.Bold,
|
||||
};
|
||||
|
||||
var inputRow = new DockPanel
|
||||
{
|
||||
Background = Brushes.Black,
|
||||
Children =
|
||||
{
|
||||
SetDock(promptLabel, Dock.Left),
|
||||
_commandInput
|
||||
}
|
||||
};
|
||||
|
||||
_notificationText = new TextBlock
|
||||
{
|
||||
Foreground = Brushes.Yellow,
|
||||
Padding = new Thickness(1, 0),
|
||||
};
|
||||
_notificationBorder = new Border
|
||||
{
|
||||
Background = new SolidColorBrush(Color.FromRgb(60, 50, 20)),
|
||||
BorderBrush = Brushes.Yellow,
|
||||
BorderThickness = new Thickness(1),
|
||||
Child = _notificationText,
|
||||
IsVisible = false,
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
VerticalAlignment = VerticalAlignment.Top,
|
||||
};
|
||||
|
||||
_suggestionPanel = new StackPanel
|
||||
{
|
||||
Orientation = Avalonia.Layout.Orientation.Vertical,
|
||||
};
|
||||
_suggestionPanel.PointerWheelChanged += OnSuggestionWheelChanged;
|
||||
_suggestionBorder = new Border
|
||||
{
|
||||
Background = new SolidColorBrush(Color.FromRgb(30, 30, 30)),
|
||||
BorderBrush = new SolidColorBrush(Color.FromRgb(80, 80, 80)),
|
||||
BorderThickness = new Thickness(1),
|
||||
Child = _suggestionPanel,
|
||||
IsVisible = false,
|
||||
HorizontalAlignment = HorizontalAlignment.Left,
|
||||
VerticalAlignment = VerticalAlignment.Bottom,
|
||||
Margin = new Thickness(0, 0, 0, 1),
|
||||
};
|
||||
|
||||
_mainContent = new DockPanel
|
||||
{
|
||||
Background = Brushes.Black,
|
||||
Children =
|
||||
{
|
||||
SetDock(_statusBar, Dock.Top),
|
||||
SetDock(inputRow, Dock.Bottom),
|
||||
_logScrollViewer
|
||||
}
|
||||
};
|
||||
|
||||
_rootPanel = new Panel
|
||||
{
|
||||
Background = Brushes.Black,
|
||||
Children = { _mainContent, _notificationBorder, _suggestionBorder }
|
||||
};
|
||||
|
||||
Content = _rootPanel;
|
||||
|
||||
StartStatusBarTimer();
|
||||
}
|
||||
|
||||
private static Control SetDock(Control control, Dock dock)
|
||||
{
|
||||
DockPanel.SetDock(control, dock);
|
||||
return control;
|
||||
}
|
||||
|
||||
#region Log output
|
||||
|
||||
public void AppendLogLine(string text)
|
||||
{
|
||||
_logLines.Add(text);
|
||||
|
||||
var tb = new TextBlock
|
||||
{
|
||||
Text = text,
|
||||
Foreground = Brushes.White,
|
||||
Padding = new Thickness(0),
|
||||
Margin = new Thickness(0),
|
||||
TextWrapping = TextWrapping.Wrap,
|
||||
};
|
||||
_logControls.Add(tb);
|
||||
|
||||
TrimLog();
|
||||
|
||||
if (_autoScroll)
|
||||
ScheduleScrollToEnd();
|
||||
}
|
||||
|
||||
public void AppendFormattedLogLine(string text)
|
||||
{
|
||||
_logLines.Add(text);
|
||||
|
||||
var tb = McColorParser.CreateColoredTextBlock(text, TextWrapping.Wrap);
|
||||
_logControls.Add(tb);
|
||||
|
||||
TrimLog();
|
||||
|
||||
if (_autoScroll)
|
||||
ScheduleScrollToEnd();
|
||||
}
|
||||
|
||||
private void TrimLog()
|
||||
{
|
||||
while (_logLines.Count > MaxLogLines)
|
||||
{
|
||||
_logLines.RemoveAt(0);
|
||||
_logControls.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
private void ScheduleScrollToEnd()
|
||||
{
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
_programmaticScroll = true;
|
||||
var sv = _logScrollViewer;
|
||||
sv.Offset = new Vector(0, sv.Extent.Height);
|
||||
_programmaticScroll = false;
|
||||
}, DispatcherPriority.Background);
|
||||
}
|
||||
|
||||
public string LatestLogLine => _logLines.Count > 0 ? _logLines[^1] : "";
|
||||
|
||||
public ObservableCollection<string> GetRecentLogLines(int _) => _logLines;
|
||||
|
||||
private void OnLogAreaPointerPressed(object? sender, PointerPressedEventArgs e)
|
||||
{
|
||||
var props = e.GetCurrentPoint(null).Properties;
|
||||
if (!props.IsLeftButtonPressed)
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => _commandInput.Focus());
|
||||
return;
|
||||
}
|
||||
|
||||
bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;
|
||||
if (shift)
|
||||
return;
|
||||
|
||||
long now = Environment.TickCount64;
|
||||
long elapsed = now - _lastLogClickTicks;
|
||||
_lastLogClickTicks = now;
|
||||
|
||||
if (elapsed < DoubleClickMsec)
|
||||
{
|
||||
ShowNotification(Translations.tui_select_copy_hint, 3000);
|
||||
_lastLogClickTicks = 0;
|
||||
}
|
||||
|
||||
Dispatcher.UIThread.Post(() => _commandInput.Focus());
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Input
|
||||
|
||||
public void ClearInput()
|
||||
{
|
||||
_commandInput.Text = string.Empty;
|
||||
}
|
||||
|
||||
private void OnCommandKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
if (_tabCycling && e.Key is not (Key.Tab or Key.Up or Key.Down or Key.Escape))
|
||||
_tabCycling = false;
|
||||
|
||||
bool ctrl = (e.KeyModifiers & KeyModifiers.Control) != 0;
|
||||
|
||||
if (e.Key == Key.C && ctrl)
|
||||
{
|
||||
HandleCtrlC();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if ((e.Key == Key.Back || e.Key == Key.W) && ctrl)
|
||||
{
|
||||
DeleteWordBackward();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.Left && ctrl)
|
||||
{
|
||||
MoveCaretWordLeft();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.Right && ctrl)
|
||||
{
|
||||
MoveCaretWordRight();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.A && ctrl)
|
||||
{
|
||||
_commandInput.CaretIndex = 0;
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.E && ctrl)
|
||||
{
|
||||
_commandInput.CaretIndex = _commandInput.Text?.Length ?? 0;
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.U && ctrl)
|
||||
{
|
||||
_commandInput.Text = string.Empty;
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.Escape && SuggestionsVisible)
|
||||
{
|
||||
ClearSuggestions();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.Tab && SuggestionsVisible)
|
||||
{
|
||||
if (_tabCycling)
|
||||
{
|
||||
MoveSuggestionSelection(1);
|
||||
ApplySuggestionInPlace(_selectedSuggestionIndex);
|
||||
}
|
||||
else
|
||||
{
|
||||
ApplySuggestionInPlace(_selectedSuggestionIndex);
|
||||
_tabCycling = true;
|
||||
}
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Key == Key.Tab)
|
||||
{
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (e.Key)
|
||||
{
|
||||
case Key.Enter:
|
||||
SubmitCommand();
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.Up:
|
||||
if (SuggestionsVisible)
|
||||
MoveSuggestionSelection(-1);
|
||||
else
|
||||
NavigateHistory(-1);
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.Down:
|
||||
if (SuggestionsVisible)
|
||||
MoveSuggestionSelection(1);
|
||||
else
|
||||
NavigateHistory(1);
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.PageUp:
|
||||
ScrollLog(-10);
|
||||
e.Handled = true;
|
||||
break;
|
||||
|
||||
case Key.PageDown:
|
||||
ScrollLog(10);
|
||||
e.Handled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteWordBackward()
|
||||
{
|
||||
string text = _commandInput.Text ?? "";
|
||||
int caret = _commandInput.CaretIndex;
|
||||
if (caret == 0 || text.Length == 0) return;
|
||||
|
||||
int pos = caret - 1;
|
||||
while (pos > 0 && text[pos - 1] == ' ') pos--;
|
||||
while (pos > 0 && text[pos - 1] != ' ') pos--;
|
||||
|
||||
_commandInput.Text = text[..pos] + text[caret..];
|
||||
_commandInput.CaretIndex = pos;
|
||||
}
|
||||
|
||||
private void MoveCaretWordLeft()
|
||||
{
|
||||
string text = _commandInput.Text ?? "";
|
||||
int pos = _commandInput.CaretIndex;
|
||||
if (pos == 0) return;
|
||||
|
||||
pos--;
|
||||
while (pos > 0 && text[pos - 1] == ' ') pos--;
|
||||
while (pos > 0 && text[pos - 1] != ' ') pos--;
|
||||
|
||||
_commandInput.CaretIndex = pos;
|
||||
}
|
||||
|
||||
private void MoveCaretWordRight()
|
||||
{
|
||||
string text = _commandInput.Text ?? "";
|
||||
int pos = _commandInput.CaretIndex;
|
||||
if (pos >= text.Length) return;
|
||||
|
||||
while (pos < text.Length && text[pos] != ' ') pos++;
|
||||
while (pos < text.Length && text[pos] == ' ') pos++;
|
||||
|
||||
_commandInput.CaretIndex = pos;
|
||||
}
|
||||
|
||||
private void OnCommandTextChanged(object? sender, TextChangedEventArgs e)
|
||||
{
|
||||
string text = _commandInput.Text ?? string.Empty;
|
||||
|
||||
if (text.Contains('\n') || text.Contains('\r'))
|
||||
{
|
||||
string cleaned = text.Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
|
||||
_commandInput.Text = cleaned;
|
||||
_commandInput.CaretIndex = cleaned.Length;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_acceptingSuggestion || _tabCycling)
|
||||
return;
|
||||
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
ClearSuggestions();
|
||||
return;
|
||||
}
|
||||
|
||||
var backend = TuiConsoleBackend.Instance;
|
||||
if (backend == null) return;
|
||||
int cursor = _commandInput.CaretIndex;
|
||||
backend.OnInputChanged(text, cursor);
|
||||
}
|
||||
|
||||
private void SubmitCommand()
|
||||
{
|
||||
string command = _commandInput.Text?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(command))
|
||||
return;
|
||||
|
||||
ClearSuggestions();
|
||||
_tabCycling = false;
|
||||
|
||||
_commandHistory.Add(command);
|
||||
_historyIndex = _commandHistory.Count;
|
||||
|
||||
_acceptingSuggestion = true;
|
||||
try { _commandInput.Text = string.Empty; }
|
||||
finally { _acceptingSuggestion = false; }
|
||||
|
||||
_autoScroll = true;
|
||||
|
||||
AppendLogLine($"> {command}");
|
||||
|
||||
TuiConsoleBackend.Instance?.OnCommandSubmitted(command);
|
||||
}
|
||||
|
||||
private void NavigateHistory(int direction)
|
||||
{
|
||||
if (_commandHistory.Count == 0)
|
||||
return;
|
||||
|
||||
_historyIndex += direction;
|
||||
if (_historyIndex < 0) _historyIndex = 0;
|
||||
if (_historyIndex >= _commandHistory.Count)
|
||||
{
|
||||
_historyIndex = _commandHistory.Count;
|
||||
_commandInput.Text = string.Empty;
|
||||
return;
|
||||
}
|
||||
|
||||
string historyText = _commandHistory[_historyIndex];
|
||||
_commandInput.Text = historyText;
|
||||
_commandInput.CaretIndex = historyText.Length;
|
||||
Dispatcher.UIThread.Post(() => _commandInput.CaretIndex = historyText.Length,
|
||||
DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Suggestions
|
||||
|
||||
private const int PromptWidth = 2; // "> "
|
||||
private const int BorderAndPadding = 2; // 1 border + 1 padding on each side
|
||||
|
||||
internal void UpdateSuggestions(CommandSuggestion[] suggestions, (int Start, int End) range)
|
||||
{
|
||||
if (suggestions.Length == 0)
|
||||
{
|
||||
ClearSuggestions();
|
||||
return;
|
||||
}
|
||||
|
||||
_suggestions = suggestions;
|
||||
_suggestionRange = range;
|
||||
_selectedSuggestionIndex = 0;
|
||||
_suggestionViewTop = 0;
|
||||
|
||||
int leftOffset = PromptWidth + range.Start - BorderAndPadding;
|
||||
double screenWidth = Bounds.Width;
|
||||
if (screenWidth < 1)
|
||||
screenWidth = 80;
|
||||
|
||||
if (leftOffset < 0)
|
||||
leftOffset = 0;
|
||||
|
||||
_suggestionBorder.Margin = new Thickness(leftOffset, 0, 0, 1);
|
||||
_suggestionBorder.MaxWidth = Math.Max(10, screenWidth - leftOffset);
|
||||
|
||||
RebuildSuggestionItems();
|
||||
_suggestionBorder.IsVisible = true;
|
||||
}
|
||||
|
||||
internal void ClearSuggestions()
|
||||
{
|
||||
if (!_suggestionBorder.IsVisible && _suggestions.Length == 0)
|
||||
return;
|
||||
|
||||
_suggestions = Array.Empty<CommandSuggestion>();
|
||||
_selectedSuggestionIndex = -1;
|
||||
_suggestionBorder.IsVisible = false;
|
||||
_suggestionPanel.Children.Clear();
|
||||
}
|
||||
|
||||
private bool SuggestionsVisible => _suggestionBorder.IsVisible && _suggestions.Length > 0;
|
||||
|
||||
private void RebuildSuggestionItems()
|
||||
{
|
||||
_suggestionPanel.Children.Clear();
|
||||
|
||||
int visibleCount = Math.Min(_suggestions.Length, MaxVisibleSuggestions);
|
||||
int viewBottom = _suggestionViewTop + visibleCount;
|
||||
|
||||
for (int i = _suggestionViewTop; i < viewBottom && i < _suggestions.Length; i++)
|
||||
{
|
||||
var sug = _suggestions[i];
|
||||
int index = i;
|
||||
|
||||
string label = sug.Text;
|
||||
if (!string.IsNullOrEmpty(sug.Tooltip))
|
||||
label += " " + sug.Tooltip;
|
||||
|
||||
var tb = new TextBlock
|
||||
{
|
||||
Text = label,
|
||||
Padding = new Thickness(1, 0),
|
||||
Foreground = Brushes.White,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis,
|
||||
Background = i == _selectedSuggestionIndex
|
||||
? new SolidColorBrush(Color.FromRgb(0, 90, 160))
|
||||
: Brushes.Transparent,
|
||||
};
|
||||
|
||||
var row = new Border
|
||||
{
|
||||
Child = tb,
|
||||
Background = Brushes.Transparent,
|
||||
};
|
||||
|
||||
row.PointerPressed += (_, _) =>
|
||||
{
|
||||
_selectedSuggestionIndex = index;
|
||||
ApplySuggestionInPlace(index);
|
||||
_tabCycling = true;
|
||||
};
|
||||
row.PointerEntered += (_, _) =>
|
||||
{
|
||||
if (_selectedSuggestionIndex != index)
|
||||
{
|
||||
_selectedSuggestionIndex = index;
|
||||
UpdateSuggestionHighlight();
|
||||
}
|
||||
};
|
||||
|
||||
_suggestionPanel.Children.Add(row);
|
||||
}
|
||||
|
||||
if (_suggestions.Length > MaxVisibleSuggestions)
|
||||
{
|
||||
string scrollHint = $"[{_suggestionViewTop + 1}-{viewBottom}/{_suggestions.Length}]";
|
||||
var hintTb = new TextBlock
|
||||
{
|
||||
Text = scrollHint,
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(120, 120, 120)),
|
||||
Padding = new Thickness(1, 0),
|
||||
TextAlignment = TextAlignment.Right,
|
||||
HorizontalAlignment = HorizontalAlignment.Stretch,
|
||||
};
|
||||
_suggestionPanel.Children.Add(hintTb);
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateSuggestionHighlight()
|
||||
{
|
||||
int visibleCount = Math.Min(_suggestions.Length, MaxVisibleSuggestions);
|
||||
for (int i = 0; i < visibleCount && i < _suggestionPanel.Children.Count; i++)
|
||||
{
|
||||
if (_suggestionPanel.Children[i] is Border border && border.Child is TextBlock tb)
|
||||
{
|
||||
int dataIndex = _suggestionViewTop + i;
|
||||
tb.Background = dataIndex == _selectedSuggestionIndex
|
||||
? new SolidColorBrush(Color.FromRgb(0, 90, 160))
|
||||
: Brushes.Transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void MoveSuggestionSelection(int direction)
|
||||
{
|
||||
if (_suggestions.Length == 0) return;
|
||||
|
||||
_selectedSuggestionIndex += direction;
|
||||
if (_selectedSuggestionIndex < 0)
|
||||
_selectedSuggestionIndex = _suggestions.Length - 1;
|
||||
else if (_selectedSuggestionIndex >= _suggestions.Length)
|
||||
_selectedSuggestionIndex = 0;
|
||||
|
||||
int visibleCount = Math.Min(_suggestions.Length, MaxVisibleSuggestions);
|
||||
if (_selectedSuggestionIndex < _suggestionViewTop)
|
||||
{
|
||||
_suggestionViewTop = _selectedSuggestionIndex;
|
||||
RebuildSuggestionItems();
|
||||
}
|
||||
else if (_selectedSuggestionIndex >= _suggestionViewTop + visibleCount)
|
||||
{
|
||||
_suggestionViewTop = _selectedSuggestionIndex - visibleCount + 1;
|
||||
RebuildSuggestionItems();
|
||||
}
|
||||
else
|
||||
{
|
||||
UpdateSuggestionHighlight();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSuggestionWheelChanged(object? sender, PointerWheelEventArgs e)
|
||||
{
|
||||
if (!SuggestionsVisible) return;
|
||||
|
||||
int direction = e.Delta.Y > 0 ? -1 : 1;
|
||||
ScrollSuggestionViewport(direction);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private void ScrollSuggestionViewport(int direction)
|
||||
{
|
||||
if (_suggestions.Length <= MaxVisibleSuggestions) return;
|
||||
|
||||
int newTop = _suggestionViewTop + direction;
|
||||
int maxTop = _suggestions.Length - MaxVisibleSuggestions;
|
||||
newTop = Math.Clamp(newTop, 0, maxTop);
|
||||
|
||||
if (newTop == _suggestionViewTop) return;
|
||||
_suggestionViewTop = newTop;
|
||||
|
||||
int viewBottom = _suggestionViewTop + MaxVisibleSuggestions;
|
||||
if (_selectedSuggestionIndex < _suggestionViewTop)
|
||||
_selectedSuggestionIndex = _suggestionViewTop;
|
||||
else if (_selectedSuggestionIndex >= viewBottom)
|
||||
_selectedSuggestionIndex = viewBottom - 1;
|
||||
|
||||
RebuildSuggestionItems();
|
||||
}
|
||||
|
||||
private void ApplySuggestionText(int index)
|
||||
{
|
||||
if (index < 0 || index >= _suggestions.Length) return;
|
||||
|
||||
string text = _commandInput.Text ?? "";
|
||||
string selected = _suggestions[index].Text;
|
||||
|
||||
int start = Math.Min(_suggestionRange.Start, text.Length);
|
||||
int end = Math.Min(_suggestionRange.End, text.Length);
|
||||
|
||||
string before = text[..start];
|
||||
string after = text[end..];
|
||||
string newText = before + selected + after;
|
||||
|
||||
_commandInput.Text = newText;
|
||||
_commandInput.CaretIndex = before.Length + selected.Length;
|
||||
|
||||
_suggestionRange = (start, start + selected.Length);
|
||||
}
|
||||
|
||||
private void ApplySuggestionInPlace(int index)
|
||||
{
|
||||
if (index < 0 || index >= _suggestions.Length) return;
|
||||
|
||||
_acceptingSuggestion = true;
|
||||
try
|
||||
{
|
||||
ApplySuggestionText(index);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_acceptingSuggestion = false;
|
||||
}
|
||||
UpdateSuggestionHighlight();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Ctrl+C
|
||||
|
||||
internal void HandleCtrlC()
|
||||
{
|
||||
long now = Environment.TickCount64;
|
||||
long elapsed = now - _lastCtrlCTicks;
|
||||
|
||||
if (_lastCtrlCTicks > 0 && elapsed < CtrlCDoublePressMsec)
|
||||
{
|
||||
HideNotification();
|
||||
TuiConsoleBackend.Instance?.Shutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
_lastCtrlCTicks = now;
|
||||
|
||||
string inputText = _commandInput.Text?.Trim() ?? "";
|
||||
if (inputText.Length > 0)
|
||||
{
|
||||
_commandInput.Text = string.Empty;
|
||||
ShowNotification(Translations.tui_ctrlc_input_cleared, CtrlCDoublePressMsec);
|
||||
}
|
||||
else
|
||||
{
|
||||
ShowNotification(Translations.tui_ctrlc_quit_hint, CtrlCDoublePressMsec);
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowNotification(string message, int autoHideMs)
|
||||
{
|
||||
_notificationText.Text = message;
|
||||
_notificationBorder.IsVisible = true;
|
||||
|
||||
var timer = new Avalonia.Threading.DispatcherTimer
|
||||
{
|
||||
Interval = TimeSpan.FromMilliseconds(autoHideMs),
|
||||
};
|
||||
timer.Tick += (_, _) =>
|
||||
{
|
||||
timer.Stop();
|
||||
HideNotification();
|
||||
};
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
private void HideNotification()
|
||||
{
|
||||
_notificationBorder.IsVisible = false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Scrolling
|
||||
|
||||
private void ScrollLog(int delta)
|
||||
{
|
||||
var sv = _logScrollViewer;
|
||||
var newY = sv.Offset.Y + delta;
|
||||
newY = Math.Max(0, Math.Min(newY, sv.Extent.Height - sv.Viewport.Height));
|
||||
sv.Offset = new Vector(0, newY);
|
||||
|
||||
_autoScroll = newY >= sv.Extent.Height - sv.Viewport.Height - 2;
|
||||
}
|
||||
|
||||
private void OnLogScrollChanged(object? sender, ScrollChangedEventArgs e)
|
||||
{
|
||||
if (_programmaticScroll) return;
|
||||
|
||||
var sv = _logScrollViewer;
|
||||
_autoScroll = sv.Offset.Y >= sv.Extent.Height - sv.Viewport.Height - 2;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Status Bar (Health / Food)
|
||||
|
||||
private void StartStatusBarTimer()
|
||||
{
|
||||
var timer = new DispatcherTimer
|
||||
{
|
||||
Interval = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
timer.Tick += (_, _) => UpdateStatusBar();
|
||||
timer.Start();
|
||||
}
|
||||
|
||||
private void UpdateStatusBar()
|
||||
{
|
||||
if (McClient.Instance is not McClient client)
|
||||
{
|
||||
_statusBar.IsVisible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
int gamemode = client.GetGamemode();
|
||||
if (gamemode != 0 && gamemode != 2)
|
||||
{
|
||||
_statusBar.IsVisible = false;
|
||||
return;
|
||||
}
|
||||
|
||||
float health = client.GetHealth();
|
||||
int food = client.GetSaturation();
|
||||
|
||||
int heartsFilled = (int)Math.Ceiling(health / 20f * 10);
|
||||
heartsFilled = Math.Clamp(heartsFilled, 0, 10);
|
||||
int foodFilled = (int)Math.Ceiling(food / 20f * 10);
|
||||
foodFilled = Math.Clamp(foodFilled, 0, 10);
|
||||
|
||||
_statusBar.Inlines?.Clear();
|
||||
_statusBar.Inlines ??= new Avalonia.Controls.Documents.InlineCollection();
|
||||
|
||||
var healthText = BuildBarText(heartsFilled, 10, "\u2764\ufe0f", " \u2661 ");
|
||||
var foodText = BuildBarText(foodFilled, 10, "\ud83c\udf56", " \u25cb ");
|
||||
|
||||
_statusBar.Inlines.Add(new Avalonia.Controls.Documents.Run(healthText)
|
||||
{
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(255, 85, 85)),
|
||||
});
|
||||
_statusBar.Inlines.Add(new Avalonia.Controls.Documents.Run($" {health:F1} ")
|
||||
{
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(255, 150, 150)),
|
||||
});
|
||||
_statusBar.Inlines.Add(new Avalonia.Controls.Documents.Run(foodText)
|
||||
{
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(200, 160, 80)),
|
||||
});
|
||||
_statusBar.Inlines.Add(new Avalonia.Controls.Documents.Run($" {food}")
|
||||
{
|
||||
Foreground = new SolidColorBrush(Color.FromRgb(220, 190, 100)),
|
||||
});
|
||||
|
||||
_statusBar.IsVisible = true;
|
||||
}
|
||||
|
||||
private static string BuildBarText(int filled, int total, string filledChar, string emptyChar)
|
||||
{
|
||||
var sb = new System.Text.StringBuilder();
|
||||
for (int i = 0; i < filled; i++)
|
||||
{
|
||||
if (i > 0) sb.Append(' ');
|
||||
sb.Append(filledChar);
|
||||
}
|
||||
for (int i = filled; i < total; i++)
|
||||
{
|
||||
sb.Append(emptyChar);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Overlay
|
||||
|
||||
public void ShowOverlay(Control content, Action? onClose = null)
|
||||
{
|
||||
if (_overlayContent != null)
|
||||
HideOverlay();
|
||||
|
||||
_overlayContent = content;
|
||||
_overlayCloseCallback = onClose;
|
||||
_mainContent.IsVisible = false;
|
||||
|
||||
_rootPanel.Children.Add(_overlayContent);
|
||||
}
|
||||
|
||||
public void HideOverlay()
|
||||
{
|
||||
if (_overlayContent == null) return;
|
||||
|
||||
_rootPanel.Children.Remove(_overlayContent);
|
||||
|
||||
_overlayContent = null;
|
||||
_mainContent.IsVisible = true;
|
||||
|
||||
var cb = _overlayCloseCallback;
|
||||
_overlayCloseCallback = null;
|
||||
cb?.Invoke();
|
||||
|
||||
_commandInput.Focus();
|
||||
}
|
||||
|
||||
public bool HasOverlay => _overlayContent != null;
|
||||
|
||||
protected override void OnKeyDown(KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Escape && _overlayContent != null)
|
||||
{
|
||||
HideOverlay();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
base.OnKeyDown(e);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
|
||||
{
|
||||
base.OnAttachedToVisualTree(e);
|
||||
Dispatcher.UIThread.Post(() =>
|
||||
{
|
||||
_commandInput.Focus();
|
||||
}, DispatcherPriority.Loaded);
|
||||
}
|
||||
}
|
||||
}
|
||||
114
MinecraftClient/Tui/McColorParser.cs
Normal file
114
MinecraftClient/Tui/McColorParser.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.Documents;
|
||||
using Avalonia.Media;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses Minecraft § color codes and produces Avalonia Inlines for rich text display.
|
||||
/// </summary>
|
||||
public static class McColorParser
|
||||
{
|
||||
private static readonly Dictionary<char, IBrush> ColorMap = new()
|
||||
{
|
||||
{ '0', new SolidColorBrush(Color.FromRgb(0, 0, 0)) },
|
||||
{ '1', new SolidColorBrush(Color.FromRgb(0, 0, 170)) },
|
||||
{ '2', new SolidColorBrush(Color.FromRgb(0, 170, 0)) },
|
||||
{ '3', new SolidColorBrush(Color.FromRgb(0, 170, 170)) },
|
||||
{ '4', new SolidColorBrush(Color.FromRgb(170, 0, 0)) },
|
||||
{ '5', new SolidColorBrush(Color.FromRgb(170, 0, 170)) },
|
||||
{ '6', new SolidColorBrush(Color.FromRgb(255, 170, 0)) },
|
||||
{ '7', new SolidColorBrush(Color.FromRgb(170, 170, 170)) },
|
||||
{ '8', new SolidColorBrush(Color.FromRgb(85, 85, 85)) },
|
||||
{ '9', new SolidColorBrush(Color.FromRgb(85, 85, 255)) },
|
||||
{ 'a', new SolidColorBrush(Color.FromRgb(85, 255, 85)) },
|
||||
{ 'b', new SolidColorBrush(Color.FromRgb(85, 255, 255)) },
|
||||
{ 'c', new SolidColorBrush(Color.FromRgb(255, 85, 85)) },
|
||||
{ 'd', new SolidColorBrush(Color.FromRgb(255, 85, 255)) },
|
||||
{ 'e', new SolidColorBrush(Color.FromRgb(255, 255, 85)) },
|
||||
{ 'f', Brushes.White },
|
||||
};
|
||||
|
||||
public static TextBlock CreateColoredTextBlock(string text, TextWrapping wrapping = TextWrapping.Wrap)
|
||||
{
|
||||
var tb = new TextBlock
|
||||
{
|
||||
TextWrapping = wrapping,
|
||||
Padding = new Avalonia.Thickness(0),
|
||||
Margin = new Avalonia.Thickness(0),
|
||||
};
|
||||
|
||||
if (string.IsNullOrEmpty(text) || !text.Contains('§'))
|
||||
{
|
||||
tb.Text = text ?? "";
|
||||
tb.Foreground = Brushes.White;
|
||||
return tb;
|
||||
}
|
||||
|
||||
IBrush currentColor = Brushes.White;
|
||||
bool bold = false;
|
||||
bool italic = false;
|
||||
int start = 0;
|
||||
|
||||
for (int i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (text[i] == '§' && i + 1 < text.Length)
|
||||
{
|
||||
if (i > start)
|
||||
AddRun(tb, text[start..i], currentColor, bold, italic);
|
||||
|
||||
char code = char.ToLower(text[i + 1]);
|
||||
|
||||
if (ColorMap.TryGetValue(code, out var brush))
|
||||
{
|
||||
currentColor = brush;
|
||||
bold = false;
|
||||
italic = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
switch (code)
|
||||
{
|
||||
case 'l': bold = true; break;
|
||||
case 'o': italic = true; break;
|
||||
case 'r':
|
||||
currentColor = Brushes.White;
|
||||
bold = false;
|
||||
italic = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
i++;
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (start < text.Length)
|
||||
AddRun(tb, text[start..], currentColor, bold, italic);
|
||||
|
||||
if (tb.Inlines?.Count == 0)
|
||||
{
|
||||
tb.Text = "";
|
||||
tb.Foreground = Brushes.White;
|
||||
}
|
||||
|
||||
return tb;
|
||||
}
|
||||
|
||||
private static void AddRun(TextBlock tb, string text, IBrush color, bool bold, bool italic)
|
||||
{
|
||||
if (text.Length == 0) return;
|
||||
|
||||
tb.Inlines ??= new InlineCollection();
|
||||
tb.Inlines.Add(new Run(text)
|
||||
{
|
||||
Foreground = color,
|
||||
FontWeight = bold ? FontWeight.Bold : FontWeight.Normal,
|
||||
FontStyle = italic ? FontStyle.Italic : FontStyle.Normal,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
35
MinecraftClient/Tui/MccTuiApp.cs
Normal file
35
MinecraftClient/Tui/MccTuiApp.cs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Media;
|
||||
using Consolonia.Themes;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class MccTuiApp : Application
|
||||
{
|
||||
public override void Initialize()
|
||||
{
|
||||
Styles.Add(new ModernTheme());
|
||||
}
|
||||
|
||||
public override void OnFrameworkInitializationCompleted()
|
||||
{
|
||||
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
|
||||
{
|
||||
var view = new MainTuiView();
|
||||
TuiConsoleBackend.Instance?.SetView(view);
|
||||
|
||||
desktop.MainWindow = new Window
|
||||
{
|
||||
Content = view,
|
||||
Title = "Minecraft Console Client",
|
||||
Background = Brushes.Black,
|
||||
Padding = new Thickness(0),
|
||||
};
|
||||
}
|
||||
|
||||
base.OnFrameworkInitializationCompleted();
|
||||
}
|
||||
}
|
||||
}
|
||||
157
MinecraftClient/Tui/SlotViewModel.cs
Normal file
157
MinecraftClient/Tui/SlotViewModel.cs
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using MinecraftClient.Inventory;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
public class SlotViewModel : INotifyPropertyChanged
|
||||
{
|
||||
private bool _isSelected;
|
||||
private bool _isHovered;
|
||||
|
||||
public int SlotId { get; }
|
||||
public string ItemDisplayText { get; private set; }
|
||||
public string CountDisplay { get; private set; }
|
||||
public string FullInfo { get; private set; }
|
||||
public string ItemTypeName { get; private set; }
|
||||
public bool IsEmpty { get; private set; }
|
||||
public bool IsHotbar { get; }
|
||||
public int HotbarIndex { get; }
|
||||
public ItemType ItemType { get; private set; }
|
||||
public int ItemCount { get; private set; }
|
||||
public Item? RawItem { get; private set; }
|
||||
public int NameMaxWidth { get; set; } = 9;
|
||||
public int NameMaxLines { get; set; } = 1;
|
||||
|
||||
public bool IsSelected
|
||||
{
|
||||
get => _isSelected;
|
||||
set { _isSelected = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public bool IsHovered
|
||||
{
|
||||
get => _isHovered;
|
||||
set { _isHovered = value; OnPropertyChanged(); }
|
||||
}
|
||||
|
||||
public SlotViewModel(int slotId, bool isHotbar = false, int hotbarIndex = -1)
|
||||
{
|
||||
SlotId = slotId;
|
||||
IsHotbar = isHotbar;
|
||||
HotbarIndex = hotbarIndex;
|
||||
ItemDisplayText = "";
|
||||
CountDisplay = "";
|
||||
FullInfo = "";
|
||||
ItemTypeName = "";
|
||||
IsEmpty = true;
|
||||
ItemType = ItemType.Air;
|
||||
ItemCount = 0;
|
||||
}
|
||||
|
||||
public void Update(Item? item)
|
||||
{
|
||||
RawItem = item;
|
||||
if (item == null || item.IsEmpty)
|
||||
{
|
||||
ItemDisplayText = "";
|
||||
CountDisplay = "";
|
||||
FullInfo = "";
|
||||
ItemTypeName = "";
|
||||
IsEmpty = true;
|
||||
ItemType = ItemType.Air;
|
||||
ItemCount = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
ItemType = item.Type;
|
||||
ItemCount = item.Count;
|
||||
string typeName = item.GetTypeString();
|
||||
ItemTypeName = typeName;
|
||||
ItemDisplayText = FormatMultiLine(typeName, NameMaxWidth, NameMaxLines);
|
||||
CountDisplay = item.Count > 1 ? $"x{item.Count}" : "";
|
||||
FullInfo = item.ToFullString();
|
||||
IsEmpty = false;
|
||||
}
|
||||
|
||||
OnPropertyChanged(nameof(ItemDisplayText));
|
||||
OnPropertyChanged(nameof(CountDisplay));
|
||||
OnPropertyChanged(nameof(FullInfo));
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(ItemType));
|
||||
OnPropertyChanged(nameof(ItemTypeName));
|
||||
OnPropertyChanged(nameof(ItemCount));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Format item name into multi-line display text that fits within
|
||||
/// maxWidth columns and maxLines lines. Breaks at word boundaries.
|
||||
/// </summary>
|
||||
private static string FormatMultiLine(string name, int maxWidth, int maxLines)
|
||||
{
|
||||
if (string.IsNullOrEmpty(name))
|
||||
return "";
|
||||
|
||||
int colonIdx = name.LastIndexOf(':');
|
||||
if (colonIdx >= 0 && colonIdx < name.Length - 1)
|
||||
name = name[(colonIdx + 1)..];
|
||||
|
||||
name = name.Replace("_", " ").Trim();
|
||||
name = InsertCamelCaseSpaces(name);
|
||||
|
||||
if (maxLines <= 1 || name.Length <= maxWidth)
|
||||
return name.Length <= maxWidth ? name : name[..maxWidth];
|
||||
|
||||
var lines = new System.Collections.Generic.List<string>();
|
||||
string remaining = name;
|
||||
|
||||
for (int line = 0; line < maxLines && remaining.Length > 0; line++)
|
||||
{
|
||||
if (remaining.Length <= maxWidth)
|
||||
{
|
||||
lines.Add(remaining);
|
||||
break;
|
||||
}
|
||||
|
||||
int breakAt = -1;
|
||||
for (int i = maxWidth; i >= 1; i--)
|
||||
{
|
||||
if (remaining[i] == ' ')
|
||||
{
|
||||
breakAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (breakAt < 0)
|
||||
breakAt = maxWidth;
|
||||
|
||||
lines.Add(remaining[..breakAt].TrimEnd());
|
||||
remaining = remaining[breakAt..].TrimStart();
|
||||
}
|
||||
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
|
||||
private static string InsertCamelCaseSpaces(string s)
|
||||
{
|
||||
if (s.Length < 2) return s;
|
||||
var sb = new System.Text.StringBuilder(s.Length + 4);
|
||||
sb.Append(s[0]);
|
||||
for (int i = 1; i < s.Length; i++)
|
||||
{
|
||||
if (char.IsUpper(s[i]) && char.IsLower(s[i - 1]))
|
||||
sb.Append(' ');
|
||||
sb.Append(s[i]);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
private void OnPropertyChanged([CallerMemberName] string? name = null)
|
||||
{
|
||||
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
306
MinecraftClient/Tui/TuiConsoleBackend.cs
Normal file
306
MinecraftClient/Tui/TuiConsoleBackend.cs
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using Avalonia;
|
||||
using Avalonia.Threading;
|
||||
using Consolonia;
|
||||
|
||||
namespace MinecraftClient.Tui
|
||||
{
|
||||
/// <summary>
|
||||
/// Console backend that uses Avalonia/Consolonia for a full-screen TUI.
|
||||
/// Avalonia Dispatcher runs on the main thread; MCC logic runs on background threads.
|
||||
/// </summary>
|
||||
public class TuiConsoleBackend : IConsoleBackend
|
||||
{
|
||||
public event EventHandler<string>? MessageReceived;
|
||||
public event EventHandler<ConsoleInputBuffer>? OnInputChange;
|
||||
|
||||
private MainTuiView? _view;
|
||||
private volatile bool _readThreadActive;
|
||||
|
||||
public bool DisplayUserInput { get; set; } = true;
|
||||
|
||||
internal static TuiConsoleBackend? Instance { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the Avalonia app and starts the main UI loop.
|
||||
/// This blocks the calling thread until the TUI exits.
|
||||
/// Before blocking, it starts MCC's remaining initialization on a background thread.
|
||||
/// </summary>
|
||||
public void RunTuiMainLoop(string[] args)
|
||||
{
|
||||
Instance = this;
|
||||
|
||||
AppDomain.CurrentDomain.ProcessExit += (_, _) => RestoreTerminalState();
|
||||
|
||||
System.Console.CancelKeyPress += (_, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
var view = _view;
|
||||
if (view != null)
|
||||
Dispatcher.UIThread.Post(() => view.HandleCtrlC());
|
||||
};
|
||||
|
||||
new Thread(() =>
|
||||
{
|
||||
Thread.Sleep(500);
|
||||
ContinueMccStartup(args);
|
||||
})
|
||||
{ Name = "MCC-Main", IsBackground = true }.Start();
|
||||
|
||||
AppBuilder builder = AppBuilder.Configure<MccTuiApp>()
|
||||
.UseConsolonia()
|
||||
.UseAutoDetectedConsole()
|
||||
.LogToException();
|
||||
|
||||
try
|
||||
{
|
||||
builder.StartWithConsoleLifetime(Array.Empty<string>());
|
||||
}
|
||||
finally
|
||||
{
|
||||
RestoreTerminalState();
|
||||
}
|
||||
}
|
||||
|
||||
private static volatile bool _terminalRestored;
|
||||
|
||||
private static void RestoreTerminalState()
|
||||
{
|
||||
if (_terminalRestored) return;
|
||||
_terminalRestored = true;
|
||||
|
||||
try
|
||||
{
|
||||
System.Console.Write("\x1b[?1000l"); // disable X11 mouse
|
||||
System.Console.Write("\x1b[?1001l"); // disable highlight mouse
|
||||
System.Console.Write("\x1b[?1002l"); // disable button-event mouse
|
||||
System.Console.Write("\x1b[?1003l"); // disable any-event mouse
|
||||
System.Console.Write("\x1b[?1004l"); // disable focus events
|
||||
System.Console.Write("\x1b[?1005l"); // disable UTF-8 mouse encoding
|
||||
System.Console.Write("\x1b[?1006l"); // disable SGR mouse encoding
|
||||
System.Console.Write("\x1b[?1015l"); // disable urxvt mouse encoding
|
||||
System.Console.Write("\x1b[?1049l"); // leave alternate screen
|
||||
System.Console.Write("\x1b[?25h"); // show cursor
|
||||
System.Console.Write("\x1b[?7h"); // re-enable line wrap
|
||||
System.Console.Write("\x1b[0m"); // reset attributes
|
||||
System.Console.Write("\x1b[2J"); // clear entire screen
|
||||
System.Console.Write("\x1b[H"); // cursor to home
|
||||
System.Console.Out.Flush();
|
||||
}
|
||||
catch { }
|
||||
|
||||
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var proc = Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "stty",
|
||||
Arguments = "sane",
|
||||
UseShellExecute = false,
|
||||
});
|
||||
proc?.WaitForExit(500);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
private static void ContinueMccStartup(string[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
Program.ContinueAfterTuiInit(args);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ConsoleIO.WriteLineFormatted($"§c[MCC] Fatal: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
internal void SetView(MainTuiView view)
|
||||
{
|
||||
_view = view;
|
||||
}
|
||||
|
||||
internal MainTuiView? GetView() => _view;
|
||||
|
||||
public void Init()
|
||||
{
|
||||
}
|
||||
|
||||
public void WriteLine(string text)
|
||||
{
|
||||
var view = _view;
|
||||
if (view == null)
|
||||
{
|
||||
System.Console.WriteLine(text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
view.AppendLogLine(text);
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => view.AppendLogLine(text));
|
||||
}
|
||||
|
||||
public void WriteLineFormatted(string text)
|
||||
{
|
||||
var view = _view;
|
||||
if (view == null)
|
||||
{
|
||||
System.Console.WriteLine(Scripting.ChatBot.GetVerbatim(text));
|
||||
return;
|
||||
}
|
||||
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
view.AppendFormattedLogLine(text);
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => view.AppendFormattedLogLine(text));
|
||||
}
|
||||
|
||||
public void BeginReadThread()
|
||||
{
|
||||
_readThreadActive = true;
|
||||
}
|
||||
|
||||
public void StopReadThread()
|
||||
{
|
||||
_readThreadActive = false;
|
||||
DismissOverlay();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Close any open overlay (e.g. inventory) so the user can interact
|
||||
/// with the main console again. Safe to call from any thread.
|
||||
/// </summary>
|
||||
internal void DismissOverlay()
|
||||
{
|
||||
var view = _view;
|
||||
if (view == null) return;
|
||||
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
{
|
||||
view.HideOverlay();
|
||||
}
|
||||
else
|
||||
{
|
||||
Dispatcher.UIThread.Post(() => view.HideOverlay());
|
||||
}
|
||||
}
|
||||
|
||||
public string RequestImmediateInput()
|
||||
{
|
||||
if (_shutdownRequested)
|
||||
{
|
||||
Thread.Sleep(Timeout.Infinite);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var mre = new ManualResetEventSlim(false);
|
||||
string? result = null;
|
||||
|
||||
void Handler(object? sender, string e)
|
||||
{
|
||||
result = e;
|
||||
mre.Set();
|
||||
}
|
||||
|
||||
MessageReceived += Handler;
|
||||
mre.Wait();
|
||||
MessageReceived -= Handler;
|
||||
|
||||
return result ?? string.Empty;
|
||||
}
|
||||
|
||||
public string? ReadPassword()
|
||||
{
|
||||
return RequestImmediateInput();
|
||||
}
|
||||
|
||||
public void ClearInputBuffer()
|
||||
{
|
||||
if (_view == null) return;
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
_view.ClearInput();
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => _view?.ClearInput());
|
||||
}
|
||||
|
||||
public void SetInputVisible(bool visible)
|
||||
{
|
||||
}
|
||||
|
||||
public void SetBackreadBufferLimit(int limit)
|
||||
{
|
||||
}
|
||||
|
||||
public void Shutdown()
|
||||
{
|
||||
_shutdownRequested = true;
|
||||
RestoreTerminalState();
|
||||
|
||||
var lifetime = Application.Current?.ApplicationLifetime
|
||||
as Avalonia.Controls.ApplicationLifetimes.IControlledApplicationLifetime;
|
||||
|
||||
if (lifetime != null)
|
||||
{
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
lifetime.Shutdown();
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => lifetime.Shutdown());
|
||||
}
|
||||
|
||||
new Thread(() =>
|
||||
{
|
||||
Thread.Sleep(500);
|
||||
Environment.Exit(0);
|
||||
}) { Name = "TUI-Exit-Guard", IsBackground = true }.Start();
|
||||
}
|
||||
|
||||
private volatile bool _shutdownRequested;
|
||||
|
||||
/// <summary>
|
||||
/// Called from the TUI view when user presses Enter in the command input.
|
||||
/// Always fires MessageReceived so that both the normal read-thread path
|
||||
/// and RequestImmediateInput (used by offline prompt) receive the input.
|
||||
/// </summary>
|
||||
internal void OnCommandSubmitted(string command)
|
||||
{
|
||||
MessageReceived?.Invoke(this, command);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called from the TUI view when user types in the command input.
|
||||
/// </summary>
|
||||
internal void OnInputChanged(string text, int cursorPos)
|
||||
{
|
||||
OnInputChange?.Invoke(this, new ConsoleInputBuffer(text, cursorPos));
|
||||
}
|
||||
|
||||
internal void UpdateSuggestions(CommandSuggestion[] suggestions, (int Start, int End) range)
|
||||
{
|
||||
var view = _view;
|
||||
if (view == null) return;
|
||||
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
view.UpdateSuggestions(suggestions, range);
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => view.UpdateSuggestions(suggestions, range));
|
||||
}
|
||||
|
||||
internal void ClearSuggestions()
|
||||
{
|
||||
var view = _view;
|
||||
if (view == null) return;
|
||||
|
||||
if (Dispatcher.UIThread.CheckAccess())
|
||||
view.ClearSuggestions();
|
||||
else
|
||||
Dispatcher.UIThread.Post(() => view.ClearSuggestions());
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue