Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make sure console is restored #270

Merged
merged 2 commits into from
Jan 22, 2025
Merged

make sure console is restored #270

merged 2 commits into from
Jan 22, 2025

Conversation

tomlm
Copy link
Collaborator

@tomlm tomlm commented Jan 22, 2025

  • Always dispose console driver
  • Implment CursorsConsole .PrepareConsole() and RestoreConsole() correctly.

NOTE: This is correctly cleaning up curses, but there is a dotnet platform bug dotnet/runtime#111272 which was just merged in december which will fix this in dotnet 10.x release which is that dotnet is not correctly reseting the console state when a dotnet console app exits.

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

📝 Walkthrough

Walkthrough

The pull request introduces modifications to the ConsoloniaLifetime and CursesConsole classes, focusing on improving resource management and console initialization. In the ConsoloniaLifetime class, the StartCore method now includes a try-finally block to ensure proper resource disposal, even if an exception occurs during the main loop execution. The Dispose method adds a null check for TopLevel.PlatformImpl when casting to ConsoleWindow, enhancing error handling.

In the CursesConsole class, significant changes include the introduction of PrepareConsole and RestoreConsole methods to manage console initialization and cleanup. The input processing logic has been refined, with improved handling of key events, ESC sequences, and mouse input. These modifications aim to enhance the robustness and clarity of console interaction and lifecycle management.

Possibly related PRs

  • Enable alternate screen buffer #141: Modifies ConsoloniaLifetime class, which is directly related to the changes made in the main PR regarding the Dispose method and lifecycle management.
  • 190-strange-coloring-auto-detect-ega #237: Involves changes to the ConsoloniaLifetime class, adding a method that checks the console color mode, which may relate to the overall lifecycle and resource management discussed in the main PR.
  • Dispatching input alltogether #256: Introduces changes to the ConsoleBase class, which may impact how input and output are managed during the application lifecycle, relevant to the changes in the main PR.

Suggested labels

bug, enhancement


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (2)
src/Consolonia.PlatformSupport/CursesConsole.cs (1)

248-418: Refactor complex key handling logic for maintainability

The key handling logic within the ProcessInput() method, particularly for ESC sequences, is complex and may be difficult to maintain or debug.

Consider refactoring this code by:

  • Breaking it into smaller helper methods with descriptive names.
  • Adding comments to explain non-obvious logic.
  • Using a state machine or parsing library to handle key sequences more elegantly.
src/Consolonia.Core/ConsoloniaLifetime.cs (1)

95-105: Handle exceptions within the main loop appropriately

While the try-finally block ensures Dispose() is called, any exceptions thrown within Dispatcher.UIThread.MainLoop may cause abrupt termination without proper logging or user feedback.

Consider catching exceptions inside the try block to log them or provide user-friendly error messages:

 try
 {
-    Dispatcher.UIThread.MainLoop(_cts.Token);
+    try
+    {
+        Dispatcher.UIThread.MainLoop(_cts.Token);
+    }
+    catch (Exception ex)
+    {
+        // Log the exception or handle it accordingly
+        Console.Error.WriteLine($"An error occurred: {ex.Message}");
+    }
     Environment.ExitCode = _exitCode;
     return _exitCode;
 }
 finally
 {
     Dispose();
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0c1fd60 and dc0779d.

📒 Files selected for processing (2)
  • src/Consolonia.Core/ConsoloniaLifetime.cs (2 hunks)
  • src/Consolonia.PlatformSupport/CursesConsole.cs (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (1)
src/Consolonia.PlatformSupport/CursesConsole.cs (1)

248-418: Review the timeout setting for input processing

Setting Curses.timeout(200); introduces a 200ms delay when processing input, which may impact the responsiveness of the application, especially for quick key presses.

Confirm if the 200ms timeout is necessary for processing ESC sequences. If not, consider reducing the timeout or exploring alternative approaches that do not compromise responsiveness.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/Consolonia.PlatformSupport/CursesConsole.cs (1)

145-169: Consider implementing IDisposable pattern.

The console resource management would benefit from proper implementation of the IDisposable pattern to ensure deterministic cleanup.

-public class CursesConsole : ConsoleBase
+public class CursesConsole : ConsoleBase, IDisposable
 {
     private bool _disposed;
     private Curses.Window _cursesWindow;

+    protected virtual void Dispose(bool disposing)
+    {
+        if (_disposed) return;
+        if (disposing)
+        {
+            RestoreConsole();
+        }
+        _disposed = true;
+    }
+
+    public void Dispose()
+    {
+        Dispose(true);
+        GC.SuppressFinalize(this);
+    }
+
+    ~CursesConsole()
+    {
+        Dispose(false);
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc0779d and c477175.

📒 Files selected for processing (2)
  • src/Consolonia.Core/ConsoloniaLifetime.cs (2 hunks)
  • src/Consolonia.PlatformSupport/CursesConsole.cs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Consolonia.Core/ConsoloniaLifetime.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (4)
src/Consolonia.PlatformSupport/CursesConsole.cs (4)

111-111: Initialize _cursesWindow in constructor or add null checks.

The field is used in multiple methods but lacks proper initialization guarantees.


128-129: Avoid calling virtual methods from constructors.

Calling PrepareConsole() (virtual) indirectly from the constructor via StartEventLoop() can lead to unexpected behavior if a subclass overrides this method.


145-157: Add error handling for Curses initialization.

The PrepareConsole() method should handle potential failures from Curses functions.

Additionally, consider adding debug logging to track console state transitions:

 public override void PrepareConsole()
 {
+    Debug.WriteLine("Preparing Curses console...");
     _cursesWindow = Curses.initscr();
     Curses.raw();
     Curses.noecho();
     _cursesWindow.keypad(true);
     Curses.cbreak();
     Curses.mousemask(
         Curses.Event.AllEvents | Curses.Event.ReportMousePosition,
         out Curses.Event _);

     base.PrepareConsole();
+    Debug.WriteLine("Curses console prepared successfully");
 }

159-169: Add null check and error handling in RestoreConsole().

The method should safely handle cases where _cursesWindow is null.

Additionally, consider adding debug logging for console cleanup:

 public override void RestoreConsole()
 {
+    Debug.WriteLine("Restoring Curses console...");
     base.RestoreConsole();

+    if (_cursesWindow == null)
+    {
+        Debug.WriteLine("Warning: Curses window was null during restore");
+        return;
+    }

     Curses.mousemask(0, out Curses.Event _);
     Curses.nocbreak();
     _cursesWindow.keypad(false);
     Curses.echo();
     Curses.noraw();
     Curses.endwin();
+    Debug.WriteLine("Curses console restored successfully");
 }

@tomlm tomlm marked this pull request as ready for review January 22, 2025 04:20
@tomlm tomlm requested a review from jinek January 22, 2025 04:20
@tomlm tomlm merged commit 5b73343 into main Jan 22, 2025
3 checks passed
@tomlm tomlm deleted the tomlm/fixCursesCleanup branch January 22, 2025 18:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants