Skip to content

Add comprehensive examples section to README #171

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jonra1993
Copy link

@jonra1993 jonra1993 commented Aug 10, 2025

πŸ“š Add Examples Documentation

This PR adds a comprehensive "Examples" section to the README that explains how to run the various examples included in the project.

✨ What's Added

  • Examples Section: New dedicated section explaining how to run examples
  • Screenshots Example: Detailed instructions for the screenshots example including:
    • How to run with cargo run --example screenshots
    • What the example does (captures screen, saves PNG frames)
    • Alternative run methods (build then run, release mode)
    • Configuration options
  • Main Example: Instructions for running the main example in src/main.rs
  • Customization Guide: Tips on modifying capture settings like FPS, crop area, resolution
  • Platform Notes: Reminder about screen recording permissions

οΏ½οΏ½ Why This Matters

  • Better Developer Experience: New users can quickly understand how to try out the library
  • Clear Instructions: Step-by-step guidance for running examples
  • Multiple Options: Shows different ways to build and run examples
  • Context: Explains what each example does before running it

πŸ“ Changes Made

  • Added new "Examples" section after the "Usage" section
  • Included code blocks with copy-paste ready commands
  • Added explanatory text for each example's functionality
  • Provided customization tips and important notes

This documentation makes the project much more accessible to developers who want to experiment with the screen capture capabilities through the provided examples.

Summary by CodeRabbit

  • New Features

    • Added a new example program for capturing screen frames at 60 FPS, saving them as PNG images with customizable options such as crop area, cursor visibility, and output resolution.
  • Documentation

    • Expanded the README with an "Examples" section, including instructions for running and customizing the new screenshot capture example and main example.
    • Added notes on required permissions for screen recording.
  • Chores

    • Updated the dependency list to include the "image" crate.
    • Updated the .gitignore file to exclude captured frame outputs.

Copy link

coderabbitai bot commented Aug 10, 2025

Walkthrough

A new screen capture example was added to the project, demonstrating frame capture at 60 FPS with cropping, cursor/highlight overlays, and saving PNGs to a directory. The .gitignore was updated to exclude the output directory. The image crate was added as a dependency, and the README was expanded with detailed example usage instructions.

Changes

Cohort / File(s) Change Summary
Example Program Addition
examples/screenshots.rs
New example for screen capture: captures at 60 FPS, crops, overlays cursor/highlights, saves PNGs, and handles user stop.
Dependency Update
Cargo.toml
Added the image crate (v0.25.2) as a dependency for image saving functionality.
Documentation Update
README.md
Added an "Examples" section detailing usage, customization, and permissions for the new and main examples.
Git Ignore Update
.gitignore
Added captured_frames/ to ignore output directory generated by the new example.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ExampleApp as screenshots.rs
    participant OS
    participant FileSystem

    User->>ExampleApp: Run example
    ExampleApp->>OS: Check platform support & permissions
    OS-->>ExampleApp: Permission granted/denied
    ExampleApp->>ExampleApp: Configure capture options
    ExampleApp->>ExampleApp: Start capture loop
    loop Until Enter pressed
        ExampleApp->>OS: Capture frame
        OS-->>ExampleApp: Return frame (BGRA)
        ExampleApp->>ExampleApp: Convert BGRA to RGBA
        ExampleApp->>FileSystem: Save PNG image
        ExampleApp->>ExampleApp: Print progress every 30 frames
    end
    User->>ExampleApp: Press Enter
    ExampleApp->>ExampleApp: Stop capture, print summary
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

A bunny with code in its fur,
Captures screens in a blur.
With PNGs saved neat,
And examples complete,
It hops through the docs with a purr.
Now frames are ignored,
And dependencies storedβ€”
This update’s a carrot for sure! πŸ₯•

Note

πŸ”Œ MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
  • πŸ“ Generate Docstrings
πŸ§ͺ Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

πŸͺ§ 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.
    • Explain this complex logic.
    • 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 explain this code block.
  • 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 explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @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

@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: 4

🧹 Nitpick comments (3)
.gitignore (1)

5-5: Scope the ignore to the examples directory (optional).

Current pattern will ignore any directory named captured_frames anywhere in the repo. If you want to restrict to the example’s output, scope it.

-captured_frames/
+examples/captured_frames/
README.md (1)

113-119: Clarify output path and tighten phrasing (β€œPNG images” β†’ β€œPNGs”).

LanguageTool flagged β€œPNG images” as tautological. Also, the example writes to examples/captured_frames/.

-**What it does:**
-- Captures your screen at 60 FPS
-- Saves frames as PNG images in a `captured_frames/` directory
+**What it does:**
+- Captures your screen at 60 FPS
+- Saves frames as PNGs in `examples/captured_frames/`
examples/screenshots.rs (1)

137-143: Faster BGRA→RGBA conversion: swap channels in-place on a clone.

Reduces per-pixel allocations and copies.

