Reformat using cargofmt

This commit is contained in:
timvisee
2018-09-22 18:30:29 +02:00
parent c37da9b40b
commit bd6b48cd3b
10 changed files with 146 additions and 223 deletions

View File

@@ -1,19 +1,16 @@
extern crate clap; extern crate clap;
extern crate num_cpus; extern crate num_cpus;
use clap::{Arg, ArgMatches, App}; use clap::{App, Arg, ArgMatches};
use app::*; use app::*;
/// CLI argument handler. /// CLI argument handler.
pub struct ArgHandler<'a> { pub struct ArgHandler<'a> {
matches: ArgMatches<'a>, matches: ArgMatches<'a>,
} }
impl<'a: 'b, 'b> ArgHandler<'a> { impl<'a: 'b, 'b> ArgHandler<'a> {
/// Parse CLI arguments. /// Parse CLI arguments.
pub fn parse() -> ArgHandler<'a> { pub fn parse() -> ArgHandler<'a> {
// Handle/parse arguments // Handle/parse arguments
@@ -21,88 +18,95 @@ impl<'a: 'b, 'b> ArgHandler<'a> {
.version(APP_VERSION) .version(APP_VERSION)
.author(APP_AUTHOR) .author(APP_AUTHOR)
.about(APP_ABOUT) .about(APP_ABOUT)
.arg(Arg::with_name("HOST") .arg(
.help("The host to pwn \"host:port\"") Arg::with_name("HOST")
.required(true) .help("The host to pwn \"host:port\"")
.index(1)) .required(true)
.arg(Arg::with_name("image") .index(1),
.short("i") ).arg(
.long("image") Arg::with_name("image")
.alias("images") .short("i")
.value_name("PATH") .long("image")
.help("Image paths") .alias("images")
.required(true) .value_name("PATH")
.multiple(true) .help("Image paths")
.display_order(1) .required(true)
.takes_value(true)) .multiple(true)
.arg(Arg::with_name("width") .display_order(1)
.short("w") .takes_value(true),
.long("width") ).arg(
.value_name("PIXELS") Arg::with_name("width")
.help("Draw width (def: screen width)") .short("w")
.display_order(2) .long("width")
.takes_value(true)) .value_name("PIXELS")
.arg(Arg::with_name("height") .help("Draw width (def: screen width)")
.short("h") .display_order(2)
.long("height") .takes_value(true),
.value_name("PIXELS") ).arg(
.help("Draw height (def: screen height)") Arg::with_name("height")
.display_order(3) .short("h")
.takes_value(true)) .long("height")
.arg(Arg::with_name("x") .value_name("PIXELS")
.short("x") .help("Draw height (def: screen height)")
.value_name("PIXELS") .display_order(3)
.help("Draw X offset (def: 0)") .takes_value(true),
.display_order(4) ).arg(
.takes_value(true)) Arg::with_name("x")
.arg(Arg::with_name("y") .short("x")
.short("y") .value_name("PIXELS")
.value_name("PIXELS") .help("Draw X offset (def: 0)")
.help("Draw Y offset (def: 0)") .display_order(4)
.display_order(5) .takes_value(true),
.takes_value(true)) ).arg(
.arg(Arg::with_name("count") Arg::with_name("y")
.short("c") .short("y")
.long("count") .value_name("PIXELS")
.alias("thread") .help("Draw Y offset (def: 0)")
.alias("threads") .display_order(5)
.value_name("COUNT") .takes_value(true),
.help("Number of concurrent threads (def: CPUs)") ).arg(
.display_order(6) Arg::with_name("count")
.takes_value(true)) .short("c")
.arg(Arg::with_name("fps") .long("count")
.short("r") .alias("thread")
.long("fps") .alias("threads")
.value_name("RATE") .value_name("COUNT")
.help("Frames per second with multiple images (def: 1)") .help("Number of concurrent threads (def: CPUs)")
.display_order(7) .display_order(6)
.takes_value(true)) .takes_value(true),
.get_matches(); ).arg(
Arg::with_name("fps")
.short("r")
.long("fps")
.value_name("RATE")
.help("Frames per second with multiple images (def: 1)")
.display_order(7)
.takes_value(true),
).get_matches();
// Instantiate // Instantiate
ArgHandler { ArgHandler { matches }
matches,
}
} }
/// Get the host property. /// Get the host property.
pub fn host(&'a self) -> &'b str { pub fn host(&'a self) -> &'b str {
self.matches.value_of("HOST") self.matches
.value_of("HOST")
.expect("Please specify a host") .expect("Please specify a host")
} }
/// Get the thread count. /// Get the thread count.
pub fn count(&self) -> usize { pub fn count(&self) -> usize {
self.matches.value_of("count") self.matches
.map(|count| count.parse::<usize>() .value_of("count")
.expect("Invalid count specified") .map(|count| count.parse::<usize>().expect("Invalid count specified"))
)
.unwrap_or(num_cpus::get()) .unwrap_or(num_cpus::get())
} }
/// Get the image paths. /// Get the image paths.
pub fn image_paths(&'a self) -> Vec<&'b str> { pub fn image_paths(&'a self) -> Vec<&'b str> {
self.matches.values_of("image") self.matches
.values_of("image")
.expect("Please specify an image paths") .expect("Please specify an image paths")
.collect() .collect()
} }
@@ -111,45 +115,36 @@ impl<'a: 'b, 'b> ArgHandler<'a> {
/// Use the given default value if not set. /// Use the given default value if not set.
pub fn size(&self, def: Option<(u32, u32)>) -> (u32, u32) { pub fn size(&self, def: Option<(u32, u32)>) -> (u32, u32) {
( (
self.matches.value_of("width") self.matches
.map(|width| width.parse() .value_of("width")
.expect("Invalid image width") .map(|width| width.parse().expect("Invalid image width"))
) .unwrap_or(def.expect("No screen width set or known").0),
.unwrap_or( self.matches
def.expect("No screen width set or known").0 .value_of("height")
), .map(|height| height.parse().expect("Invalid image height"))
self.matches.value_of("height") .unwrap_or(def.expect("No screen height set or known").1),
.map(|height| height.parse()
.expect("Invalid image height")
)
.unwrap_or(
def.expect("No screen height set or known").1
),
) )
} }
/// Get the image offset. /// Get the image offset.
pub fn offset(&self) -> (u32, u32) { pub fn offset(&self) -> (u32, u32) {
( (
self.matches.value_of("x") self.matches
.map(|x| x.parse::<u32>() .value_of("x")
.expect("Invalid X offset") .map(|x| x.parse::<u32>().expect("Invalid X offset"))
)
.unwrap_or(0), .unwrap_or(0),
self.matches.value_of("y") self.matches
.map(|y| y.parse::<u32>() .value_of("y")
.expect("Invalid Y offset") .map(|y| y.parse::<u32>().expect("Invalid Y offset"))
)
.unwrap_or(0), .unwrap_or(0),
) )
} }
/// Get the FPS. /// Get the FPS.
pub fn fps(&self) -> u32 { pub fn fps(&self) -> u32 {
self.matches.value_of("fps") self.matches
.map(|fps| fps.parse::<u32>() .value_of("fps")
.expect("Invalid frames per second rate") .map(|fps| fps.parse::<u32>().expect("Invalid frames per second rate"))
)
.unwrap_or(DEFAULT_IMAGE_FPS) .unwrap_or(DEFAULT_IMAGE_FPS)
} }
} }

View File

@@ -9,16 +9,11 @@ pub struct Color {
} }
impl Color { impl Color {
/// Constructor. /// Constructor.
/// ///
/// The color channels must be between 0 and 255. /// The color channels must be between 0 and 255.
pub fn from(r: u8, g: u8, b: u8) -> Color { pub fn from(r: u8, g: u8, b: u8) -> Color {
Color { Color { r, g, b }
r,
g,
b,
}
} }
/// Get a hexadecimal representation of the color, /// Get a hexadecimal representation of the color,

View File

@@ -7,8 +7,6 @@ use image::{DynamicImage, FilterType};
use pix::canvas::Canvas; use pix::canvas::Canvas;
/// A manager that manages all images to print. /// A manager that manages all images to print.
pub struct ImageManager { pub struct ImageManager {
images: Vec<DynamicImage>, images: Vec<DynamicImage>,
@@ -33,11 +31,8 @@ impl ImageManager {
println!("Load and process {} image(s)...", paths.len()); println!("Load and process {} image(s)...", paths.len());
// Load the images from the paths // Load the images from the paths
let image_manager = ImageManager::from( let image_manager =
paths.iter() ImageManager::from(paths.iter().map(|path| load_image(path, &size)).collect());
.map(|path| load_image(path, &size))
.collect()
);
// TODO: process the image slices // TODO: process the image slices
@@ -58,9 +53,7 @@ impl ImageManager {
} }
// Get the image to use // Get the image to use
let image = &mut self.images[ let image = &mut self.images[self.index as usize % bound];
self.index as usize % bound
];
// Update the image on the canvas // Update the image on the canvas
canvas.update_image(image); canvas.update_image(image);
@@ -83,15 +76,11 @@ impl ImageManager {
self.tick(canvas); self.tick(canvas);
// Sleep until we need to show the next image // Sleep until we need to show the next image
sleep(Duration::from_millis( sleep(Duration::from_millis((1000f32 / (fps as f32)) as u64));
(1000f32 / (fps as f32)) as u64
));
} }
} }
} }
/// Load the image at the given path, and size it correctly /// Load the image at the given path, and size it correctly
fn load_image(path: &str, size: &(u32, u32)) -> DynamicImage { fn load_image(path: &str, size: &(u32, u32)) -> DynamicImage {
// Create a path instance // Create a path instance
@@ -106,9 +95,5 @@ fn load_image(path: &str, size: &(u32, u32)) -> DynamicImage {
let image = image::open(&path).unwrap(); let image = image::open(&path).unwrap();
// Resize the image to fit the screen // Resize the image to fit the screen
image.resize_exact( image.resize_exact(size.0, size.1, FilterType::Gaussian)
size.0,
size.1,
FilterType::Gaussian,
)
} }

View File

@@ -16,8 +16,6 @@ use image_manager::ImageManager;
use pix::canvas::Canvas; use pix::canvas::Canvas;
use pix::client::Client; use pix::client::Client;
/// Main application entrypoint. /// Main application entrypoint.
fn main() { fn main() {
// Parse CLI arguments // Parse CLI arguments
@@ -33,8 +31,8 @@ fn start<'a>(arg_handler: &ArgHandler<'a>) {
println!("Starting... (use CTRL+C to stop)"); println!("Starting... (use CTRL+C to stop)");
// Gather facts about the host // Gather facts about the host
let screen_size = gather_host_facts(&arg_handler) let screen_size =
.expect("Failed to gather facts about pixelflut server"); gather_host_facts(&arg_handler).expect("Failed to gather facts about pixelflut server");
// Determine the size to use // Determine the size to use
let size = arg_handler.size(Some(screen_size)); let size = arg_handler.size(Some(screen_size));
@@ -48,10 +46,7 @@ fn start<'a>(arg_handler: &ArgHandler<'a>) {
); );
// Load the image manager // Load the image manager
let mut image_manager = ImageManager::load( let mut image_manager = ImageManager::load(arg_handler.image_paths(), &size);
arg_handler.image_paths(),
&size,
);
// Start the work in the image manager, to walk through the frames // Start the work in the image manager, to walk through the frames
image_manager.work(&mut canvas, arg_handler.fps()); image_manager.work(&mut canvas, arg_handler.fps());
@@ -60,9 +55,7 @@ fn start<'a>(arg_handler: &ArgHandler<'a>) {
/// Gather important facts about the host. /// Gather important facts about the host.
fn gather_host_facts(arg_handler: &ArgHandler) -> Result<(u32, u32), Error> { fn gather_host_facts(arg_handler: &ArgHandler) -> Result<(u32, u32), Error> {
// Set up a client, and get the screen size // Set up a client, and get the screen size
let size = Client::connect( let size = Client::connect(arg_handler.host().to_string())?.read_screen_size()?;
arg_handler.host().to_string(),
)?.read_screen_size()?;
// Print status // Print status
println!("Gathered screen size: {}x{}", size.0, size.1); println!("Gathered screen size: {}x{}", size.0, size.1);

View File

@@ -7,8 +7,6 @@ use image::DynamicImage;
use rect::Rect; use rect::Rect;
/// A handle to a painter thread. /// A handle to a painter thread.
/// ///
/// This also holds a channel to the painter thread, /// This also holds a channel to the painter thread,
@@ -33,16 +31,12 @@ impl Handle {
/// Push an image update. /// Push an image update.
pub fn update_image(&self, full_image: &mut DynamicImage) { pub fn update_image(&self, full_image: &mut DynamicImage) {
// Crop the image to the area // Crop the image to the area
let image = full_image.crop( let image = full_image.crop(self.area.x, self.area.y, self.area.w, self.area.h);
self.area.x,
self.area.y,
self.area.w,
self.area.h,
);
// Push a new image to the thread // Push a new image to the thread
// TODO: return this result // TODO: return this result
self.image_sender.send(image) self.image_sender
.send(image)
.expect("Failed to send image update to painter"); .expect("Failed to send image update to painter");
} }
} }

View File

@@ -1,3 +1,3 @@
// Reexport modules // Reexport modules
pub mod painter;
pub mod handle; pub mod handle;
pub mod painter;

View File

@@ -7,8 +7,6 @@ use color::Color;
use pix::client::Client; use pix::client::Client;
use rect::Rect; use rect::Rect;
/// A painter that paints on a pixelflut panel. /// A painter that paints on a pixelflut panel.
pub struct Painter { pub struct Painter {
client: Client, client: Client,
@@ -19,7 +17,12 @@ pub struct Painter {
impl Painter { impl Painter {
/// Create a new painter. /// Create a new painter.
pub fn new(client: Client, area: Rect, offset: (u32, u32), image: Option<DynamicImage>) -> Painter { pub fn new(
client: Client,
area: Rect,
offset: (u32, u32),
image: Option<DynamicImage>,
) -> Painter {
Painter { Painter {
client, client,
area, area,
@@ -61,15 +64,11 @@ impl Painter {
// Get the pixel at this location // Get the pixel at this location
let pixel = image.get_pixel(x, y); let pixel = image.get_pixel(x, y);
// Get the channels // Get the channels
let channels = pixel.channels(); let channels = pixel.channels();
// Define the color // Define the color
let color = Color::from( let color = Color::from(channels[0], channels[1], channels[2]);
channels[0],
channels[1],
channels[2],
);
// Set the pixel // Set the pixel
self.client.write_pixel( self.client.write_pixel(

View File

@@ -1,16 +1,14 @@
use std::sync::mpsc; use std::sync::mpsc;
use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc::{Receiver, Sender};
use std::thread; use std::thread;
use image::DynamicImage; use image::DynamicImage;
use painter::painter::Painter;
use painter::handle::Handle; use painter::handle::Handle;
use painter::painter::Painter;
use pix::client::Client; use pix::client::Client;
use rect::Rect; use rect::Rect;
/// A pixflut instance /// A pixflut instance
pub struct Canvas { pub struct Canvas {
host: String, host: String,
@@ -22,12 +20,7 @@ pub struct Canvas {
impl Canvas { impl Canvas {
/// Create a new pixelflut canvas. /// Create a new pixelflut canvas.
pub fn new( pub fn new(host: &str, painter_count: usize, size: (u32, u32), offset: (u32, u32)) -> Canvas {
host: &str,
painter_count: usize,
size: (u32, u32),
offset: (u32, u32),
) -> Canvas {
// Initialize the object // Initialize the object
let mut canvas = Canvas { let mut canvas = Canvas {
host: host.to_string(), host: host.to_string(),
@@ -51,19 +44,14 @@ impl Canvas {
fn spawn_painters(&mut self) { fn spawn_painters(&mut self) {
// Spawn some painters // Spawn some painters
for i in 0..self.painter_count { for i in 0..self.painter_count {
// Determine the slice width // Determine the slice width
let width = self.size.0 / (self.painter_count as u32); let width = self.size.0 / (self.painter_count as u32);
// Define the area to paint per thread // Define the area to paint per thread
let painter_area = Rect::from( let painter_area = Rect::from((i as u32) * width, 0, width, self.size.1);
(i as u32) * width,
0,
width,
self.size.1,
);
// Spawn the painter // Spawn the painter
self.spawn_painter(painter_area); self.spawn_painter(painter_area);
} }
} }
@@ -76,38 +64,24 @@ impl Canvas {
let offset = (self.offset.0, self.offset.1); let offset = (self.offset.0, self.offset.1);
// Create a channel to push new images // Create a channel to push new images
let (tx, rx): (Sender<DynamicImage>, Receiver<DynamicImage>) let (tx, rx): (Sender<DynamicImage>, Receiver<DynamicImage>) = mpsc::channel();
= mpsc::channel();
// Create the painter thread // Create the painter thread
let thread = thread::spawn(move || { let thread = thread::spawn(move || {
// Create a new client // Create a new client
let client = Client::connect(host) let client = Client::connect(host).expect("failed to open stream to pixelflut");
.expect("failed to open stream to pixelflut");
// Create a painter // Create a painter
let mut painter = Painter::new( let mut painter = Painter::new(client, area, offset, None);
client,
area,
offset,
None,
);
// Do some work // Do some work
loop { loop {
painter.work(&rx) painter.work(&rx).expect("Painter failed to perform work");
.expect("Painter failed to perform work");
} }
}); });
// Create a new painter handle, pust it to the list // Create a new painter handle, pust it to the list
self.painter_handles.push( self.painter_handles.push(Handle::new(thread, area, tx));
Handle::new(
thread,
area,
tx,
)
);
} }
// Update the image that is being rendered for all painters. // Update the image that is being rendered for all painters.

View File

@@ -1,8 +1,8 @@
extern crate bufstream; extern crate bufstream;
extern crate regex; extern crate regex;
use std::io::{Error, ErrorKind};
use std::io::prelude::*; use std::io::prelude::*;
use std::io::{Error, ErrorKind};
use std::net::TcpStream; use std::net::TcpStream;
use self::bufstream::BufStream; use self::bufstream::BufStream;
@@ -10,18 +10,13 @@ use self::regex::Regex;
use color::Color; use color::Color;
// The default buffer size for reading the client stream. // The default buffer size for reading the client stream.
// - Big enough so we don't have to expand // - Big enough so we don't have to expand
// - Small enough to not take up to much memory // - Small enough to not take up to much memory
const CMD_READ_BUFFER_SIZE: usize = 32; const CMD_READ_BUFFER_SIZE: usize = 32;
// The response format of the screen size from a pixelflut server. // The response format of the screen size from a pixelflut server.
const PIX_SERVER_SIZE_REGEX: &'static str = const PIX_SERVER_SIZE_REGEX: &'static str = r"^(?i)\s*SIZE\s+([[:digit:]]+)\s+([[:digit:]]+)\s*$";
r"^(?i)\s*SIZE\s+([[:digit:]]+)\s+([[:digit:]]+)\s*$";
/// A pixelflut client. /// A pixelflut client.
/// ///
@@ -45,19 +40,13 @@ impl Client {
/// Create a new client instane from the given host, and connect to it. /// Create a new client instane from the given host, and connect to it.
pub fn connect(host: String) -> Result<Client, Error> { pub fn connect(host: String) -> Result<Client, Error> {
// Create a new stream, and instantiate the client // Create a new stream, and instantiate the client
Ok( Ok(Client::new(create_stream(host)?))
Client::new(
create_stream(host)?
)
)
} }
/// Write a pixel to the given stream. /// Write a pixel to the given stream.
pub fn write_pixel(&mut self, x: u32, y: u32, color: &Color) -> Result<(), Error> { pub fn write_pixel(&mut self, x: u32, y: u32, color: &Color) -> Result<(), Error> {
// Write the command to set a pixel // Write the command to set a pixel
self.write_command( self.write_command(format!("PX {} {} {}", x, y, color.as_hex()))
format!("PX {} {} {}", x, y, color.as_hex()),
)
} }
/// Read the size of the screen. /// Read the size of the screen.
@@ -73,12 +62,17 @@ impl Client {
// Find captures in the data, return the result // Find captures in the data, return the result
match re.captures(&data) { match re.captures(&data) {
Some(matches) => Ok(( Some(matches) => Ok((
matches[1].parse::<u32>().expect("Failed to parse screen width, received malformed data"), matches[1]
matches[2].parse::<u32>().expect("Failed to parse screen height, received malformed data"), .parse::<u32>()
.expect("Failed to parse screen width, received malformed data"),
matches[2]
.parse::<u32>()
.expect("Failed to parse screen height, received malformed data"),
)),
None => Err(Error::new(
ErrorKind::Other,
"Failed to parse screen size, received malformed data",
)), )),
None => Err(
Error::new(ErrorKind::Other, "Failed to parse screen size, received malformed data")
),
} }
} }
@@ -92,7 +86,8 @@ impl Client {
// TODO: only flush each 100 pixels? // TODO: only flush each 100 pixels?
// TODO: make flushing configurable? // TODO: make flushing configurable?
// TODO: make buffer size configurable? // TODO: make buffer size configurable?
self.stream.flush() self.stream
.flush()
.expect("failed to flush write buffer to server"); .expect("failed to flush write buffer to server");
// Everything seems to be ok // Everything seems to be ok
@@ -124,8 +119,6 @@ impl Drop for Client {
} }
} }
/// Create a stream to talk to the pixelflut server. /// Create a stream to talk to the pixelflut server.
/// ///
/// The stream is returned as result. /// The stream is returned as result.

View File

@@ -10,11 +10,6 @@ pub struct Rect {
impl Rect { impl Rect {
pub fn from(x: u32, y: u32, w: u32, h: u32) -> Rect { pub fn from(x: u32, y: u32, w: u32, h: u32) -> Rect {
Rect { Rect { x, y, w, h }
x,
y,
w,
h,
}
} }
} }