Repository navigation
Implement input handling and exit mechanism - #19
Conversation
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- 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]>
WalkthroughAdds graceful Ctrl-C signal handling and terminal lifecycle management to the UI. Introduces the Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes
Possibly related issues
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/ui.rs (1)
100-103: Consider stronger memory ordering for the exit flag.While
Ordering::Relaxedis likely sufficient for a simple exit flag, usingOrdering::Acquirewould 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
📒 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 afterrun_loop()completes, regardless of whether it returnsOkorErr. 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.
| let should_exit = Arc::new(AtomicBool::new(false)); | ||
| Self::setup_signal_handler(should_exit.clone()); |
There was a problem hiding this comment.
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.
| fn setup_signal_handler(should_exit: Arc<AtomicBool>) { | ||
| ctrlc::set_handler(move || { | ||
| should_exit.store(true, Ordering::Relaxed); | ||
| }) | ||
| .expect("Error setting Ctrl-C handler"); | ||
| } |
There was a problem hiding this comment.
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.
close: #10
Summary
ctrlcdependency to handle Ctrl+C signals properlyArc<AtomicBool>for thread-safe exit flagcleanup()method to ensure terminal is always restored to normal stateTest plan
cargo checkpassescargo testpassescargo clippy --all-targets --all-features -- -D warningspassescargo fmtapplied🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Changes