Skip to content

Implement input handling and exit mechanism - #19

Merged
unhappychoice merged 2 commits into
mainfrom
feat/input-handling-exit-10
Nov 9, 2025
Merged

unhappychoice merged 2 commits into
mainfrom
feat/input-handling-exit-10

Conversation

@unhappychoice

@unhappychoice unhappychoice commented Nov 9, 2025 •

Copy link
Copy Markdown
Owner

close: #10

Summary

  • Added ctrlc dependency to handle Ctrl+C signals properly
  • Implemented signal handler using Arc<AtomicBool> for thread-safe exit flag
  • Added Esc key handling for graceful exit
  • Created dedicated cleanup() method to ensure terminal is always restored to normal state
  • Removed support for 'q' key exit, now only Ctrl+C and Esc trigger exit

Test plan

  • cargo check passes
  • cargo test passes
  • cargo clippy --all-targets --all-features -- -D warnings passes
  • cargo fmt applied
  • Manual testing: Press Esc to exit
  • Manual testing: Press Ctrl+C to exit
  • Manual testing: Verify terminal is restored properly after exit

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Application now exits when pressing Ctrl-C.
  • Changes

    • Exit key binding changed from 'q' to 'Esc'.

unhappychoice and others added 2 commits November 10, 2025 01:51
- Setup Ctrl+C signal handler using ctrlc crate
- Exit gracefully on Esc key press
- Ensure terminal is restored to normal state on exit
- Cleanup resources properly with dedicated cleanup method

close: #10

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds graceful Ctrl-C signal handling and terminal lifecycle management to the UI. Introduces the ctrlc dependency, a concurrency-safe should_exit atomic flag for shutdown coordination, signal handler configuration, and public run() method with terminal setup and cleanup logic.

Changes

Cohort / File(s) Change Summary
Dependency Management
Cargo.toml
Added ctrlc v3.4 dependency for Ctrl-C signal handling
UI Lifecycle and Signal Handling
src/ui.rs
Added should_exit: Arc<AtomicBool> field for thread-safe shutdown coordination; introduced public run() method to manage UI lifecycle with terminal setup and cleanup; added setup_signal_handler() to configure Ctrl-C handling; added cleanup() to restore terminal state; modified main loop to check shutdown flag and transition to Finished state; changed key handling to respond only to Esc instead of both 'q' and Esc

Sequence Diagram

sequenceDiagram
    participant User
    participant UI Loop
    participant Signal Handler
    participant Terminal

    User->>Signal Handler: Press Ctrl-C
    Signal Handler->>Signal Handler: Flip should_exit flag
    
    rect rgb(200, 220, 255)
    Note over UI Loop: Main Event Loop
    UI Loop->>UI Loop: Check should_exit flag
    UI Loop->>UI Loop: Transition to Finished state
    end
    
    UI Loop->>Terminal: Call cleanup()
    Terminal->>Terminal: Restore terminal state
    Terminal-->>UI Loop: Return success
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

  • Thread safety verification: Ensure Arc<AtomicBool> usage is correct for concurrent access from signal handler and main UI thread
  • Signal handler lifecycle: Verify signal handler setup doesn't leak resources and integrates cleanly with the event loop
  • Terminal state restoration: Confirm cleanup() properly restores terminal to normal state in all exit paths

Possibly related issues

  • Issue #10: The changes directly implement the objectives outlined—signal handler for Ctrl-C, graceful exit with terminal cleanup, and input-based exit logic.

Poem

🐰 A Ctrl-C upon the key, now handled gracefully,
The terminal bows with respect, its state to resurrect,
With signals caught and cleanup done, the UI race is won—
Safe shutdown threads now play, the rabbit's atomic way! 🌙

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the main change: implementing input handling and an exit mechanism with Ctrl+C and Esc support.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #10: signal handler for Ctrl+C, input handling for Esc key, terminal cleanup on exit, and signal-safe exit flag using Arc.
Out of Scope Changes check ✅ Passed All changes are within scope: the ctrlc dependency and UI modifications directly implement the exit mechanism requirements from issue #10 with no unrelated changes detected.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/input-handling-exit-10

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/ui.rs (1)

100-103: Consider stronger memory ordering for the exit flag.

While Ordering::Relaxed is likely sufficient for a simple exit flag, using Ordering::Acquire would provide stronger synchronization guarantees and is more defensive. The performance difference is negligible.