-            // Convert BGRA to RGBA (swap red and blue channels)
-            let mut rgba_data = Vec::with_capacity(bgra_frame.data.len());
-            for chunk in bgra_frame.data.chunks(4) {
-                if chunk.len() == 4 {
-                    rgba_data.extend_from_slice(&[chunk[2], chunk[1], chunk[0], chunk[3]]);
-                }
-            }
+            // Convert BGRA to RGBA (swap red and blue channels)
+            let mut rgba_data = bgra_frame.data.clone();
+            for px in rgba_data.chunks_mut(4) {
+                // px = [B, G, R, A] -> [R, G, B, A]
+                px.swap(0, 2);
+            }
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between c03f15a and 23cf710.

β›” Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
πŸ“’ Files selected for processing (4)
  • .gitignore (1 hunks)
  • Cargo.toml (1 hunks)
  • README.md (1 hunks)
  • examples/screenshots.rs (1 hunks)
🧰 Additional context used
πŸͺ› LanguageTool
README.md

[style] ~115-~115: This phrase is redundant (β€˜G’ stands for β€˜graphic’). Use simply β€œPNGs”.
Context: ...your screen at 60 FPS - Saves frames as PNG images in a captured_frames/ directory - Cro...

(ACRONYM_TAUTOLOGY)

@@ -19,6 +19,7 @@ categories = ["graphics", "multimedia", "multimedia::video"]
futures = "0.3.31"
sysinfo = "0.30.0"
thiserror = "2.0.12"
image = "0.25.2"
Copy link

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

❓ Verification inconclusive

Move image to dev-dependencies to avoid bloating library consumers.

image is only used by the examples. Keeping it under [dependencies] makes every user of the library pull it in unnecessarily.

Apply this change:

 [dependencies]
 futures = "0.3.31"
 sysinfo = "0.30.0"
 thiserror = "2.0.12"
-image = "0.25.2"

Add this section outside the changed block:

[dev-dependencies]
image = "0.25.2"

Verify image isn’t used in library code:


🏁 Script executed:

#!/bin/bash
# Check that 'image' usage is confined to examples, not src/
rg -n --hidden -S '(^use\s+image::)|(^extern\s+crate\s+image)|(\bimage::)' -g "src/**"

Length of output: 88


Move image to dev-dependencies

Verified via rg that image isn’t referenced in src/, so it can safely be relocated to avoid bloating library consumers.

Next steps:

  • Remove image = "0.25.2" from [dependencies] in Cargo.toml
  • Add it under a new [dev-dependencies] section

Suggested change in Cargo.toml:

 [dependencies]
 futures = "0.3.31"
 sysinfo = "0.30.0"
 thiserror = "2.0.12"
-image = "0.25.2"

+[dev-dependencies]
+image = "0.25.2"
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
image = "0.25.2"
[dependencies]
futures = "0.3.31"
sysinfo = "0.30.0"
thiserror = "2.0.12"
[dev-dependencies]
image = "0.25.2"
πŸ€– Prompt for AI Agents
In Cargo.toml at line 22, the `image` crate is currently listed under
`[dependencies]` but is not used in the main source code. To avoid bloating
library consumers, remove the line `image = "0.25.2"` from the `[dependencies]`
section and add it under a new `[dev-dependencies]` section instead.

Comment on lines +55 to +57
// Create Capturer
let mut capturer = Capturer::build(options).unwrap();

Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Avoid unwrap() on capturer construction; provide context on failure.

Use expect (or proper error handling) to avoid panics without context.

-    let mut capturer = Capturer::build(options).unwrap();
+    let mut capturer = Capturer::build(options)
+        .expect("Failed to build Capturer (check platform support/permissions/options)");
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Create Capturer
let mut capturer = Capturer::build(options).unwrap();
// Create Capturer
let mut capturer = Capturer::build(options)
.expect("Failed to build Capturer (check platform support/permissions/options)");
πŸ€– Prompt for AI Agents
In examples/screenshots.rs around lines 55 to 57, replace the use of unwrap() on
the Capturer::build call with expect() to provide a clear error message if
construction fails. This will avoid panics without context by giving a
descriptive message explaining why the capturer creation failed.

Comment on lines +58 to +63
// Create output directory
let output_dir = "examples/captured_frames";
if !Path::new(output_dir).exists() {
fs::create_dir(output_dir).unwrap();
println!("πŸ“ Created output directory: {}", output_dir);
}
Copy link

Choose a reason for hiding this comment

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

πŸ› οΈ Refactor suggestion

Use create_dir_all and avoid unwrap() for better resilience.

This handles pre-existing parents and gives clearer failure messages.

