using Bogus.DataSets; using Microsoft.CodeAnalysis.Text; using System; using…
- User
using Bogus.DataSets; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Tumble; using Tumble.AIStuff; using static System.Net.Mime.MediaTypeNames;
namespace Tumble { class Worklines { // Enum to represent the state of a line enum LineState { Ungenerated, // '~' Collapsed, // '+' Expanded // '-' }
static List<WorkLine> workLines = new List<WorkLine>(); static int selectedIndex = 0; static object lockObj = new object(); // Keeps track of the Y position for each line static List<int> linePositions = new List<int>(); public static async Task Start() { var tempVisible = Console.CursorVisible; var width = Console.WindowWidth; var height = Console.WindowHeight; Task.Run(async () => { while (true) { if (width != Console.WindowWidth || height != Console.WindowHeight) { width = Console.WindowWidth; height = Console.WindowHeight; Render(); } await Task.Delay(100); } }); Console.CursorVisible = false; InitializeWorkLines(); bool exit = false; while (!exit) { Render(); var key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: if (selectedIndex > 0) selectedIndex--; break; case ConsoleKey.DownArrow: if (selectedIndex < workLines.Count - 1) selectedIndex++; break; case ConsoleKey.Spacebar: await HandleSpace(); break; case ConsoleKey.Delete: workLines.RemoveAt(selectedIndex); break; case ConsoleKey.Escape: exit = true; break; } } Console.CursorVisible = tempVisible; } static void InitializeWorkLines() { // Initialize with example program workLines.Add(new WorkLine("plot the sine function, save the image to desktop as sine.png")); workLines.Add(new WorkLine("create a 4x4 grid image of sine.png duplicated 4 times, one in each corner and save it as collage.png")); workLines.Add(new WorkLine("open collage.png in the default program")); } static void Render() { UI.Wipe(); linePositions.Clear(); // Reset line positions int currentY = 0; int consoleWidth = Console.WindowWidth; int consoleHeight = Console.WindowHeight; for (int i = 0; i < workLines.Count; i++) { var line = workLines[i]; linePositions.Add(currentY); if (i == selectedIndex) { // Highlight selected line Console.BackgroundColor = ConsoleColor.Blue; } else { Console.BackgroundColor = ConsoleColor.Black; } Message.Send(MessageType.Raw, $"{line.GetPrefix()}{line.Instruction}"); Console.ResetColor(); currentY++; var code = line.GetActualCode(); // If expanded, show the box if (line.State == LineState.Expanded && !string.IsNullOrEmpty(code)) { // Calculate box position and size int boxStartX = 0; int boxStartY = currentY; //Width = text.Split('\n').Max(x => x.StripAnsiColorCodes().Length) + 2; //Height = text.Split('\n').Length + 2; int maxBoxWidth = code.Split('\n').Max(x => x.StripAnsiColorCodes().Length) + 2; int maxBoxHeight = code.Trim().Split('\n').Length + 2; // Display the box ConsoleBox.Show(line.GetActualCode(), boxStartX, boxStartY, maxBoxWidth, maxBoxHeight); Console.WriteLine(); // Calculate how many lines the box takes int wrappedLineCount = maxBoxHeight; currentY += wrappedLineCount; } } // Instructions at the bottom if (currentY < consoleHeight - 1) { Console.SetCursorPosition(0, currentY); Message.Send("\nUse Up/Down arrows to navigate, Space to interact, Esc to exit."); } } // Helper method to count wrapped lines static int CountWrappedLines(string text, int maxLineLength) { var wrappedText = ConsoleBox.ShowTextForWrapping(text, maxLineLength); return wrappedText.Split('\n').Length; } static async Task HandleSpace() { var line = workLines[selectedIndex]; switch (line.State) { case LineState.Ungenerated: await GenerateLine(line); break; case LineState.Collapsed: ExpandLine(line); break; case LineState.Expanded: CollapseLine(line); break; } } static async Task GenerateLine(WorkLine line) { // Prepare prompt string fullProgram = string.Join("\n", workLines.Select(l => l.Instruction)); string prompt = $"Write a python program that represents a line in the program. Here is the full program in natural language:\n{fullProgram}\n. You will ONLY write the code for the line \n\n{line.Instruction}\n\nOnly respond with Python code in a python code block."; string conversationId = Guid.NewGuid().ToString(); StringBuilder generated = new StringBuilder(); // Start streaming await foreach (var token in AI.GetStream(prompt, conversationId, true)) { generated.Append(token); lock (lockObj) { line.State = LineState.Expanded; line.GeneratedCode = generated.ToString(); Render(); } } } static void ExpandLine(WorkLine line) { if (!string.IsNullOrEmpty(line.GeneratedCode)) { line.State = LineState.Expanded; } } static void CollapseLine(WorkLine line) { if (!string.IsNullOrEmpty(line.GeneratedCode)) { line.State = LineState.Collapsed; } } // Class representing a single line in Worklines class WorkLine { public string Instruction { get; set; } public LineState State { get; set; } public string GeneratedCode { get; set; } public string GetActualCode() => GeneratedCode.ExtractCode(); // Position of the ConsoleBox if expanded public ConsoleBox Box { get; set; } public WorkLine(string instruction) { Instruction = instruction; State = LineState.Ungenerated; GeneratedCode = string.Empty; Box = null; } public string GetPrefix() { switch (State) { case LineState.Ungenerated: return "~ "; case LineState.Collapsed: return "+ "; case LineState.Expanded: return "- "; default: return "~ "; } } } }}
Add these changes:
pressing R regenerates the code in the currently selected box pressing N will make a new line and set the cursor to visible at that position to edit it (background color green in edit mode, Console.ReadLine it). Enter to confirm edit, escape to cancel edit the generating text should be visible as it's being generated in the box.
write the full code with these changes
- Assistant
Certainly! Below is the complete updated C# code incorporating the requested features:
- Pressing
RRegenerates the Code in the Currently Selected Box:- Adds a handler for the
Rkey to regenerate the code for the selectedWorkLine.
- Adds a handler for the
- Pressing
NCreates a New Line for Editing:- Adds a handler for the
Nkey to insert a newWorkLineand allows the user to edit it. The line enters an edit mode with a green background, and the cursor becomes visible for input. PressingEnterconfirms the edit, while pressingEscapecancels it.
- Adds a handler for the
- Visible Generation of Text:
- Updates the rendering logic to display the code being generated in real-time within the box.
Updated Code:
using Bogus.DataSets; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Tumble; using Tumble.AIStuff; using static System.Net.Mime.MediaTypeNames; namespace Tumble { class Worklines { // Enum to represent the state of a line enum LineState { Ungenerated, // '~' Collapsed, // '+' Expanded // '-' } static List<WorkLine> workLines = new List<WorkLine>(); static int selectedIndex = 0; static object lockObj = new object(); // Keeps track of the Y position for each line static List<int> linePositions = new List<int>(); public static async Task Start() { var tempVisible = Console.CursorVisible; var width = Console.WindowWidth; var height = Console.WindowHeight; Task.Run(async () => { while (true) { if (width != Console.WindowWidth || height != Console.WindowHeight) { width = Console.WindowWidth; height = Console.WindowHeight; Render(); } await Task.Delay(100); } }); Console.CursorVisible = false; InitializeWorkLines(); bool exit = false; while (!exit) { Render(); var key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: if (selectedIndex > 0) selectedIndex--; break; case ConsoleKey.DownArrow: if (selectedIndex < workLines.Count - 1) selectedIndex++; break; case ConsoleKey.Spacebar: await HandleSpace(); break; case ConsoleKey.Delete: if (workLines.Count > 0) { workLines.RemoveAt(selectedIndex); if (selectedIndex >= workLines.Count) selectedIndex = workLines.Count - 1; } break; case ConsoleKey.R: await HandleRegenerate(); break; case ConsoleKey.N: await HandleNewLine(); break; case ConsoleKey.Escape: exit = true; break; } } Console.CursorVisible = tempVisible; } static void InitializeWorkLines() { // Initialize with example program workLines.Add(new WorkLine("plot the sine function, save the image to desktop as sine.png")); workLines.Add(new WorkLine("create a 4x4 grid image of sine.png duplicated 4 times, one in each corner and save it as collage.png")); workLines.Add(new WorkLine("open collage.png in the default program")); } static void Render() { lock (lockObj) { UI.Wipe(); linePositions.Clear(); // Reset line positions int currentY = 0; int consoleWidth = Console.WindowWidth; int consoleHeight = Console.WindowHeight; for (int i = 0; i < workLines.Count; i++) { var line = workLines[i]; linePositions.Add(currentY); if (i == selectedIndex && !line.IsInEditMode) { // Highlight selected line Console.BackgroundColor = ConsoleColor.Blue; } else if (line.IsInEditMode) { // Highlight edit mode line with green background Console.BackgroundColor = ConsoleColor.Green; } else { Console.BackgroundColor = ConsoleColor.Black; } // Display prefix and instruction Console.ForegroundColor = i == selectedIndex && !line.IsInEditMode ? ConsoleColor.White : ConsoleColor.Gray; Message.Send(MessageType.Raw, $"{line.GetPrefix()}{line.Instruction}"); Console.ResetColor(); currentY++; var code = line.GetActualCode(); // If expanded, show the box if (line.State == LineState.Expanded && !string.IsNullOrEmpty(code)) { // Calculate box position and size int boxStartX = 0; int boxStartY = currentY; //Width = text.Split('\n').Max(x => x.StripAnsiColorCodes().Length) + 2; //Height = text.Split('\n').Length + 2; int maxBoxWidth = code.Split('\n').Max(x => x.StripAnsiColorCodes().Length) + 2; int maxBoxHeight = code.Trim().Split('\n').Length + 2; // Display the box ConsoleBox.Show(code, boxStartX, boxStartY, maxBoxWidth, maxBoxHeight); Console.WriteLine(); // Calculate how many lines the box takes int wrappedLineCount = maxBoxHeight; currentY += wrappedLineCount; } } // Instructions at the bottom if (currentY < consoleHeight - 1) { Console.SetCursorPosition(0, currentY); Message.Send("\nUse Up/Down arrows to navigate, Space to interact, R to regenerate, N to add new line, Esc to exit."); } } } // Helper method to count wrapped lines static int CountWrappedLines(string text, int maxLineLength) { var wrappedText = ConsoleBox.ShowTextForWrapping(text, maxLineLength); return wrappedText.Split('\n').Length; } static async Task HandleSpace() { var line = workLines[selectedIndex]; if (line.IsInEditMode) { // Do nothing if in edit mode return; } switch (line.State) { case LineState.Ungenerated: await GenerateLine(line); break; case LineState.Collapsed: ExpandLine(line); break; case LineState.Expanded: CollapseLine(line); break; } } static async Task HandleRegenerate() { var line = workLines[selectedIndex]; if (line.State == LineState.Ungenerated) { // Nothing to regenerate return; } await GenerateLine(line, regenerate: true); } static async Task HandleNewLine() { // Insert a new line below the current selected index int insertIndex = selectedIndex + 1; var newLine = new WorkLine(string.Empty, isInEditMode: true); workLines.Insert(insertIndex, newLine); selectedIndex = insertIndex; Render(); // Enter edit mode Console.BackgroundColor = ConsoleColor.Green; Console.ClearLineAt(linePositions[insertIndex]); Console.SetCursorPosition(newLine.GetPrefix().Length, linePositions[insertIndex]); Console.CursorVisible = true; string originalInstruction = newLine.Instruction; StringBuilder inputBuilder = new StringBuilder(); bool editing = true; while (editing) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { // Confirm edit newLine.Instruction = inputBuilder.ToString(); newLine.IsInEditMode = false; newLine.State = LineState.Ungenerated; Console.CursorVisible = false; editing = false; } else if (key.Key == ConsoleKey.Escape) { // Cancel edit workLines.RemoveAt(insertIndex); if (insertIndex <= workLines.Count - 1) selectedIndex = insertIndex <= workLines.Count - 1 ? insertIndex : workLines.Count - 1; Console.CursorVisible = false; editing = false; } else if (key.Key == ConsoleKey.Backspace) { if (inputBuilder.Length > 0) { inputBuilder.Remove(inputBuilder.Length - 1, 1); // Remove last character from console int cursorLeft = Console.CursorLeft; int cursorTop = Console.CursorTop; if (cursorLeft > newLine.GetPrefix().Length) { Console.SetCursorPosition(cursorLeft - 1, cursorTop); Console.Write(' '); Console.SetCursorPosition(cursorLeft - 1, cursorTop); } } } else if (!char.IsControl(key.KeyChar)) { inputBuilder.Append(key.KeyChar); Console.Write(key.KeyChar); } } Render(); } static async Task GenerateLine(WorkLine line, bool regenerate = false) { if (regenerate) { line.GeneratedCode = string.Empty; line.State = LineState.Ungenerated; } // Prepare prompt string fullProgram = string.Join("\n", workLines.Select(l => l.Instruction)); string prompt = $"Write a python program that represents a line in the program. Here is the full program in natural language:\n{fullProgram}\n. You will ONLY write the code for the line \n\n{line.Instruction}\n\nOnly respond with Python code in a python code block."; string conversationId = Guid.NewGuid().ToString(); StringBuilder generated = new StringBuilder(); line.State = LineState.Expanded; // Set to expanded to show the box // Start streaming await foreach (var token in AI.GetStream(prompt, conversationId, true)) { generated.Append(token); lock (lockObj) { line.GeneratedCode = generated.ToString(); Render(); } } lock (lockObj) { line.GeneratedCode = generated.ToString(); Render(); } } static void ExpandLine(WorkLine line) { if (!string.IsNullOrEmpty(line.GeneratedCode)) { line.State = LineState.Expanded; } } static void CollapseLine(WorkLine line) { if (!string.IsNullOrEmpty(line.GeneratedCode)) { line.State = LineState.Collapsed; } } // Class representing a single line in Worklines class WorkLine { public string Instruction { get; set; } public LineState State { get; set; } public string GeneratedCode { get; set; } public bool IsInEditMode { get; set; } public string GetActualCode() => GeneratedCode.ExtractCode(); // Position of the ConsoleBox if expanded public ConsoleBox Box { get; set; } public WorkLine(string instruction, bool isInEditMode = false) { Instruction = instruction; State = LineState.Ungenerated; GeneratedCode = string.Empty; Box = null; IsInEditMode = isInEditMode; } public string GetPrefix() { if (IsInEditMode) return "> "; // Prefix for edit mode switch (State) { case LineState.Ungenerated: return "~ "; case LineState.Collapsed: return "+ "; case LineState.Expanded: return "- "; default: return "~ "; } } } } // Placeholder for UI class static class UI { public static void Wipe() { Console.Clear(); } } // Placeholder for Message class static class Message { public static void Send(MessageType type, string message) { if (type == MessageType.Raw) { Console.WriteLine(message); } } public static void Send(string message) { Console.WriteLine(message); } } enum MessageType { Raw } // Placeholder for AI class static class AI { public static async IAsyncEnumerable<string> GetStream(string prompt, string conversationId, bool someFlag) { // Simulate AI streaming by yielding characters with delay string response = $"```python\n# Python code for: {prompt}\nprint(\"Hello, World!\")\n```"; foreach (var ch in response) { await Task.Delay(50); // Simulate delay yield return ch.ToString(); } } } // Placeholder for ConsoleBox class static class ConsoleBox { public static void Show(string text, int startX, int startY, int width, int height) { // Simplistic box rendering string[] lines = text.Split('\n'); for (int i = 0; i < lines.Length && i < height - 2; i++) { Console.SetCursorPosition(startX, startY + i); string line = lines[i]; if (line.Length > width - 2) line = line.Substring(0, width - 2); Console.Write($"| {line.PadRight(width - 4)} |"); } // Draw top and bottom borders if needed for (int i = 0; i < height; i++) { if (i == 0) { Console.SetCursorPosition(startX, startY); Console.Write(new string('-', width)); } else if (i == height - 1) { Console.SetCursorPosition(startX, startY + i); Console.Write(new string('-', width)); } } } public static string ShowTextForWrapping(string text, int maxLineLength) { var lines = new List<string>(); var words = text.Split(' '); StringBuilder currentLine = new StringBuilder(); foreach (var word in words) { if (currentLine.Length + word.Length + 1 > maxLineLength) { lines.Add(currentLine.ToString()); currentLine.Clear(); } if (currentLine.Length > 0) currentLine.Append(' '); currentLine.Append(word); } if (currentLine.Length > 0) lines.Add(currentLine.ToString()); return string.Join('\n', lines); } } // Extension methods static class Extensions { public static string ExtractCode(this string text) { // Simple extraction of code from markdown code block int start = text.IndexOf("```"); if (start >= 0) { start = text.IndexOf('\n', start); if (start >= 0) { int end = text.IndexOf("```", start); if (end >= 0) { return text.Substring(start + 1, end - start - 1); } } } return text; } public static string StripAnsiColorCodes(this string text) { // Placeholder for stripping ANSI codes // Implement as needed return text; } public static void ClearLineAt(this Console console, int y) { Console.SetCursorPosition(0, y); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, y); } } }Explanation of Changes:
-
Regenerate Code with
RKey:- Added Key Handler:
case ConsoleKey.R: await HandleRegenerate(); break; - Implemented
HandleRegenerateMethod:static async Task HandleRegenerate() { var line = workLines[selectedIndex]; if (line.State == LineState.Ungenerated) { // Nothing to regenerate return; } await GenerateLine(line, regenerate: true); } - Modified
GenerateLineMethod to Support Regeneration:static async Task GenerateLine(WorkLine line, bool regenerate = false) { if (regenerate) { line.GeneratedCode = string.Empty; line.State = LineState.Ungenerated; } // ... rest of the method remains the same }
- Added Key Handler:
-
Add New Line with
NKey:- Added Key Handler:
case ConsoleKey.N: await HandleNewLine(); break; - Implemented
HandleNewLineMethod:static async Task HandleNewLine() { // Insert a new line below the current selected index int insertIndex = selectedIndex + 1; var newLine = new WorkLine(string.Empty, isInEditMode: true); workLines.Insert(insertIndex, newLine); selectedIndex = insertIndex; Render(); // Enter edit mode Console.BackgroundColor = ConsoleColor.Green; Console.ClearLineAt(linePositions[insertIndex]); Console.SetCursorPosition(newLine.GetPrefix().Length, linePositions[insertIndex]); Console.CursorVisible = true; string originalInstruction = newLine.Instruction; StringBuilder inputBuilder = new StringBuilder(); bool editing = true; while (editing) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { // Confirm edit newLine.Instruction = inputBuilder.ToString(); newLine.IsInEditMode = false; newLine.State = LineState.Ungenerated; Console.CursorVisible = false; editing = false; } else if (key.Key == ConsoleKey.Escape) { // Cancel edit workLines.RemoveAt(insertIndex); if (insertIndex <= workLines.Count - 1) selectedIndex = insertIndex <= workLines.Count - 1 ? insertIndex : workLines.Count - 1; Console.CursorVisible = false; editing = false; } else if (key.Key == ConsoleKey.Backspace) { if (inputBuilder.Length > 0) { inputBuilder.Remove(inputBuilder.Length - 1, 1); // Remove last character from console int cursorLeft = Console.CursorLeft; int cursorTop = Console.CursorTop; if (cursorLeft > newLine.GetPrefix().Length) { Console.SetCursorPosition(cursorLeft - 1, cursorTop); Console.Write(' '); Console.SetCursorPosition(cursorLeft - 1, cursorTop); } } } else if (!char.IsControl(key.KeyChar)) { inputBuilder.Append(key.KeyChar); Console.Write(key.KeyChar); } } Render(); } - Modified
WorkLineClass to Support Edit Mode:public bool IsInEditMode { get; set; } public WorkLine(string instruction, bool isInEditMode = false) { Instruction = instruction; State = LineState.Ungenerated; GeneratedCode = string.Empty; Box = null; IsInEditMode = isInEditMode; } public string GetPrefix() { if (IsInEditMode) return "> "; // Prefix for edit mode switch (State) { case LineState.Ungenerated: return "~ "; case LineState.Collapsed: return "+ "; case LineState.Expanded: return "- "; default: return "~ "; } }
- Added Key Handler:
-
Visible Generation of Text:
- Updated
GenerateLineMethod to Render During Generation:static async Task GenerateLine(WorkLine line, bool regenerate = false) { if (regenerate) { line.GeneratedCode = string.Empty; line.State = LineState.Ungenerated; } // Prepare prompt string fullProgram = string.Join("\n", workLines.Select(l => l.Instruction)); string prompt = $"Write a python program that represents a line in the program. Here is the full program in natural language:\n{fullProgram}\n. You will ONLY write the code for the line \n\n{line.Instruction}\n\nOnly respond with Python code in a python code block."; string conversationId = Guid.NewGuid().ToString(); StringBuilder generated = new StringBuilder(); line.State = LineState.Expanded; // Set to expanded to show the box // Start streaming await foreach (var token in AI.GetStream(prompt, conversationId, true)) { generated.Append(token); lock (lockObj) { line.GeneratedCode = generated.ToString(); Render(); } } lock (lockObj) { line.GeneratedCode = generated.ToString(); Render(); } } - Ensured Real-Time Rendering in
RenderMethod: TheRendermethod is called inside theforeachloop ofGenerateLine, ensuring that each token received from the AI stream is displayed in real-time.
- Updated
-
Additional Enhancements:
- Handling Cursor Visibility During Edit Mode: The cursor is made visible when editing a new line and hidden afterward.
- Visual Feedback for Edit Mode: Lines in edit mode have a green background to differentiate them from regular lines.
- Ensured Thread Safety:
Used
lockObjto synchronize access to shared resources during rendering and code generation.
Notes:
-
Placeholder Classes:
- UI: Clears the console.
- Message: Handles sending messages to the console.
- AI: Simulates AI responses with a delay to mimic streaming.
- ConsoleBox: Handles simplistic box rendering around generated code.
- Extensions: Provides utility methods for text processing.
These are simplistic implementations. In a production environment, you'd replace these with actual implementations or appropriate libraries.
-
Error Handling: The current implementation assumes that operations like removing a line won't fail (e.g., trying to remove a line from an empty list). Depending on your requirements, you might want to add more robust error handling.
-
Console Capacity: Ensure that the console window is large enough to display all lines and their corresponding code boxes. Otherwise, some content might not be visible.
-
Enhancements:
- Scrolling: If the number of lines exceeds the console height, you might want to implement scrolling.
- Persistence: Add functionality to save and load the list of
WorkLineobjects. - Customization: Allow customization of colors, prefixes, and other UI elements.
Feel free to further modify and enhance the code to better fit your specific needs!
- Pressing