-if self.should_exit.load(Ordering::Relaxed) {
+if self.should_exit.load(Ordering::Acquire) {
     self.state = UIState::Finished;
 }

Similarly, update the signal handler to use Ordering::Release:

 ctrlc::set_handler(move || {
-    should_exit.store(true, Ordering::Relaxed);
+    should_exit.store(true, Ordering::Release);
 })
Cargo.toml (1)

48-48: Update ctrlc dependency to the latest stable version.

Version 3.4 is outdated; the latest stable release is 3.5.1. While no security advisories were found, consider updating to 3.5.1 to receive the latest improvements and fixes.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ad8fe8e and f16f674.

📒 Files selected for processing (2)
  • Cargo.toml (1 hunks)
  • src/ui.rs (5 hunks)
🔇 Additional comments (5)
src/ui.rs (5)

13-14: LGTM: Required imports for thread-safe exit flag.

The imports correctly bring in the necessary types for the Arc<AtomicBool> pattern used for signal handling.


38-38: LGTM: Appropriate type for cross-thread exit signaling.

The Arc<AtomicBool> field enables the signal handler to safely communicate exit intent to the main loop.


73-85: LGTM: Proper cleanup ensures terminal restoration.

The pattern correctly ensures cleanup() is called after run_loop() completes, regardless of whether it returns Ok or Err. This guarantees terminal state restoration on exit.


87-96: LGTM: Comprehensive terminal cleanup.

The cleanup method properly restores the terminal state by disabling raw mode, leaving the alternate screen, disabling mouse capture, and showing the cursor. This ensures a clean exit.


125-127: LGTM: Simplified exit key handling.

The change to only handle the Esc key (removing 'q') aligns with the PR objectives. Exit is now triggered only by Esc or Ctrl-C as intended.

Comment thread src/ui.rs
Comment on lines +43 to +44
let should_exit = Arc::new(AtomicBool::new(false));
Self::setup_signal_handler(should_exit.clone());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Signal handler setup in constructor causes panics with multiple instances.

Calling setup_signal_handler in the constructor is problematic because ctrlc::set_handler can only be called once per process. If multiple UI instances are created (e.g., in tests or if the API is used programmatically), the second call will panic.

Recommendation: Move signal handler setup into the run() method instead:

 pub fn new(speed_ms: u64, _is_commit_specified: bool, repo: Option<&'a GitRepository>) -> Self {
-    let should_exit = Arc::new(AtomicBool::new(false));
-    Self::setup_signal_handler(should_exit.clone());
-
     Self {
         state: UIState::Playing,
         speed_ms,
         file_tree: FileTreePane,
         editor: EditorPane,
         terminal: TerminalPane,
         status_bar: StatusBarPane,
         engine: AnimationEngine::new(speed_ms),
         metadata: None,
         repo,
-        should_exit,
+        should_exit: Arc::new(AtomicBool::new(false)),
     }
 }

Then in run():

pub fn run(&mut self) -> Result<()> {
    Self::setup_signal_handler(self.should_exit.clone());
    enable_raw_mode()?;
    // ... rest of the method
🤖 Prompt for AI Agents
In src/ui.rs around lines 43 to 44, calling Self::setup_signal_handler in the
constructor causes panics when multiple UI instances are created because
ctrlc::set_handler may only be registered once per process; remove the
setup_signal_handler call from the constructor and instead call
Self::setup_signal_handler(self.should_exit.clone()) at the start of the run()
method (before enabling raw mode) so the handler is only registered when run()
is invoked and not during object construction.

Comment thread src/ui.rs
Comment on lines +60 to +65
fn setup_signal_handler(should_exit: Arc<AtomicBool>) {
ctrlc::set_handler(move || {
should_exit.store(true, Ordering::Relaxed);
})
.expect("Error setting Ctrl-C handler");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Improve error handling: propagate errors instead of panicking.

Using .expect() will panic if the signal handler cannot be set. This is particularly problematic given the constructor issue noted above. Consider returning a Result to allow the caller to handle errors gracefully.

Suggestion: Change the signature to return a Result:

-fn setup_signal_handler(should_exit: Arc<AtomicBool>) {
+fn setup_signal_handler(should_exit: Arc<AtomicBool>) -> Result<()> {
     ctrlc::set_handler(move || {
         should_exit.store(true, Ordering::Relaxed);
     })
-    .expect("Error setting Ctrl-C handler");
+    .map_err(|e| anyhow::anyhow!("Error setting Ctrl-C handler: {}", e))
 }

Then propagate the error in the caller using ?.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/ui.rs around lines 60 to 65, setup_signal_handler currently calls
ctrlc::set_handler(...).expect(...), which panics on failure; change the
function signature to return Result<(), ctrlc::Error> (or a suitable Box<dyn
std::error::Error>>), remove the expect and instead return the result from
ctrlc::set_handler using the ? operator, and update any callers to propagate the
Result (using ? or map/handle the error) so signal-handler setup failures are
returned to the caller for graceful handling.

@unhappychoice
unhappychoice merged commit 3d2113d into main Nov 9, 2025
@unhappychoice
unhappychoice deleted the feat/input-handling-exit-10 branch November 9, 2025 18:35
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.

Implement input handling and exit mechanism

1 participant