-    let output_dir = "examples/captured_frames";
-    if !Path::new(output_dir).exists() {
-        fs::create_dir(output_dir).unwrap();
-        println!("πŸ“ Created output directory: {}", output_dir);
-    }
+    let output_dir = "examples/captured_frames";
+    if !Path::new(output_dir).exists() {
+        fs::create_dir_all(output_dir)
+            .expect("Failed to create output directory");
+        println!("πŸ“ Created output directory: {}", output_dir);
+    }
πŸ€– Prompt for AI Agents
In examples/screenshots.rs around lines 58 to 63, replace fs::create_dir with
fs::create_dir_all to ensure all parent directories are created if missing.
Also, avoid using unwrap() by properly handling the Result returned from
create_dir_all, such as using expect with a clear error message or matching on
the Result to handle errors gracefully.

Comment on lines +89 to +116
// Try to get the next frame
match capturer.get_next_frame() {
Ok(frame) => {
frame_count += 1;

// Save frame as image
if let Err(e) = save_frame_as_image(&frame, frame_count, output_dir) {
eprintln!("Error saving frame {frame_count}: {e}");
}

// Print capture info every 30 frames (every 0.5 seconds at 60 FPS)
if frame_count % 30 == 0 {
let elapsed = start_time.elapsed().as_secs_f64();
let fps = frame_count as f64 / elapsed;
println!(
"πŸ“Έ Captured frame {frame_count} | FPS: {fps:.1} | Elapsed: {elapsed:.1}s"
);
}
}
Err(mpsc::RecvError) => {
// No frame available yet, continue
continue;
}
}

// Small delay to prevent excessive CPU usage
thread::sleep(Duration::from_millis(16)); // ~60 FPS
}
Copy link

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

🧩 Analysis chain

High-CPU spin: continue skips the sleep; also avoid coupling to mpsc::RecvError.

When no frame is available, the continue bypasses the sleep, causing a busy loop. Also, matching a concrete mpsc::RecvError ties this code to a specific error type; prefer a wildcard unless you intend to branch on variants.

-            Err(mpsc::RecvError) => {
-                // No frame available yet, continue
-                continue;
-            }
+            Err(_) => {
+                // No frame available yet
+            }

Verify get_next_frame’s error type to ensure the wildcard match is appropriate:


🏁 Script executed:

#!/bin/bash
# Try to locate the signature and error type of `get_next_frame`
rg -n "fn\s+get_next_frame\s*\(" -A 5
rg -n "get_next_frame\s*\(" -A 2 | sed -n '1,120p'

Length of output: 1031


Reduce busy-loop by allowing sleep on errors

Removing the continue ensures the per-loop sleep still runs when no frame is ready, preventing a high-CPU spin. Using a wildcard error pattern also decouples from the concrete mpsc::RecvError.

β€’ File: examples/screenshots.rs
β€’ Lines ~89–97

Suggested diff:

-            Err(mpsc::RecvError) => {
-                // No frame available yet, continue
-                continue;
-            }
+            Err(_) => {
+                // No frame available yet; fall through to sleep
+            }
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Try to get the next frame
match capturer.get_next_frame() {
Ok(frame) => {
frame_count += 1;
// Save frame as image
if let Err(e) = save_frame_as_image(&frame, frame_count, output_dir) {
eprintln!("Error saving frame {frame_count}: {e}");
}
// Print capture info every 30 frames (every 0.5 seconds at 60 FPS)
if frame_count % 30 == 0 {
let elapsed = start_time.elapsed().as_secs_f64();
let fps = frame_count as f64 / elapsed;
println!(
"πŸ“Έ Captured frame {frame_count} | FPS: {fps:.1} | Elapsed: {elapsed:.1}s"
);
}
}
Err(mpsc::RecvError) => {
// No frame available yet, continue
continue;
}
}
// Small delay to prevent excessive CPU usage
thread::sleep(Duration::from_millis(16)); // ~60 FPS
}
// Try to get the next frame
match capturer.get_next_frame() {
Ok(frame) => {
frame_count += 1;
// Save frame as image
if let Err(e) = save_frame_as_image(&frame, frame_count, output_dir) {
eprintln!("Error saving frame {frame_count}: {e}");
}
// Print capture info every 30 frames (every 0.5 seconds at 60 FPS)
if frame_count % 30 == 0 {
let elapsed = start_time.elapsed().as_secs_f64();
let fps = frame_count as f64 / elapsed;
println!(
"πŸ“Έ Captured frame {frame_count} | FPS: {fps:.1} | Elapsed: {elapsed:.1}s"
);
}
}
Err(_) => {
// No frame available yet; fall through to sleep
}
}
// Small delay to prevent excessive CPU usage
thread::sleep(Duration::from_millis(16)); // ~60 FPS
}
πŸ€– Prompt for AI Agents
In examples/screenshots.rs around lines 89 to 97, the current code uses
`continue` on `mpsc::RecvError`, which skips the per-loop sleep and causes a
busy-loop with high CPU usage. To fix this, remove the `continue` statement so
the thread sleep still executes even when no frame is ready. Also, replace the
specific `Err(mpsc::RecvError)` pattern with a wildcard `Err(_)` to decouple
from the concrete error type.

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.

1 participant