<commit_before>#[macro_use(shared_ntfy)]
extern crate rust_install;

extern crate clap;
extern crate multirust;

extern crate rustc_bisect;

use clap::{App, AppSettings, Arg};

use multirust::{Cfg, Notification};

use rustc_bisect::{Cmd, Error, Result, ToolchainSpec};

// Copied from multirust-rs.
fn set_globals() -> multirust::Result<Cfg> {
    // Base config
    let verbose = false;
    Cfg::from_env(shared_ntfy!(move |n: Notification| {
        use multirust::notify::NotificationLevel::*;
        match n.level() {
            Verbose => {
                if verbose {
                    println!("{}", n);
                }
            }
            _ => {
                println!("{}", n);
            }
        }
    }))
}

fn run_rust_bisect() -> Result<()> {
    let matches = App::new("rustc-bisect")
                      .author("Kamal Marhubi <kamal@marhubi.com>")
                      .setting(AppSettings::TrailingVarArg)
                      .arg(Arg::with_name("toolchain")
                               .long("tmp-toolchain")
                               .takes_value(true)
                               .value_name("TOOLCHAIN")
                               .required(true))
                      .arg(Arg::with_name("good")
                               .long("good")
                               .takes_value(true)
                               .value_name("TOOLCHAIN"))
                      .arg(Arg::with_name("bad")
                               .long("bad")
                               .takes_value(true)
                               .value_name("TOOLCHAIN"))
                      .arg(Arg::with_name("COMMAND")
                               .multiple(true)
                               .required(true))
                      .get_matches();

    let cfg = try!(set_globals());

    let cmd: Vec<_> = matches.values_of_os("COMMAND").expect("COMMAND").collect();
    let cmd = Cmd::from(&cmd[..]);

    let toolchain = try!(cfg.get_toolchain(matches.value_of("toolchain").expect("toolchain"),
                                           false));
    try!(toolchain.install_from_dist_if_not_installed());

    println!("{}", try!(cmd.succeeds_with(&toolchain)));

    Ok(())
}

fn main() {
    run_rust_bisect().expect("something went wrong");
}
<commit_msg>Remove unnecessary import<commit_after>#[macro_use(shared_ntfy)]
extern crate rust_install;

extern crate clap;
extern crate multirust;

extern crate rustc_bisect;

use clap::{App, AppSettings, Arg};

use multirust::{Cfg, Notification};

use rustc_bisect::{Cmd, Result, ToolchainSpec};

// Copied from multirust-rs.
fn set_globals() -> multirust::Result<Cfg> {
    // Base config
    let verbose = false;
    Cfg::from_env(shared_ntfy!(move |n: Notification| {
        use multirust::notify::NotificationLevel::*;
        match n.level() {
            Verbose => {
                if verbose {
                    println!("{}", n);
                }
            }
            _ => {
                println!("{}", n);
            }
        }
    }))
}

fn run_rust_bisect() -> Result<()> {
    let matches = App::new("rustc-bisect")
                      .author("Kamal Marhubi <kamal@marhubi.com>")
                      .setting(AppSettings::TrailingVarArg)
                      .arg(Arg::with_name("toolchain")
                               .long("tmp-toolchain")
                               .takes_value(true)
                               .value_name("TOOLCHAIN")
                               .required(true))
                      .arg(Arg::with_name("good")
                               .long("good")
                               .takes_value(true)
                               .value_name("TOOLCHAIN"))
                      .arg(Arg::with_name("bad")
                               .long("bad")
                               .takes_value(true)
                               .value_name("TOOLCHAIN"))
                      .arg(Arg::with_name("COMMAND")
                               .multiple(true)
                               .required(true))
                      .get_matches();

    let cfg = try!(set_globals());

    let cmd: Vec<_> = matches.values_of_os("COMMAND").expect("COMMAND").collect();
    let cmd = Cmd::from(&cmd[..]);

    let toolchain = try!(cfg.get_toolchain(matches.value_of("toolchain").expect("toolchain"),
                                           false));
    try!(toolchain.install_from_dist_if_not_installed());

    println!("{}", try!(cmd.succeeds_with(&toolchain)));

    Ok(())
}

fn main() {
    run_rust_bisect().expect("something went wrong");
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;

extern crate glium_sdl2;
extern crate sdl2;

#[derive(Copy, Clone)]
struct Vertex {
    position: [f32; 2],
}
implement_vertex!(Vertex, position);

impl std::fmt::Display for Vertex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "({}, {})", self.position[0], self.position[1])
    }
}

fn main() {
    use glium_sdl2::DisplayBuild;
    use glium::Surface;

    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();
    let display = video_subsystem.window("Tutorial 01", 800, 600).resizable().build_glium().unwrap();
    let v1 = Vertex { position: [-0.5, -0.5] };
    let v2 = Vertex { position: [ 0.0,  0.5] };
    let v3 = Vertex { position: [ 0.5, -0.25] };
    let shape = vec![v1, v2, v3];

    let vertex_buffer = glium::VertexBuffer::new(&display, &shape).unwrap();
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    fn create_shaders(display: &glium_sdl2::SDL2Facade) -> glium::Program {
        let vertex_shader_src = r#"
            #version 130

            in vec2 position;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0);
            }
        "#;

        let fragment_shader_src = r#"
            #version 130

            out vec4 color;

            void main() {
                color = vec4(1.0, 0.0, 0.0, 1.0);
            }
        "#;

        glium::Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap()
    }
    let program = create_shaders(&display);

    let mut running = true;
    let mut event_pump = sdl_context.event_pump().unwrap();

    while running {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 1.0, 1.0);
        target.draw(&vertex_buffer, &indices, &program, &glium::uniforms::EmptyUniforms,
                    &Default::default()).unwrap();
        target.finish().unwrap();

        for event in event_pump.poll_iter() {
            use sdl2::event::Event;

            match event {
                Event::Quit { .. } => running = false,
                _ => ()
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::Vertex;

    #[test]
    fn test_vertex() {
        assert_eq!("(3, 5)", format!("{}", Vertex { position: [3.0, 5.0] }));
    }
}
<commit_msg>learning stuff<commit_after>#[macro_use]
extern crate glium;

extern crate glium_sdl2;
extern crate sdl2;

use std::fmt;
use glium::{Surface, VertexBuffer, Program, index, uniforms};
use sdl2::event::Event;
use glium_sdl2::{DisplayBuild, SDL2Facade};

#[derive(Copy, Clone)]
struct Vertex {
    position: [f32; 2],
}
implement_vertex!(Vertex, position);

impl fmt::Display for Vertex {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.position[0], self.position[1])
    }
}

fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();
    let display = video_subsystem.window("Tutorial 01", 800, 600).resizable().build_glium().unwrap();
    let v1 = Vertex { position: [-0.5, -0.5] };
    let v2 = Vertex { position: [ 0.0,  0.5] };
    let v3 = Vertex { position: [ 0.5, -0.25] };
    let shape = vec![v1, v2, v3];

    let vertex_buffer = VertexBuffer::new(&display, &shape).unwrap();
    let indices = index::NoIndices(index::PrimitiveType::TrianglesList);

    fn create_shaders(display: &SDL2Facade) -> Program {
        let vertex_shader_src = r#"
            #version 130

            in vec2 position;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0);
            }
        "#;

        let fragment_shader_src = r#"
            #version 130

            out vec4 color;

            void main() {
                color = vec4(1.0, 0.0, 0.0, 1.0);
            }
        "#;

        Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap()
    }
    let program = create_shaders(&display);

    let mut running = true;
    let mut event_pump = sdl_context.event_pump().unwrap();

    while running {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 1.0, 1.0);
        target.draw(&vertex_buffer, &indices, &program, &uniforms::EmptyUniforms,
                    &Default::default()).unwrap();
        target.finish().unwrap();

        for event in event_pump.poll_iter() {
            match event {
                Event::Quit { .. } => running = false,
                _ => ()
            }
        }
    }
}

#[cfg(test)]
mod test {
    use super::Vertex;

    #[test]
    fn test_vertex() {
        assert_eq!("(3, 5)", format!("{}", Vertex { position: [3.0, 5.0] }));
    }
}
<|endoftext|>


<commit_before>extern crate irc;

use std::io::{self, BufRead, BufReader};
use std::fs::File;
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use std::collections::HashMap;
use irc::client::data::command::Command;
use irc::client::data::message::Message;
use irc::client::server::{IrcServer, NetIrcServer, Server};
use irc::client::server::utils::ServerExt;
use irc::client::data::kinds::{IrcRead, IrcWrite};

fn join_start_channels<T, U>(server: &IrcServer<T, U>) -> io::Result<()>
        where T: IrcRead, U: IrcWrite {
    let channels = BufReader::new(try!(File::open("channels.txt")));
    for line in channels.lines() {
        try!(server.send_join(&*try!(line)));
    }
    Ok(())
}

fn find_or_spawn<'a, S>(arc_irc_server: &Arc<NetIrcServer>,
                     user_senders: &'a mut HashMap<String, Sender<Message>>,
                     nick: S) -> &'a mut Sender<Message>
        where S: Into<String> {
    let nick = nick.into();
    user_senders.entry(nick).or_insert_with(|| {
        let (tx, rx) = channel();
        let irc_server = arc_irc_server.clone();
        thread::spawn(move || {
            for message in rx.iter() {
                if let Ok(command) = Command::from_message(&message) {
                    irc_server.send(command).unwrap();
                }
            }
        });
        tx
    })
}

fn main() {
    let arc_irc_server = Arc::new(IrcServer::new("config.json").unwrap());
    let server = arc_irc_server.clone();
    server.identify().unwrap();
    join_start_channels(&server).unwrap();
    let mut user_senders = HashMap::new();

    for message in server.iter() {
        let message = message.unwrap();
        if let Ok(command) = Command::from_message(&message) {
            match command {
                Command::PRIVMSG(_, msg) => {
                    if msg.starts_with("#") {
                        if let Some(nick) = message.get_source_nickname() {
                            let user_chan = find_or_spawn(&arc_irc_server,
                                                          &mut user_senders,
                                                          nick);
                            user_chan.send(message.clone()).unwrap();
                        }
                    }
                },
                _ => (),
            }
        }
    }
}
<commit_msg>Avoid clone of message in router<commit_after>extern crate irc;

use std::io::{self, BufRead, BufReader};
use std::fs::File;
use std::thread;
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use std::collections::HashMap;
use irc::client::data::command::Command;
use irc::client::data::message::Message;
use irc::client::server::{IrcServer, NetIrcServer, Server};
use irc::client::server::utils::ServerExt;
use irc::client::data::kinds::{IrcRead, IrcWrite};

fn join_start_channels<T, U>(server: &IrcServer<T, U>) -> io::Result<()>
        where T: IrcRead, U: IrcWrite {
    let channels = BufReader::new(try!(File::open("channels.txt")));
    for line in channels.lines() {
        try!(server.send_join(&*try!(line)));
    }
    Ok(())
}

fn find_or_spawn<'a, S>(arc_irc_server: &Arc<NetIrcServer>,
                     user_senders: &'a mut HashMap<String, Sender<Message>>,
                     nick: S) -> &'a mut Sender<Message>
        where S: Into<String> {
    let nick = nick.into();
    user_senders.entry(nick).or_insert_with(|| {
        let (tx, rx) = channel();
        let irc_server = arc_irc_server.clone();
        thread::spawn(move || {
            for message in rx.iter() {
                if let Ok(command) = Command::from_message(&message) {
                    irc_server.send(command).unwrap();
                }
            }
        });
        tx
    })
}

fn main() {
    let arc_irc_server = Arc::new(IrcServer::new("config.json").unwrap());
    let server = arc_irc_server.clone();
    server.identify().unwrap();
    join_start_channels(&server).unwrap();
    let mut user_senders = HashMap::new();

    for message in server.iter() {
        let message = message.unwrap();
        if let Ok(command) = Command::from_message(&message) {
            match command {
                Command::PRIVMSG(_, msg) => {
                    if msg.starts_with("#") {
                        if let Some(chan) = message.get_source_nickname()
                                .map(|nick| find_or_spawn(&arc_irc_server,
                                                          &mut user_senders,
                                                          nick)) {
                            chan.send(message).unwrap();
                        }
                    }
                },
                _ => (),
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate getopts;

use getopts::Options;
use std::env;
use std::str;

fn print_usage(program: &str, opts: Options) {
	let brief = format!("Usage: {} OUTPUT_DIR [options]", program);
	print!("{}", opts.usage(&brief));
}

fn main() {
	// Define args
	let args: Vec<String> = env::args().collect();
	let program = args[0].clone();

	let mut opts = Options::new();
	opts.optflag("h", "help", "Display the help text");
	opts.optopt("w", "width", "Provide a width for the grid", "WIDTH");
	opts.optopt("t", "height", "Provide a height for the grid", "HEIGHT");
	opts.optopt("n", "interations", "Provide the number of iterations to run",
		"ITERATIONS");

	// Parse args
	let matches = match opts.parse(&args[1..]) {
		Ok(m) => { m }
		Err(f) => { panic!(f.to_string()) }
	};
	// Check for help request
	if matches.opt_present("h") {
		print_usage(&program, opts);
		return;
	}
	// Parse number of iterations to run
	let iterations_str = match matches.opt_str("n") {
		Some(s) => { s }
		None => {
			println!("Required parameter 'iterations' missing");
			print_usage(&program, opts);
			return;
		}
	};
	let iterations = match iterations_str.parse::<u32>() {
		Ok(i) => i,
		Err(err) => {
			println!("Invalid value for iterations (flag 'i'):\n{}\n", err);
			return;
		}
	};
	// Parse output dir
	let output = if !matches.free.is_empty() {
		matches.free[0].clone()
	} else {
		println!("Required argument OUTPUT_DIR missing\n");
	    print_usage(&program, opts);
	    return;
	};
	// TODO: Determine if using input file or random grid
	// Handle random starting grid
	// Parse height and width of grid
	let height_str = match matches.opt_str("t") {
	    Some(expr) => expr,
	    None => String::from("None"),
	};
	let height: u32 = match height_str.parse::<u32>() {
		Ok(h) => h,
		Err(err) => {
			println!("Invalid value for height (flag 't'):\n{}\n", err);
			return;
		}
	};
	let width_str = match matches.opt_str("w") {
		Some(expr) => expr,
		None => String::from("None"),
	};
	let width: u32 = match width_str.parse::<u32>() {
		Ok(w) => w,
		Err(err) => {
			println!("Invalid value for width (flag 'w'):\n{}\n", err);
			return;
		}
	};
	// Output parsed values
	println!("Output directory set to: {}", output);
	println!("Iterations set to: {}", iterations);
	println!("Grid height set to: {}", height);
	println!("Grid width set to: {}", width);
	// TODO: Generation random grid
	// TODO: Run simulation
}
<commit_msg>Added CellState enum and created 2D vect sized from width and height.<commit_after>extern crate getopts;

use getopts::Options;
use std::env;
use std::str;

fn print_usage(program: &str, opts: Options) {
	let brief = format!("Usage: {} OUTPUT_DIR [options]", program);
	print!("{}", opts.usage(&brief));
}

#[derive(Clone)]
enum CellState
{
	Dead,
	Alive
}

fn main() {
	// Define args
	let args: Vec<String> = env::args().collect();
	let program = args[0].clone();

	let mut opts = Options::new();
	opts.optflag("h", "help", "Display the help text");
	opts.optopt("w", "width", "Provide a width for the grid", "WIDTH");
	opts.optopt("t", "height", "Provide a height for the grid", "HEIGHT");
	opts.optopt("n", "interations", "Provide the number of iterations to run",
		"ITERATIONS");

	// Parse args
	let matches = match opts.parse(&args[1..]) {
		Ok(m) => { m }
		Err(f) => { panic!(f.to_string()) }
	};
	// Check for help request
	if matches.opt_present("h") {
		print_usage(&program, opts);
		return;
	}
	// Parse number of iterations to run
	let iterations_str = match matches.opt_str("n") {
		Some(s) => { s }
		None => {
			println!("Required parameter 'iterations' missing");
			print_usage(&program, opts);
			return;
		}
	};
	let iterations = match iterations_str.parse::<u32>() {
		Ok(i) => i,
		Err(err) => {
			println!("Invalid value for iterations (flag 'i'):\n{}\n", err);
			return;
		}
	};
	// Parse output dir
	let output = if !matches.free.is_empty() {
		matches.free[0].clone()
	} else {
		println!("Required argument OUTPUT_DIR missing\n");
	    print_usage(&program, opts);
	    return;
	};
	// TODO: Determine if using input file or random grid
	// Handle random starting grid
	// Parse height and width of grid
	let height_str = match matches.opt_str("t") {
	    Some(expr) => expr,
	    None => String::from("None"),
	};
	let height: usize = match height_str.parse::<usize>() {
		Ok(h) => h,
		Err(err) => {
			println!("Invalid value for height (flag 't'):\n{}\n", err);
			return;
		}
	};
	let width_str = match matches.opt_str("w") {
		Some(expr) => expr,
		None => String::from("None"),
	};
	let width: usize = match width_str.parse::<usize>() {
		Ok(w) => w,
		Err(err) => {
			println!("Invalid value for width (flag 'w'):\n{}\n", err);
			return;
		}
	};
	// Generate grid
	let mut grid = vec![vec![CellState::Dead; width]; height];
	// Output parsed values
	println!("Output directory set to: {}", output);
	println!("Iterations set to: {}", iterations);
	println!("Grid height set to: {}", height);
	println!("Grid width set to: {}", width);
	// TODO: Generation random grid
	// TODO: Run simulation
}
<|endoftext|>


<commit_before>#![feature(inclusive_range_syntax, iterator_step_by, range_contains, try_from)]
#![recursion_limit = "1024"]

extern crate alphred;
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate url;

mod dark_sky;
mod errors;
mod forecast;
mod geocode;
mod location;
mod precipitation;
mod sparkline;
mod theme;

use std::env;

use errors::*;
use theme::Theme;

quick_main!(|| {
    let dark_sky_api_key = env::var("DARK_SKY_API_KEY")?;
    let location = location()?;
    let theme = if env::var("LIGHT_ICONS") == Ok("true".into()) {
        Theme::Light
    } else {
        Theme::Dark
    };
    let units = env::var("FORECAST_UNITS")
        .map(|units| match units.as_str() {
            "ca" => forecast::Units::Ca,
            "uk2" => forecast::Units::Uk2,
            "us" => forecast::Units::Us,
            "si" => forecast::Units::Si,
            _ => forecast::Units::Auto,
        })
        .unwrap_or_else(|_| forecast::Units::Auto);

    let dark_sky = dark_sky::DarkSky {
        dark_sky_api_key,
        location,
        theme,
        units,
    };

    dark_sky.run()
});

#[derive(Debug, Deserialize)]
struct IPInfo {
    #[serde(rename = "loc")] coord: location::Coordinate,
    city: String,
    region: String,
}

fn location() -> Result<location::Location> {
    let args: Vec<_> = env::args().skip(1).collect();
    let query = args.join(" ");

    let location = env::var("DEFAULT_LAT_LONG").ok().and_then(|lat_long| {
        let mut split = lat_long.split(',');
        split
            .next()
            .and_then(|lat| lat.parse::<f64>().ok())
            .and_then(|lat| {
                split
                    .next()
                    .and_then(|long| long.parse::<f64>().ok())
                    .map(|long| location::Coordinate(lat, long))
            })
            .map(|coord| {
                let description = env::var("DEFAULT_LOCATION").unwrap_or_else(|_| "".into());
                location::Location { description, coord }
            })
    });

    match (query, location) {
        (ref query, _) if !query.is_empty() => {
            let api_key = env::var("GOOGLE_API_KEY")?;
            let geocoder = geocode::Geocoder::new(&api_key);
            geocoder.geocode(query)
        }
        (_, Some(ref location)) => Ok(location.clone()),
        _ => {
            let ip_info: IPInfo = reqwest::get("https://ipinfo.io/json")?.json()?;
            let description = format!("{}, {}", ip_info.city, ip_info.region);
            let coord = ip_info.coord;
            Ok(location::Location { description, coord })
        }
    }
}
<commit_msg>Error out on invalid `DEFAULT_LAT_LONG`<commit_after>#![feature(inclusive_range_syntax, iterator_step_by, range_contains, try_from)]
#![recursion_limit = "1024"]

extern crate alphred;
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
extern crate url;

mod dark_sky;
mod errors;
mod forecast;
mod geocode;
mod location;
mod precipitation;
mod sparkline;
mod theme;

use std::env;

use errors::*;
use theme::Theme;

quick_main!(|| {
    let dark_sky_api_key = env::var("DARK_SKY_API_KEY")?;
    let location = location()?;
    let theme = if env::var("LIGHT_ICONS") == Ok("true".into()) {
        Theme::Light
    } else {
        Theme::Dark
    };
    let units = env::var("FORECAST_UNITS")
        .map(|units| match units.as_str() {
            "ca" => forecast::Units::Ca,
            "uk2" => forecast::Units::Uk2,
            "us" => forecast::Units::Us,
            "si" => forecast::Units::Si,
            _ => forecast::Units::Auto,
        })
        .unwrap_or_else(|_| forecast::Units::Auto);

    let dark_sky = dark_sky::DarkSky {
        dark_sky_api_key,
        location,
        theme,
        units,
    };

    dark_sky.run()
});

#[derive(Debug, Deserialize)]
struct IPInfo {
    #[serde(rename = "loc")] coord: location::Coordinate,
    city: String,
    region: String,
}

fn location() -> Result<location::Location> {
    let args: Vec<_> = env::args().skip(1).collect();
    let query = args.join(" ");

    let location = match env::var("DEFAULT_LAT_LONG") {
        Ok(lat_long) => {
            let description = env::var("DEFAULT_LOCATION").unwrap_or_else(|_| "".into());
            let mut split = lat_long.split(',');
            let coord = match (split.next(), split.next()) {
                (Some(lat), Some(long)) => {
                    let lat = lat.parse::<f64>().chain_err(|| "invalid DEFAULT_LAT_LONG")?;
                    let long = long.parse::<f64>().chain_err(|| "invalid DEFAULT_LAT_LONG")?;
                    location::Coordinate(lat, long)
                }
                _ => bail!(""),
            };
            let location = location::Location { description, coord };
            Some(location)
        }
        Err(_) => None,
    };

    match (query, location) {
        (ref query, _) if !query.is_empty() => {
            let api_key = env::var("GOOGLE_API_KEY")?;
            let geocoder = geocode::Geocoder::new(&api_key);
            geocoder.geocode(query)
        }
        (_, Some(ref location)) => Ok(location.clone()),
        _ => {
            let ip_info: IPInfo = reqwest::get("https://ipinfo.io/json")?.json()?;
            let description = format!("{}, {}", ip_info.city, ip_info.region);
            let coord = ip_info.coord;
            Ok(location::Location { description, coord })
        }
    }
}
<|endoftext|>


<commit_before>extern crate ncurses;
extern crate voodoo;

use ncurses::*;
use voodoo::window::WindowLike;

const level: [&'static str; 22] = [
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "   o....                                                  ",
    "   o....                                                  ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
];

fn main() {
    use voodoo::terminal::{Mode, Terminal};
    use voodoo::window::Window;

    let locale = LcCategory::all;
    setlocale(locale, "en_US.UTF-8");

    let term = Terminal::new();
    term.cbreak(Mode::Enabled).unwrap();
    term.echo(Mode::Disabled).unwrap();

    keypad(stdscr(), true);
    curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);

    mousemask((ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION) as u64, None);

    start_color();
    init_pair(1, COLOR_BLACK, COLOR_WHITE);

    wbkgd(stdscr(), 1);

    refresh();

    let mut info = Window::new(0, 0, 20, 24);
    let mut map = Window::new(20, 0, 60, 24);
    info.box_(0, 0);
    map.box_(0, 0);

    for (y, line) in level.iter().enumerate() {
        let y = (y + 1) as i32;
        for (x, tile) in line.chars().enumerate() {
            let x = (x + 1) as i32;
            match tile {
                '.' => map.put_at(y, x, '.'), // '·'
                'o' => map.put_at(y, x, 'O'),
                _ => {}
            }
        }
    }

    info.refresh();
    map.refresh();

    print!("\x1B[?1003h\n"); // Makes the terminal report mouse movement events

    loop {
        match voodoo::poll_event() {
            Some(voodoo::Event::Mouse) => {
                let event = get_mouse_state();
                map.put_at(event.y, event.x - 20, 'y');
                map.refresh();
            }

            Some(voodoo::Event::Char('\n')) => {
                break;
            }

            _ => {}
        }
    }

    print!("\x1B[?1003l\n"); // Disable mouse movement events, as l = low

    endwin();
}

fn get_mouse_state() -> MEVENT {
    let mut event = MEVENT { id: 0, x: 0, y: 0, z: 0, bstate: 0 };
    let res = getmouse(&mut event);
    if res != 0 {
        panic!("getmouse");
    }
    event
}
<commit_msg>feat: basic map mouse highlight<commit_after>extern crate ncurses;
extern crate voodoo;

use ncurses::*;
use voodoo::terminal::{Mode, Terminal};
use voodoo::window::{DisplayChar, Window, WindowLike};

const LEVEL_DESCR: [&'static str; 22] = [
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "   o....                                                  ",
    "   o....                                                  ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
    "                                                          ",
];

struct Level {
    layout: Vec<String>,
}

impl Level {
    fn display_for(&self, y: usize, x: usize) -> Option<DisplayChar> {
        Self::convert(self.layout[y].chars().nth(x).unwrap())
    }

    fn convert(c: char) -> Option<DisplayChar> {
        match c {
            '.' => Some(Into::<DisplayChar>::into('.').dim()), // '·'
            'o' => Some(Into::<DisplayChar>::into('O')),
            _ => None,
        }
    }

    fn display(&self, map: &mut Window) {
        for (y, line) in self.layout.iter().enumerate() {
            let y = y + 1;
            for (x, tile) in line.chars().enumerate() {
                let x = x + 1;
                match tile {
                    '.' => map.put_at(y as i32, x as i32, Into::<DisplayChar>::into('.').dim()), // '·'
                    'o' => map.put_at(y as i32, x as i32, 'O'),
                    _ => {}
                }
            }
        }
    }
}

fn main() {
    let mut layout = Vec::new();
    for s in LEVEL_DESCR.iter() {
        layout.push(s.to_string());
    }
    let level = Level {
        layout: layout,
    };

    let locale = LcCategory::all;
    setlocale(locale, "en_US.UTF-8");

    let term = Terminal::new();
    term.cbreak(Mode::Enabled).unwrap();
    term.echo(Mode::Disabled).unwrap();

    keypad(stdscr(), true);
    curs_set(CURSOR_VISIBILITY::CURSOR_INVISIBLE);

    mousemask((ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION) as u64, None);

    start_color();
    init_pair(1, COLOR_BLACK, COLOR_WHITE);

    wbkgd(stdscr(), 1);

    refresh();

    let mut info = Window::new(0, 0, 20, 24);
    let mut map = Window::new(20, 0, 60, 24);
    info.box_(0, 0);
    map.box_(0, 0);

    level.display(&mut map);

    info.refresh();
    map.refresh();

    print!("\x1B[?1003h\n"); // Makes the terminal report mouse movement events

    loop {
        match voodoo::poll_event() {
            Some(voodoo::Event::Mouse) => {
                let event = get_mouse_state();
                let x = event.x - 20;
                let y = event.y - 1;
                if y <= 0 || y >= 59 || x <= 0 || x >= 19 {

                }
                else if let Some(c) = level.display_for(event.y as usize - 1, event.x as usize - 21) {
                    map.put_at(event.y, event.x - 20, c.bold());
                    map.refresh();
                }
            }

            Some(voodoo::Event::Char('\n')) => {
                break;
            }

            _ => {}
        }
    }

    print!("\x1B[?1003l\n"); // Disable mouse movement events, as l = low

    endwin();
}

fn get_mouse_state() -> MEVENT {
    let mut event = MEVENT { id: 0, x: 0, y: 0, z: 0, bstate: 0 };
    let res = getmouse(&mut event);
    if res != 0 {
        panic!("getmouse");
    }
    event
}
<|endoftext|>


<commit_before>// Copyright 2016 Alex Crawford
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate clap;
extern crate hyper;
extern crate pulldown_cmark;
extern crate url;
extern crate walkdir;

use clap::{Arg, App};
use hyper::client::Client;
use hyper::header::UserAgent;
use hyper::status::StatusCode;
use pulldown_cmark::{Event, OPTION_ENABLE_TABLES, Parser, Tag};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use std::process::exit;
use url::{ParseError, Url};
use walkdir::WalkDir;

macro_rules! fail {
    ($($print:expr),+) => {
        {
            let _ = writeln!(&mut std::io::stderr(), $($print),+);
            exit(2);
        }
    };
}

macro_rules! print_issue {
    ($flag:expr, $($print:expr),+) => {
        {
            println!($($print),+);
            $flag = true;
        }
    };
}

struct State<'a> {
    skip_http: bool,
    code_block: bool,
    last_text: String,
    directory: &'a Path,
}

enum LinkError {
    PathAbsolute,
    PathNonExistant,
    HttpStatus(StatusCode),
    HttpError(hyper::error::Error),
    UrlMalformed(ParseError),
}

fn main() {
    let matches = App::new("Marker")
        .version(crate_version!())
        .arg(Arg::with_name("root")
            .short("r")
            .long("root")
            .help("The path to the root of the documentation to be checked")
            .takes_value(true))
        .arg(Arg::with_name("skip-http")
            .long("skip-http")
            .help("Skip validation of HTTP[S] URLs"))
        .get_matches();

    let skip_http = matches.is_present("skip-http");
    let root = Path::new(matches.value_of("root").unwrap_or("."));
    let mut links = HashMap::new();
    let mut found_issue = false;

    for entry in WalkDir::new(root).into_iter().filter_map(|entry| {
        let entry = entry.unwrap_or_else(|err| {
            fail!("Failed to walk directory: {}", err);
        });
        if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("md")) {
            Some(entry)
        } else {
            None
        }
    }) {
        let contents = {
            let mut file = File::open(entry.path()).unwrap_or_else(|err| {
                fail!("Failed to open file ({}): {}", entry.path().display(), err);
            });
            let mut text = String::new();
            if let Err(err) = file.read_to_string(&mut text) {
                fail!("Failed to read file ({}): {}", entry.path().display(), err);
            };
            text
        };

        let newlines = contents.match_indices('\n').map(|(i, _)| i).collect::<Vec<_>>();

        let mut state = State {
            skip_http: skip_http,
            code_block: false,
            last_text: String::new(),
            directory: entry.path().parent().expect("non-root path"),
        };
        let mut parser = Parser::new_ext(&contents, OPTION_ENABLE_TABLES);
        while let Some(event) = parser.next() {
            let line = newlines.iter().take_while(|i| i < &&parser.get_offset()).count() + 1;
            match event {
                Event::Text(ref text) => {
                    state.last_text = text.to_string();
                    if let Some(reference) = try_reference(&state, text) {
                        print_issue!(found_issue,
                                     "Found broken reference ({}) in {}:{}",
                                     reference,
                                     entry.path().display(),
                                     line)
                    }
                }
                Event::End(Tag::Link(dest, _)) => {
                    match check_link(&mut state, &mut links, &dest) {
                        Ok(()) => {}
                        Err(LinkError::PathAbsolute) => {
                            print_issue!(found_issue,
                                         "Found absolute path    ({} -> {}) at {}:{}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line)
                        }
                        Err(LinkError::PathNonExistant) => {
                            print_issue!(found_issue,
                                         "Found broken path      ({} -> {}) at {}:{}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line)
                        }
                        Err(LinkError::HttpStatus(status)) => {
                            print_issue!(found_issue,
                                         "Found broken url       ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         status)
                        }
                        Err(LinkError::HttpError(err)) => {
                            print_issue!(found_issue,
                                         "HTTP failure           ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         err);
                        }
                        Err(LinkError::UrlMalformed(err)) => {
                            print_issue!(found_issue,
                                         "Found malformed URL    ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         err);
                        }
                    }
                }
                Event::Start(Tag::Code) |
                Event::Start(Tag::CodeBlock(_)) => state.code_block = true,
                Event::End(Tag::Code) |
                Event::End(Tag::CodeBlock(_)) => state.code_block = false,
                _ => {}
            }
        }
    }

    if found_issue {
        exit(1)
    }
}

fn try_reference<'a>(state: &State, text: &'a str) -> Option<&'a str> {
    if !state.code_block && text.chars().next() == Some('[') && text.chars().last() == Some(']') {
        Some(&text[1..(text.len() - 1)])
    } else {
        None
    }
}

fn check_link(state: &mut State,
              links: &mut HashMap<Url, StatusCode>,
              dest: &str)
              -> Result<(), LinkError> {
    match (Url::parse(&dest), state.skip_http) {
        (Ok(url), false) => check_url(links, url),
        (Ok(_), true) => Ok(()),
        (Err(ParseError::RelativeUrlWithoutBase), _) => check_path(state, dest),
        (Err(err), _) => Err(LinkError::UrlMalformed(err)),
    }
}

fn check_url(links: &mut HashMap<Url, StatusCode>, url: Url) -> Result<(), LinkError> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Ok(());
    }

    let client = Client::new();
    let agent = UserAgent(format!("marker/{}", crate_version!()));

    let status = if let Some(status) = links.remove(&url) {
        status
    } else {
        let res = client.head(url.clone()).header(agent.clone()).send().and_then(|resp| {
            if resp.status == StatusCode::MethodNotAllowed {
                client.get(url.clone()).header(agent.clone()).send()
            } else {
                Ok(resp)
            }
        });
        match res {
            Ok(resp) => resp.status,
            Err(err) => return Err(LinkError::HttpError(err)),
        }
    };
    links.insert(url, status);
    match status {
        StatusCode::Ok => Ok(()),
        status => Err(LinkError::HttpStatus(status)),
    }
}

fn check_path(state: &mut State, path: &str) -> Result<(), LinkError> {
    let path = Path::new(OsStr::new(path.split('#').next().expect("string")));
    if path.is_absolute() {
        Err(LinkError::PathAbsolute)
    } else if !state.directory.join(path).exists() {
        Err(LinkError::PathNonExistant)
    } else {
        Ok(())
    }
}
<commit_msg>main: loosen restriction on reference links<commit_after>// Copyright 2016 Alex Crawford
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[macro_use]
extern crate clap;
extern crate hyper;
extern crate pulldown_cmark;
extern crate url;
extern crate walkdir;

use clap::{Arg, App};
use hyper::client::Client;
use hyper::header::UserAgent;
use hyper::status::StatusCode;
use pulldown_cmark::{Event, OPTION_ENABLE_TABLES, Parser, Tag};
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use std::process::exit;
use url::{ParseError, Url};
use walkdir::WalkDir;

macro_rules! fail {
    ($($print:expr),+) => {
        {
            let _ = writeln!(&mut std::io::stderr(), $($print),+);
            exit(2);
        }
    };
}

macro_rules! print_issue {
    ($flag:expr, $($print:expr),+) => {
        {
            println!($($print),+);
            $flag = true;
        }
    };
}

struct State<'a> {
    skip_http: bool,
    code_block: bool,
    last_text: String,
    directory: &'a Path,
}

enum LinkError {
    PathAbsolute,
    PathNonExistant,
    HttpStatus(StatusCode),
    HttpError(hyper::error::Error),
    UrlMalformed(ParseError),
}

fn main() {
    let matches = App::new("Marker")
        .version(crate_version!())
        .arg(Arg::with_name("root")
            .short("r")
            .long("root")
            .help("The path to the root of the documentation to be checked")
            .takes_value(true))
        .arg(Arg::with_name("skip-http")
            .long("skip-http")
            .help("Skip validation of HTTP[S] URLs"))
        .get_matches();

    let skip_http = matches.is_present("skip-http");
    let root = Path::new(matches.value_of("root").unwrap_or("."));
    let mut links = HashMap::new();
    let mut found_issue = false;

    for entry in WalkDir::new(root).into_iter().filter_map(|entry| {
        let entry = entry.unwrap_or_else(|err| {
            fail!("Failed to walk directory: {}", err);
        });
        if entry.file_type().is_file() && entry.path().extension() == Some(OsStr::new("md")) {
            Some(entry)
        } else {
            None
        }
    }) {
        let contents = {
            let mut file = File::open(entry.path()).unwrap_or_else(|err| {
                fail!("Failed to open file ({}): {}", entry.path().display(), err);
            });
            let mut text = String::new();
            if let Err(err) = file.read_to_string(&mut text) {
                fail!("Failed to read file ({}): {}", entry.path().display(), err);
            };
            text
        };

        let newlines = contents.match_indices('\n').map(|(i, _)| i).collect::<Vec<_>>();

        let mut state = State {
            skip_http: skip_http,
            code_block: false,
            last_text: String::new(),
            directory: entry.path().parent().expect("non-root path"),
        };
        let mut parser = Parser::new_ext(&contents, OPTION_ENABLE_TABLES);
        while let Some(event) = parser.next() {
            let line = newlines.iter().take_while(|i| i < &&parser.get_offset()).count() + 1;
            match event {
                Event::Text(ref text) => {
                    state.last_text = text.to_string();
                    if let Some(reference) = try_reference(&state, text) {
                        print_issue!(found_issue,
                                     "Found broken reference ({}) in {}:{}",
                                     reference,
                                     entry.path().display(),
                                     line)
                    }
                }
                Event::End(Tag::Link(dest, _)) => {
                    match check_link(&mut state, &mut links, &dest) {
                        Ok(()) => {}
                        Err(LinkError::PathAbsolute) => {
                            print_issue!(found_issue,
                                         "Found absolute path    ({} -> {}) at {}:{}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line)
                        }
                        Err(LinkError::PathNonExistant) => {
                            print_issue!(found_issue,
                                         "Found broken path      ({} -> {}) at {}:{}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line)
                        }
                        Err(LinkError::HttpStatus(status)) => {
                            print_issue!(found_issue,
                                         "Found broken url       ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         status)
                        }
                        Err(LinkError::HttpError(err)) => {
                            print_issue!(found_issue,
                                         "HTTP failure           ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         err);
                        }
                        Err(LinkError::UrlMalformed(err)) => {
                            print_issue!(found_issue,
                                         "Found malformed URL    ({} -> {}) at {}:{} : {}",
                                         state.last_text,
                                         dest,
                                         entry.path().display(),
                                         line,
                                         err);
                        }
                    }
                }
                Event::Start(Tag::Code) |
                Event::Start(Tag::CodeBlock(_)) => state.code_block = true,
                Event::End(Tag::Code) |
                Event::End(Tag::CodeBlock(_)) => state.code_block = false,
                _ => {}
            }
        }
    }

    if found_issue {
        exit(1)
    }
}

fn try_reference<'a>(state: &State, text: &'a str) -> Option<&'a str> {
    if state.code_block || text.chars().next() != Some('[') {
        return None;
    }

    if let Some(pos) = text.find(']') {
        Some(&text[1..pos])
    } else {
        None
    }
}

fn check_link(state: &mut State,
              links: &mut HashMap<Url, StatusCode>,
              dest: &str)
              -> Result<(), LinkError> {
    match (Url::parse(&dest), state.skip_http) {
        (Ok(url), false) => check_url(links, url),
        (Ok(_), true) => Ok(()),
        (Err(ParseError::RelativeUrlWithoutBase), _) => check_path(state, dest),
        (Err(err), _) => Err(LinkError::UrlMalformed(err)),
    }
}

fn check_url(links: &mut HashMap<Url, StatusCode>, url: Url) -> Result<(), LinkError> {
    if url.scheme() != "http" && url.scheme() != "https" {
        return Ok(());
    }

    let client = Client::new();
    let agent = UserAgent(format!("marker/{}", crate_version!()));

    let status = if let Some(status) = links.remove(&url) {
        status
    } else {
        let res = client.head(url.clone()).header(agent.clone()).send().and_then(|resp| {
            if resp.status == StatusCode::MethodNotAllowed {
                client.get(url.clone()).header(agent.clone()).send()
            } else {
                Ok(resp)
            }
        });
        match res {
            Ok(resp) => resp.status,
            Err(err) => return Err(LinkError::HttpError(err)),
        }
    };
    links.insert(url, status);
    match status {
        StatusCode::Ok => Ok(()),
        status => Err(LinkError::HttpStatus(status)),
    }
}

fn check_path(state: &mut State, path: &str) -> Result<(), LinkError> {
    let path = Path::new(OsStr::new(path.split('#').next().expect("string")));
    if path.is_absolute() {
        Err(LinkError::PathAbsolute)
    } else if !state.directory.join(path).exists() {
        Err(LinkError::PathNonExistant)
    } else {
        Ok(())
    }
}
<|endoftext|>


<commit_before>// Separated compile units
extern crate psocrypto;
extern crate psomsg;
extern crate psodata;
extern crate psodb_common;
extern crate psodb_sqlite;

extern crate rand;
extern crate byteorder;
extern crate encoding;
extern crate typenum;
#[macro_use] extern crate log;
extern crate crc;
extern crate docopt;
extern crate mio;
extern crate rustc_serialize;
extern crate staticvec;

pub mod patch;
pub mod data;
pub mod game;
pub mod login;
pub mod bb;
pub mod ship;
pub mod util;
pub mod args;
pub mod loop_handler;
pub mod services;

use ::args::USAGE_STRING;
use ::args::Args;

use docopt::Docopt;

use mio::EventLoop;

use ::loop_handler::LoopHandler;
use ::patch::PatchService;
use ::data::DataService;

fn main() {
    let args: Args = Docopt::new(USAGE_STRING)
        .and_then(|o| o.decode())
        .unwrap_or_else(|e| e.exit());

    if args.flag_version {
        println!("idola 0.1.0");
        return
    }

    // TODO load the config

    // 1. Create EventLoop.
    // 2. Spin up service threads to get handles.
    // 3. Create LoopHandler and register services.
    // 4. Run event loop.
    let mut event_loop = EventLoop::new().expect("Could not create event loop");

    let mut services = Vec::new();
    services.push(PatchService::spawn(&"127.0.0.1:11000".parse().unwrap(), event_loop.channel()));
    services.push(DataService::spawn(&"127.0.0.1:11001".parse().unwrap(), event_loop.channel()));

    let mut loop_handler = LoopHandler::new(services, &mut event_loop);

    event_loop.run(&mut loop_handler).unwrap();
}
<commit_msg>Enable env_logger.<commit_after>// Separated compile units
extern crate psocrypto;
extern crate psomsg;
extern crate psodata;
extern crate psodb_common;
extern crate psodb_sqlite;

extern crate rand;
extern crate byteorder;
extern crate encoding;
extern crate typenum;
#[macro_use] extern crate log;
extern crate crc;
extern crate docopt;
extern crate mio;
extern crate rustc_serialize;
extern crate staticvec;
extern crate env_logger;

pub mod patch;
pub mod data;
pub mod game;
pub mod login;
pub mod bb;
pub mod ship;
pub mod util;
pub mod args;
pub mod loop_handler;
pub mod services;

use ::args::USAGE_STRING;
use ::args::Args;

use docopt::Docopt;

use mio::EventLoop;

use ::loop_handler::LoopHandler;
use ::patch::PatchService;
use ::data::DataService;

fn main() {
    env_logger::init().expect("env_logger failed to initialize");

    let args: Args = Docopt::new(USAGE_STRING)
        .and_then(|o| o.decode())
        .unwrap_or_else(|e| e.exit());

    if args.flag_version {
        println!("idola 0.1.0");
        return
    }

    // TODO load the config

    // 1. Create EventLoop.
    // 2. Spin up service threads to get handles.
    // 3. Create LoopHandler and register services.
    // 4. Run event loop.
    let mut event_loop = EventLoop::new().expect("Could not create event loop");

    let mut services = Vec::new();
    services.push(PatchService::spawn(&"127.0.0.1:11000".parse().unwrap(), event_loop.channel()));
    services.push(DataService::spawn(&"127.0.0.1:11001".parse().unwrap(), event_loop.channel()));

    let mut loop_handler = LoopHandler::new(services, &mut event_loop);

    event_loop.run(&mut loop_handler).unwrap();
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate rocket;
extern crate rocket_contrib;

#[macro_use]
extern crate serde_derive;
extern crate serde_json;

extern crate file;
extern crate rand;

use rocket_contrib::JSON;

use std::collections::HashSet;

use rand::Rng;

#[derive(Serialize, Debug, Clone, Copy)]
enum Sex {
    Male,
    Female
}

impl rand::Rand for Sex {
    fn rand<R: Rng>(rng: &mut R) -> Self {
        let variants = [Sex::Male, Sex::Female];
        *rng.choose(&variants).unwrap()
    }
}

#[derive(Serialize, Debug)]
struct Person {
    sex: Sex,
    first_name: String,
    second_name: String,
    last_name: String
}

#[derive(Debug)]
struct NamePool {
    female: Vec<String>,
    male: Vec<String>,
    surname: Vec<String>,
}

impl NamePool {
    fn random_name(&self) -> Person {
        fn random_value(vec: &Vec<String>) -> &String {
            // todo unwrap_or
            rand::thread_rng().choose(vec).unwrap()
        }

        let sex: Sex = rand::random();
        let first_name = match sex {
            Sex::Male => random_value(&self.male),
            Sex::Female => random_value(&self.female)
        };

        let person = Person {
            sex: sex,
            first_name: first_name.to_string(),
            second_name: random_value(&self.male).to_string(),
            last_name: random_value(&self.surname).to_string()
        };

        println!("{:?}", person);
        person
    }
}

#[get("/")]
fn index(pool: rocket::State<NamePool>) -> JSON<Person> {
    let person = pool.random_name();
    JSON(person)
}

fn load_name_pool() -> NamePool {
    let female_names = merge_names(&[
        "src/names/female-names-v1-14376.txt",
        "src/names/female-names-v2-16673.txt",
    ]);

    let male_names = merge_names(&[
        "src/names/male-names-v1-14999.txt",
        "src/names/male-names-v2-21904.txt",
    ]);

    let surnames = merge_names(&[
        "src/names/surnames-184624.txt",
    ]);

    NamePool { female: female_names, male: male_names, surname: surnames }
}

fn merge_names(filenames: &[&str]) -> Vec<String> {
    let mut distinct = HashSet::new();
    for filename in filenames {
        let names = load_from_file(filename);
        for item in names {
            distinct.insert(item);
        }
    }

    let mut result = vec![];
    for item in distinct {
        result.push(item);
    }

    result
}

fn load_from_file(filename: &str) -> HashSet<String> {
    let content = Box::new(file::get_text(filename).unwrap_or("".to_string()));
    let mut names = HashSet::new();
    for line in content.as_ref().split_whitespace() {
        names.insert(line.to_string());
    }
    names
}

fn main() {
    let pool = load_name_pool();
    rocket::ignite()
        .manage(pool)
        .mount("/", routes![index]).launch();
}
<commit_msg>Example of another Content-Type.<commit_after>#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate rocket;
extern crate rocket_contrib;

#[macro_use]
extern crate serde_derive;
extern crate serde_json;

extern crate file;
extern crate rand;

use rocket_contrib::JSON;
use rocket::response::content::Content;
use rocket::http::ContentType;

use std::collections::HashSet;
use std::str::FromStr;

use rand::Rng;

#[derive(Serialize, Debug, Clone, Copy)]
enum Sex {
    Male,
    Female
}

impl rand::Rand for Sex {
    fn rand<R: Rng>(rng: &mut R) -> Self {
        let variants = [Sex::Male, Sex::Female];
        *rng.choose(&variants).unwrap()
    }
}

#[derive(Serialize, Debug)]
struct Person {
    sex: Sex,
    first_name: String,
    second_name: String,
    last_name: String
}

#[derive(Debug)]
struct NamePool {
    female: Vec<String>,
    male: Vec<String>,
    surname: Vec<String>,
}

impl NamePool {
    fn random_name(&self) -> Person {
        fn random_value(vec: &Vec<String>) -> &String {
            // todo unwrap_or
            rand::thread_rng().choose(vec).unwrap()
        }

        let sex: Sex = rand::random();
        let first_name = match sex {
            Sex::Male => random_value(&self.male),
            Sex::Female => random_value(&self.female)
        };

        let person = Person {
            sex: sex,
            first_name: first_name.to_string(),
            second_name: random_value(&self.male).to_string(),
            last_name: random_value(&self.surname).to_string()
        };

        println!("{:?}", person);
        person
    }
}

#[get("/")]
fn index(pool: rocket::State<NamePool>) -> JSON<Person> {
    let person = pool.random_name();
    JSON(person)
}

fn json_workaround() -> ContentType {
    ContentType::from_str("application/json; encoding=utf-8").unwrap()
}

#[get("/2")]
fn index2(pool: rocket::State<NamePool>) -> Content<String> {
    let person = pool.random_name();
    let json = serde_json::to_string(&person).unwrap();
    Content(json_workaround(), json)
}

fn load_name_pool() -> NamePool {
    let female_names = merge_names(&[
        "src/names/female-names-v1-14376.txt",
        "src/names/female-names-v2-16673.txt",
    ]);

    let male_names = merge_names(&[
        "src/names/male-names-v1-14999.txt",
        "src/names/male-names-v2-21904.txt",
    ]);

    let surnames = merge_names(&[
        "src/names/surnames-184624.txt",
    ]);

    NamePool { female: female_names, male: male_names, surname: surnames }
}

fn merge_names(filenames: &[&str]) -> Vec<String> {
    let mut distinct = HashSet::new();
    for filename in filenames {
        let names = load_from_file(filename);
        for item in names {
            distinct.insert(item);
        }
    }

    let mut result = vec![];
    for item in distinct {
        result.push(item);
    }

    result
}

fn load_from_file(filename: &str) -> HashSet<String> {
    let content = Box::new(file::get_text(filename).unwrap_or("".to_string()));
    let mut names = HashSet::new();
    for line in content.as_ref().split_whitespace() {
        names.insert(line.to_string());
    }
    names
}

fn main() {
    let pool = load_name_pool();
    rocket::ignite()
        .manage(pool)
        .mount("/", routes![index, index2]).launch();
}
<|endoftext|>


<commit_before>// Unseemly is a "core" typed language with (typed!) macros.
// You shouldn't write code in Unseemly.
// Instead, you should implement your programming language as Unseemly macros.

#![allow(dead_code,non_snake_case,unused_imports,non_upper_case_globals, unused_macros)]
// dead_code and unused_macros are hopefully temporary allowances
// non_snake_case is stylistic, unused_imports is inaccurate because of macros
// non_upper_case_globals is stylistic; I like my thread_local!s lowercase.

// unstable; only for testing
// #![feature(log_syntax,trace_macros)]
// trace_macros!(true);

// unstable; only for testing
// #[macro_use] extern crate log;
#[macro_use] extern crate lazy_static;
extern crate num;
#[macro_use] extern crate custom_derive;
#[macro_use] extern crate mac;
#[macro_use] extern crate quote;
extern crate rustyline;
extern crate regex;

use std::path::Path;
use std::fs::File;
use std::io::Read;

mod macros;

mod name; // should maybe be moved to `util`; `mbe` needs it

mod util;

mod beta;
mod read;
mod ast;

mod earley;
mod parse;

mod form;

mod ast_walk;
mod ty;
mod ty_compare;

mod runtime;

mod core_type_forms;
mod core_forms;

use runtime::reify::Reifiable;

use runtime::core_values;
use std::cell::RefCell;
use util::assoc::Assoc;
use name::{Name, n};
use ty::Ty;
use ast::Ast;
use runtime::eval::{eval, Value};

thread_local! {
    pub static ty_env : RefCell<Assoc<Name, Ty>> = RefCell::new(core_values::core_types());
    pub static val_env : RefCell<Assoc<Name, Value>> = RefCell::new(core_values::core_values());
}

struct ValueCompleter {}

impl rustyline::completion::Completer for ValueCompleter {
    fn complete(&self, line: &str, pos: usize)
            -> Result<(usize, Vec<String>), rustyline::error::ReadlineError> {
        let mut break_chars = std::collections::BTreeSet::new();
        break_chars.extend(vec!['[', '(', '{', ' ', '}', ')',  ']'].iter());
        let mut res = vec![];
        let (start, word_so_far) = rustyline::completion::extract_word(line, pos, &break_chars);
        val_env.with(|vals| {
            let vals = vals.borrow();
            for k in vals.iter_keys() {
                if k.sp().starts_with(word_so_far) { res.push(k.sp()); }
            }
        });
        Ok((start, res))
    }
}

fn main() {
    let arguments : Vec<String> = std::env::args().collect();

    if arguments.len() == 1 {
        let mut rl = rustyline::Editor::<ValueCompleter>::new();
        rl.set_completer(Some(ValueCompleter{}));

        let just_type = regex::Regex::new("^:t (.*)$").unwrap();
        let assign_value = regex::Regex::new("^(\\w+)\\s*:=(.*)$").unwrap();

        print!("\n");
        print!("                 \x1b[1;32mUnseemly\x1b[0m\n");
        print!("   `:t <expr>` to synthesize the type of <expr>.\n");
        print!("   `<name> := <expr>` to bind a name for this session.\n");
        print!("   Tab-completion works on variables, and many Bash-isms work.\n");

        let _ = rl.load_history("/tmp/unseemly_interp_history");
        while let Ok(line) = rl.readline("\x1b[1;36m≫\x1b[0m ") {
            // TODO: count delimiters, and allow line continuation!
            rl.add_history_entry(&line);

            let result_display = if let Some(caps) = just_type.captures(&line) {
                type_unseemly_program(caps.at(1).unwrap()).map(|x| format!("{}", x))
            } else if let Some(caps) = assign_value.captures(&line) {
                let expr = caps.at(2).unwrap();
                let res = eval_unseemly_program(expr);

                if let Ok(ref v) = res {
                    let var = n(caps.at(1).unwrap());
                    let ty = type_unseemly_program(expr).unwrap();
                    ty_env.with(|tys| {
                        val_env.with(|vals| {
                            let new_tys = tys.borrow().set(var, ty).clone();
                            let new_vals = vals.borrow().set(var, v.clone());
                            *tys.borrow_mut() = new_tys;
                            *vals.borrow_mut() = new_vals;
                        })
                    })
                }

                res.map(|x| format!("{}", x))
            } else {
                eval_unseemly_program(&line).map(|x| format!("{}", x))
            };

            match result_display {
                Ok(v) => print!("\x1b[1;32m≉\x1b[0m {}\n", v),
                Err(s) => print!("\x1b[1;31m✘\x1b[0m {}\n", s)
            }
        }
        let _ = rl.save_history("/tmp/unseemly_interp_history").unwrap();
    } else {
        let ref filename = arguments[1];

        let mut raw_input = String::new();
        File::open(&Path::new(filename))
            .expect("Error opening file")
            .read_to_string(&mut raw_input)
            .expect("Error reading file");

        let result = eval_unseemly_program(&raw_input);

        print!("{:?}\n", result);
    }
}

fn type_unseemly_program(program: &str) -> Result<ty::Ty, String> {
    let tokens = read::read_tokens(program);

    let ast = try!(
        parse::parse(&core_forms::outermost_form(), &core_forms::get_core_forms(), &tokens)
            .map_err(|e| e.msg));

    ty_env.with(|types| {
        ty::synth_type(&ast, types.borrow().clone()).map_err(|e| format!("{:?}", e))
    })
}

fn eval_unseemly_program(program: &str) -> Result<runtime::eval::Value, String> {
    let tokens = read::read_tokens(program);

    let ast : ::ast::Ast = try!(
        parse::parse(&core_forms::outermost_form(), &core_forms::get_core_forms(), &tokens)
            .map_err(|e| e.msg));

    let _type = try!(ty_env.with(|types| {
        ty::synth_type(&ast, types.borrow().clone()).map_err(|e| format!("{:?}", e))
    }));

    val_env.with(|vals| {
        runtime::eval::eval(&ast, vals.borrow().clone()).map_err(|_| "???".to_string())
    })
}

#[test]
fn end_to_end_eval() {
    assert_eq!(eval_unseemly_program("(zero? zero)"), Ok(val!(b true)));

    assert_eq!(eval_unseemly_program("(plus one one)"), Ok(val!(i 2)));

    assert_eq!(eval_unseemly_program("(.[x : int  y : int . (plus x y)]. one one)"),
               Ok(val!(i 2)));
}
<commit_msg>Add a saveable prelude.<commit_after>// Unseemly is a "core" typed language with (typed!) macros.
// You shouldn't write code in Unseemly.
// Instead, you should implement your programming language as Unseemly macros.

#![allow(dead_code,non_snake_case,unused_imports,non_upper_case_globals, unused_macros)]
// dead_code and unused_macros are hopefully temporary allowances
// non_snake_case is stylistic, unused_imports is inaccurate because of macros
// non_upper_case_globals is stylistic; I like my thread_local!s lowercase.

// unstable; only for testing
// #![feature(log_syntax,trace_macros)]
// trace_macros!(true);

// unstable; only for testing
// #[macro_use] extern crate log;
#[macro_use] extern crate lazy_static;
extern crate num;
#[macro_use] extern crate custom_derive;
#[macro_use] extern crate mac;
#[macro_use] extern crate quote;
extern crate rustyline;
extern crate regex;

use std::path::Path;
use std::fs::File;
use std::io::Read;

mod macros;

mod name; // should maybe be moved to `util`; `mbe` needs it

mod util;

mod beta;
mod read;
mod ast;

mod earley;
mod parse;

mod form;

mod ast_walk;
mod ty;
mod ty_compare;

mod runtime;

mod core_type_forms;
mod core_forms;

use runtime::reify::Reifiable;

use runtime::core_values;
use std::cell::RefCell;
use util::assoc::Assoc;
use name::{Name, n};
use ty::Ty;
use ast::Ast;
use runtime::eval::{eval, Value};
use std::io::BufRead;

thread_local! {
    pub static ty_env : RefCell<Assoc<Name, Ty>> = RefCell::new(core_values::core_types());
    pub static val_env : RefCell<Assoc<Name, Value>> = RefCell::new(core_values::core_values());
}

struct ValueCompleter {}

impl rustyline::completion::Completer for ValueCompleter {
    fn complete(&self, line: &str, pos: usize)
            -> Result<(usize, Vec<String>), rustyline::error::ReadlineError> {
        let mut break_chars = std::collections::BTreeSet::new();
        break_chars.extend(vec!['[', '(', '{', ' ', '}', ')',  ']'].iter());
        let mut res = vec![];
        let (start, word_so_far) = rustyline::completion::extract_word(line, pos, &break_chars);
        val_env.with(|vals| {
            let vals = vals.borrow();
            for k in vals.iter_keys() {
                if k.sp().starts_with(word_so_far) { res.push(k.sp()); }
            }
        });
        Ok((start, res))
    }
}

fn main() {
    let arguments : Vec<String> = std::env::args().collect();
    let prelude_filename = format!("{}/.unseemly_prelude",
                                   std::env::home_dir().unwrap().display());
    let history_filename = format!("{}/.unseemly_history",
                                   std::env::home_dir().unwrap().display());

    if arguments.len() == 1 {
        let mut rl = rustyline::Editor::<ValueCompleter>::new();
        rl.set_completer(Some(ValueCompleter{}));

        let just_type = regex::Regex::new("^:t (.*)$").unwrap();
        let assign_value = regex::Regex::new("^(\\w+)\\s*:=(.*)$").unwrap();
        let save_value = regex::Regex::new("^:s +(\\w+\\s*:=(.*))$").unwrap();

        print!("\n");
        print!("                  \x1b[1;32mUnseemly\x1b[0m\n");
        print!("    `<name> := <expr>` to bind a name for this session.\n");
        print!("    `:s <name> := <expr>` to save a binding to the prelude for the future.\n");
        print!("    `:t <expr>` to synthesize the type of <expr>.\n");
        print!("    Command history is saved over sessions.\n");
        print!("    Tab-completion works on variables, and many Bash-isms work.\n");

        if let Ok(prelude_file) = File::open(&Path::new(&prelude_filename)) {
            let prelude = std::io::BufReader::new(prelude_file);
            for line in prelude.lines() {
                let line = line.unwrap();
                if let Some(caps) = assign_value.captures(&line) {
                    if let Err(e) = assign_variable(caps.at(1).unwrap(), caps.at(2).unwrap()) {
                        print!("    Error in prelude line: {}\n    {}\n", line, e);
                    }
                }
            }
            print!("    [prelude loaded]\n");
        }

        let _ = rl.load_history(&history_filename);
        while let Ok(line) = rl.readline("\x1b[1;36m≫\x1b[0m ") {
            // TODO: count delimiters, and allow line continuation!
            rl.add_history_entry(&line);

            let result_display = if let Some(caps) = just_type.captures(&line) {
                type_unseemly_program(caps.at(1).unwrap()).map(|x| format!("{}", x))
            } else if let Some(caps) = assign_value.captures(&line) {
                assign_variable(caps.at(1).unwrap(), caps.at(2).unwrap()).map(|x| format!("{}", x))
            } else if let Some(caps) = save_value.captures(&line) {
                match eval_unseemly_program(caps.at(2).unwrap()) {
                    Ok(_) => {
                        use std::io::Write;
                        let mut prel_file = ::std::fs::OpenOptions::new().create(true).append(true)
                            .open(&prelude_filename).unwrap();
                        writeln!(prel_file, "{}", caps.at(1).unwrap()).unwrap();
                        Ok(format!("[saved to {}]", &prelude_filename))
                    }
                    Err(e) => Err(e)
                }
            } else {
                eval_unseemly_program(&line).map(|x| format!("{}", x))
            };

            match result_display {
                Ok(v) => print!("\x1b[1;32m≉\x1b[0m {}\n", v),
                Err(s) => print!("\x1b[1;31m✘\x1b[0m {}\n", s)
            }
        }
        let _ = rl.save_history(&history_filename).unwrap();
    } else {
        let ref filename = arguments[1];

        let mut raw_input = String::new();
        File::open(&Path::new(filename))
            .expect("Error opening file")
            .read_to_string(&mut raw_input)
            .expect("Error reading file");

        let result = eval_unseemly_program(&raw_input);

        print!("{:?}\n", result);
    }
}

fn assign_variable(name: &str, expr: &str) -> Result<Value, String> {
    let res = eval_unseemly_program(expr);

    if let Ok(ref v) = res {
        let ty = type_unseemly_program(expr).unwrap();
        ty_env.with(|tys| {
            val_env.with(|vals| {
                let new_tys = tys.borrow().set(n(name), ty).clone();
                let new_vals = vals.borrow().set(n(name), v.clone());
                *tys.borrow_mut() = new_tys;
                *vals.borrow_mut() = new_vals;
            })
        })
    }
    res
}

fn type_unseemly_program(program: &str) -> Result<ty::Ty, String> {
    let tokens = read::read_tokens(program);

    let ast = try!(
        parse::parse(&core_forms::outermost_form(), &core_forms::get_core_forms(), &tokens)
            .map_err(|e| e.msg));

    ty_env.with(|types| {
        ty::synth_type(&ast, types.borrow().clone()).map_err(|e| format!("{:?}", e))
    })
}

fn eval_unseemly_program(program: &str) -> Result<runtime::eval::Value, String> {
    let tokens = read::read_tokens(program);

    let ast : ::ast::Ast = try!(
        parse::parse(&core_forms::outermost_form(), &core_forms::get_core_forms(), &tokens)
            .map_err(|e| e.msg));

    let _type = try!(ty_env.with(|types| {
        ty::synth_type(&ast, types.borrow().clone()).map_err(|e| format!("{:?}", e))
    }));

    val_env.with(|vals| {
        runtime::eval::eval(&ast, vals.borrow().clone()).map_err(|_| "???".to_string())
    })
}

#[test]
fn end_to_end_eval() {
    assert_eq!(eval_unseemly_program("(zero? zero)"), Ok(val!(b true)));

    assert_eq!(eval_unseemly_program("(plus one one)"), Ok(val!(i 2)));

    assert_eq!(eval_unseemly_program("(.[x : int  y : int . (plus x y)]. one one)"),
               Ok(val!(i 2)));
}
<|endoftext|>


<commit_before>extern crate iron;
extern crate router;
extern crate mount;
extern crate staticfile;
extern crate robots;
extern crate persistent;
extern crate env_logger;

use iron::prelude::*;
use iron::status;
use router::Router;
use staticfile::Static;
use mount::Mount;
use std::path::Path;
use std::any::Any;
use std::sync::{Arc,Mutex};
use std::thread;
use std::time;
use robots::actors::{ActorSystem,Actor,ActorCell,ActorContext,Props,ActorRef,ActorPath};
use persistent::Read;
use iron::typemap::Key;
use std::fmt::{Debug, Display,Formatter,Result};
use gpioaccess::PinProxy;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DirectionProxied {
    In,
    Out,
    High,
    Low,
}

#[derive(Debug)]
pub enum ProxyError {
	MonErreur,
}

impl ::std::error::Error for ProxyError {
	fn description(&self) -> &str {
		"an error"
	}
}

impl Display for ProxyError {
	fn fmt(&self, f: &mut Formatter) -> Result {
		write!(f, "an error")
	}
}

pub type ProxyResult<T> = ::std::result::Result<T, ProxyError>;

//depend on abstractions not concretions lulz
trait PinProxyContract {

	fn new(pin_num: u64) -> Self;
	//FIXME :figure out mapping overloaded Result from gpio library
	fn export(&self) -> ProxyResult<()>;

	fn unexport(&self) ->  ProxyResult<()>;

	fn set_value(&self, value: u8) -> ProxyResult<()>;

	fn set_direction(&self, dir: DirectionProxied) ->  ProxyResult<()>;
}

#[cfg(unix)]
pub mod gpioaccess{

	extern crate sysfs_gpio;
	use sysfs_gpio::{Direction, Pin};
	use super::{PinProxyContract,DirectionProxied,ProxyError,ProxyResult};

	pub struct PinProxy {
		pin : Pin,
	}

	impl PinProxyContract for PinProxy
	{
		fn new(pin_num: u64) -> PinProxy {
			PinProxy{ pin: Pin::new(pin_num) }
		}

		fn export(&self) ->  ProxyResult<()>{
			match self.pin.export()
			{
				Ok(()) => Ok(()),
				_ => ProxyError::MonErreur,

			}
		}

		fn unexport(&self) ->  ProxyResult<()> {
			match self.pin.unexport()
			{
				Ok(()) => Ok(()),
				_ => yProxyError::MonErreur,
			}
		}

		fn set_value(&self, value: u8) ->  ProxyResult<()> {
			match self.pin.set_value(value)
			{
				Ok(()) => Ok(()),
				_ => ProxyError::MonErreur,
			}
		}

		fn set_direction(&self, dir: DirectionProxied) ->  ProxyResult<()>{
			let dirmapped =  match dir {
                                           DirectionProxied::In =>  Direction::In,
                                           DirectionProxied::Out => Direction::Out,
                                           DirectionProxied::High => Direction::High,
                                           DirectionProxied::Low => Direction::Low,
                                       };
			match self.pin.set_direction(dirmapped)
			{
				Ok(()) => Ok(()),
				_ => ProxyError::MonErreur,
			}
		}

    }
}

#[cfg(not(unix))]
pub mod gpioaccess{
	//use std::fmt;
	use super::{PinProxyContract,DirectionProxied,ProxyError,ProxyResult};

	pub struct PinProxy {
		pin_num: u64,
	}

	impl PinProxyContract for PinProxy
	{
		fn new(pin_num: u64) -> PinProxy {
			PinProxy{ pin_num: pin_num }
		}
		fn export(&self) -> ProxyResult<()>
		{
      println!("exporting pin {}",self.pin_num);
			Ok::<(),ProxyError>(())
		}
		fn unexport(&self) -> ProxyResult<()>
		{
        println!("unexporting pin {}",self.pin_num);
			  Ok::<(),ProxyError>(())
		}

		fn set_value(&self, value: u8) -> ProxyResult<()>
		{
			Ok::<(),ProxyError>(())
		}

		fn set_direction(&self, dir: DirectionProxied) -> ProxyResult<()>
		{
			Ok::<(),ProxyError>(())
		}
    }
}

#[derive(Copy, Clone)]
pub struct Sys;
impl Key for Sys { type Value = ActorSystem; }

struct Resolver;

impl Actor for Resolver {
    fn receive(&self, message: Box<Any>, context: ActorCell) {
        if let Ok(message) = Box::<Any>::downcast::<String>(message) {
            let future = context.identify_actor(*message, "resolver_request".to_owned());
            context.forward_result_to_future::<Option<ActorRef>>(future, context.sender());
			      context.stop(context.actor_ref());
        }
    }
}

impl Resolver {
    fn new(_dummy: ()) -> Resolver {
        Resolver
    }
}

fn main() {
  match env_logger::init() {
      Ok(()) => {}
      _ => {}
  };
	let dragon_actor_system  = ActorSystem::new("dragon".to_owned());
	dragon_actor_system.spawn_threads(3);

	dragon_actor_system.actor_of(Props::new(Arc::new(Dragon::new),()), "gorynich".to_owned());
    // the router (for RESTfull actions)
	let mut router = Router::new();
	router.get("/wings", move_wings,"wings");
	router.get("/mouth", open_mouth,"mouth");
	router.get("/eyes", blink_eyes,"eyes");

	fn handle_command(req: &mut Request, dragon_command: DragonCommands, dragon_event: DragonEvents ) ->IronResult<Response> {
		let arcsys = req.get::<Read<Sys>>().unwrap();
    	let sys = arcsys.as_ref();
		let props = Props::new(Arc::new(Resolver::new), ());
    	let answerer = sys.actor_of(props.clone(), "answerer".to_owned());
        let dragon = sys.ask(answerer, "/user/gorynich".to_owned(), "future".to_owned());
    	let dragon: Option<ActorRef> = sys.extract_result(dragon);
		match dragon {
			None => {
				Ok(Response::with((status::Ok, "Dragon not found")))
			}
			Some(dragonunwrapped) => {
				let future = sys.ask(dragonunwrapped, dragon_command, "request".to_owned());
	    		let event: DragonEvents = sys.extract_result(future);
				if event == dragon_event {
					Ok(Response::with((status::Ok, dragon_event.to_string())))
				} else
				{
					Ok(Response::with((status::Ok, "Unknown event!")))
				}
			}
		}
	}

	fn move_wings(req:&mut Request)  -> IronResult<Response>  {
		handle_command(req,DragonCommands::MoveWings,DragonEvents::WingsMoved)
	}

	fn open_mouth(req: &mut Request) -> IronResult<Response> {
		handle_command(req,DragonCommands::OpenMouth,DragonEvents::MouthOpened)
	}

	fn blink_eyes(req: &mut Request) -> IronResult<Response> {
		handle_command(req,DragonCommands::BlinkEyes,DragonEvents::EyesBlinked)
	}

	let mut chain = Chain::new(router);
	chain.link(Read::<Sys>::both(dragon_actor_system));
	// the mounter for static files
	let mut mount = Mount::new();
	mount
		.mount("/",Static::new(Path::new("static")))
		.mount("/api/",chain);
	Iron::new(mount).http("0.0.0.0:8080").unwrap();
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum DragonCommands {
	MoveWings,
	OpenMouth,
	BlinkEyes,
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum DragonEvents {
	WingsMoved,
	MouthOpened,
	EyesBlinked,
}

impl Display for DragonCommands {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

impl Display for DragonEvents {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

struct Dragon;

impl Actor for Dragon {

	fn pre_start(&self, context: ActorCell) {
		let wings = context.actor_of(Props::new(Arc::new(Wings::new),()), "wings".to_owned()).unwrap();
		let mouth = context.actor_of(Props::new(Arc::new(Mouth::new),()), "mouth".to_owned()).unwrap();
		let eyes = context.actor_of(Props::new(Arc::new(Eyes::new),()), "eyes".to_owned()).unwrap();
		context.tell(wings,LimbCommands::Init(10));
		context.tell(mouth,LimbCommands::Init(10));
		context.tell(eyes,LimbCommands::Init(10));
	}
	fn receive(&self, _message: Box<Any>, _context: ActorCell){
		if let Ok(_message) = Box::<Any>::downcast::<DragonCommands>(_message){
			match *_message {
				DragonCommands::MoveWings => {
						let wings: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/wings".to_owned())).cloned().unwrap();
						_context.tell(wings,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::WingsMoved);
						},
				DragonCommands::OpenMouth => {
						let mouth: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/mouth".to_owned())).cloned().unwrap();
						_context.tell(mouth,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::MouthOpened);
						},
				DragonCommands::BlinkEyes => {
						let eyes: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/eyes".to_owned())).cloned().unwrap();
						_context.tell(eyes,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::EyesBlinked);
						}
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Dragon {
	fn new(_: ()) -> Dragon {
		Dragon
	}
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum LimbCommands {
	Init(u64),
	Aggitate,
	Reset,
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum LimbEvents {
	Aggitated,
	NotAggitated(u64),
}

impl Display for LimbCommands {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

impl Display for LimbEvents {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

struct Wings;

impl Actor for Wings {
    fn pre_start(&self, context: ActorCell) {
		   context.actor_of(Props::new(Arc::new(PinActor::new), 18), "pin18".to_owned()).unwrap();
    }
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
            let pin18 : ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/wings/pin18".to_owned())).cloned().unwrap();
						_context.tell(pin18,PinCommands::Blink(20));
						println!("Moving Wings");
				},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Wings {
    fn new(_: ()) -> Wings {
        Wings
    }
}

struct Mouth;

impl Actor for Mouth {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
						println!("Opening Mouth");
						},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Mouth {
    fn new(_: ()) -> Mouth {
        Mouth
    }
}

struct Eyes;

impl Actor for Eyes {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
						println!("Blinking Eyes");
						//_context.complete(_context.sender(),LimbEvents::Aggitated);
						},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Eyes {
    fn new(_: ()) -> Eyes {
        Eyes
    }
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum PinCommands {
	Blink(u64),
	Switch,
}

struct PinActor {
	pinproxy :  Mutex<PinProxy>,
}

impl Actor for PinActor {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<PinCommands>(_message){
			match *_message {
				  PinCommands::Blink(times) => {
              let pin = self.pinproxy.lock().unwrap();
              match pin.export() {
                  Ok(()) => {
						          println!("Pin exported");
                      pin.set_direction(DirectionProxied::Out);
                      pin.set_direction(DirectionProxied::High);
                      thread::sleep(time::Duration::from_millis(10));
                      pin.set_direction(DirectionProxied::Low);
                      thread::sleep(time::Duration::from_millis(10));
                      match pin.unexport() {
                          Ok(()) => {
						                  println!("Pin unexported");
                          }
                          _ => {}
                      }
                  }
                  _ => {}
              }
          },
				PinCommands::Switch => {	}
			}
		}
	}
}

impl PinActor{
	fn new(pin_number: u64) -> PinActor {
		PinActor{ pinproxy : Mutex::new(PinProxy::new(pin_number)) }
    }
}

mod test;
<commit_msg>it werks on rpi<commit_after>extern crate iron;
extern crate router;
extern crate mount;
extern crate staticfile;
extern crate robots;
extern crate persistent;
extern crate env_logger;

use iron::prelude::*;
use iron::status;
use router::Router;
use staticfile::Static;
use mount::Mount;
use std::path::Path;
use std::any::Any;
use std::sync::{Arc,Mutex};
use std::thread;
use std::time;
use robots::actors::{ActorSystem,Actor,ActorCell,ActorContext,Props,ActorRef,ActorPath};
use persistent::Read;
use iron::typemap::Key;
use std::fmt::{Debug, Display,Formatter,Result};
use gpioaccess::PinProxy;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DirectionProxied {
    In,
    Out,
    High,
    Low,
}

#[derive(Debug)]
pub enum ProxyError {
	MonErreur,
}

impl ::std::error::Error for ProxyError {
	fn description(&self) -> &str {
		"an error"
	}
}

impl Display for ProxyError {
	fn fmt(&self, f: &mut Formatter) -> Result {
		write!(f, "an error")
	}
}

pub type ProxyResult<T> = ::std::result::Result<T, ProxyError>;

//depend on abstractions not concretions lulz
trait PinProxyContract {

	fn new(pin_num: u64) -> Self;
	//FIXME :figure out mapping overloaded Result from gpio library
	fn export(&self) -> ProxyResult<()>;

	fn unexport(&self) ->  ProxyResult<()>;

	fn set_value(&self, value: u8) -> ProxyResult<()>;

	fn set_direction(&self, dir: DirectionProxied) ->  ProxyResult<()>;
}

#[cfg(unix)]
pub mod gpioaccess{

	extern crate sysfs_gpio;
	use self::sysfs_gpio::{Direction, Pin};
	use super::{PinProxyContract,DirectionProxied,ProxyError,ProxyResult};

	pub struct PinProxy {
		pin : Pin,
	}

	impl PinProxyContract for PinProxy
	{
		fn new(pin_num: u64) -> PinProxy {
			PinProxy{ pin: Pin::new(pin_num) }
		}

		fn export(&self) ->  ProxyResult<()>{
			match self.pin.export()
			{
				Ok(()) => Ok(()),
				_ => Err(ProxyError::MonErreur),

			}
		}

		fn unexport(&self) ->  ProxyResult<()> {
			match self.pin.unexport()
			{
				Ok(()) => Ok(()),
				_ => Err(ProxyError::MonErreur),
			}
		}

		fn set_value(&self, value: u8) ->  ProxyResult<()> {
			match self.pin.set_value(value)
			{
				Ok(()) => Ok(()),
				_ => Err(ProxyError::MonErreur),
			}
		}

		fn set_direction(&self, dir: DirectionProxied) ->  ProxyResult<()>{
			let dirmapped =  match dir {
                                           DirectionProxied::In =>  Direction::In,
                                           DirectionProxied::Out => Direction::Out,
                                           DirectionProxied::High => Direction::High,
                                           DirectionProxied::Low => Direction::Low,
                                       };
			match self.pin.set_direction(dirmapped)
			{
				Ok(()) => Ok(()),
				_ => Err(ProxyError::MonErreur),
			}
		}

    }
}

#[cfg(not(unix))]
pub mod gpioaccess{
	//use std::fmt;
	use super::{PinProxyContract,DirectionProxied,ProxyError,ProxyResult};

	pub struct PinProxy {
		pin_num: u64,
	}

	impl PinProxyContract for PinProxy
	{
		fn new(pin_num: u64) -> PinProxy {
			PinProxy{ pin_num: pin_num }
		}
		fn export(&self) -> ProxyResult<()>
		{
      println!("exporting pin {}",self.pin_num);
			Ok::<(),ProxyError>(())
		}
		fn unexport(&self) -> ProxyResult<()>
		{
        println!("unexporting pin {}",self.pin_num);
			  Ok::<(),ProxyError>(())
		}

		fn set_value(&self, value: u8) -> ProxyResult<()>
		{
			Ok::<(),ProxyError>(())
		}

		fn set_direction(&self, dir: DirectionProxied) -> ProxyResult<()>
		{
			Ok::<(),ProxyError>(())
		}
    }
}

#[derive(Copy, Clone)]
pub struct Sys;
impl Key for Sys { type Value = ActorSystem; }

struct Resolver;

impl Actor for Resolver {
    fn receive(&self, message: Box<Any>, context: ActorCell) {
        if let Ok(message) = Box::<Any>::downcast::<String>(message) {
            let future = context.identify_actor(*message, "resolver_request".to_owned());
            context.forward_result_to_future::<Option<ActorRef>>(future, context.sender());
			      context.stop(context.actor_ref());
        }
    }
}

impl Resolver {
    fn new(_dummy: ()) -> Resolver {
        Resolver
    }
}

fn main() {
  match env_logger::init() {
      Ok(()) => {}
      _ => {}
  };
	let dragon_actor_system  = ActorSystem::new("dragon".to_owned());
	dragon_actor_system.spawn_threads(3);

	dragon_actor_system.actor_of(Props::new(Arc::new(Dragon::new),()), "gorynich".to_owned());
    // the router (for RESTfull actions)
	let mut router = Router::new();
	router.get("/wings", move_wings,"wings");
	router.get("/mouth", open_mouth,"mouth");
	router.get("/eyes", blink_eyes,"eyes");

	fn handle_command(req: &mut Request, dragon_command: DragonCommands, dragon_event: DragonEvents ) ->IronResult<Response> {
		let arcsys = req.get::<Read<Sys>>().unwrap();
    	let sys = arcsys.as_ref();
		let props = Props::new(Arc::new(Resolver::new), ());
    	let answerer = sys.actor_of(props.clone(), "answerer".to_owned());
        let dragon = sys.ask(answerer, "/user/gorynich".to_owned(), "future".to_owned());
    	let dragon: Option<ActorRef> = sys.extract_result(dragon);
		match dragon {
			None => {
				Ok(Response::with((status::Ok, "Dragon not found")))
			}
			Some(dragonunwrapped) => {
				let future = sys.ask(dragonunwrapped, dragon_command, "request".to_owned());
	    		let event: DragonEvents = sys.extract_result(future);
				if event == dragon_event {
					Ok(Response::with((status::Ok, dragon_event.to_string())))
				} else
				{
					Ok(Response::with((status::Ok, "Unknown event!")))
				}
			}
		}
	}

	fn move_wings(req:&mut Request)  -> IronResult<Response>  {
		handle_command(req,DragonCommands::MoveWings,DragonEvents::WingsMoved)
	}

	fn open_mouth(req: &mut Request) -> IronResult<Response> {
		handle_command(req,DragonCommands::OpenMouth,DragonEvents::MouthOpened)
	}

	fn blink_eyes(req: &mut Request) -> IronResult<Response> {
		handle_command(req,DragonCommands::BlinkEyes,DragonEvents::EyesBlinked)
	}

	let mut chain = Chain::new(router);
	chain.link(Read::<Sys>::both(dragon_actor_system));
	// the mounter for static files
	let mut mount = Mount::new();
	mount
		.mount("/",Static::new(Path::new("static")))
		.mount("/api/",chain);
	Iron::new(mount).http("0.0.0.0:8080").unwrap();
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum DragonCommands {
	MoveWings,
	OpenMouth,
	BlinkEyes,
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum DragonEvents {
	WingsMoved,
	MouthOpened,
	EyesBlinked,
}

impl Display for DragonCommands {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

impl Display for DragonEvents {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

struct Dragon;

impl Actor for Dragon {

	fn pre_start(&self, context: ActorCell) {
		let wings = context.actor_of(Props::new(Arc::new(Wings::new),()), "wings".to_owned()).unwrap();
		let mouth = context.actor_of(Props::new(Arc::new(Mouth::new),()), "mouth".to_owned()).unwrap();
		let eyes = context.actor_of(Props::new(Arc::new(Eyes::new),()), "eyes".to_owned()).unwrap();
		context.tell(wings,LimbCommands::Init(10));
		context.tell(mouth,LimbCommands::Init(10));
		context.tell(eyes,LimbCommands::Init(10));
	}
	fn receive(&self, _message: Box<Any>, _context: ActorCell){
		if let Ok(_message) = Box::<Any>::downcast::<DragonCommands>(_message){
			match *_message {
				DragonCommands::MoveWings => {
						let wings: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/wings".to_owned())).cloned().unwrap();
						_context.tell(wings,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::WingsMoved);
						},
				DragonCommands::OpenMouth => {
						let mouth: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/mouth".to_owned())).cloned().unwrap();
						_context.tell(mouth,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::MouthOpened);
						},
				DragonCommands::BlinkEyes => {
						let eyes: ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/eyes".to_owned())).cloned().unwrap();
						_context.tell(eyes,LimbCommands::Aggitate);
						_context.complete(_context.sender(),DragonEvents::EyesBlinked);
						}
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Dragon {
	fn new(_: ()) -> Dragon {
		Dragon
	}
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum LimbCommands {
	Init(u64),
	Aggitate,
	Reset,
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum LimbEvents {
	Aggitated,
	NotAggitated(u64),
}

impl Display for LimbCommands {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

impl Display for LimbEvents {
    fn fmt(&self, f: &mut Formatter) -> Result {
        Debug::fmt(self, f)
    }
}

struct Wings;

impl Actor for Wings {
    fn pre_start(&self, context: ActorCell) {
		   context.actor_of(Props::new(Arc::new(PinActor::new), 18), "pin18".to_owned()).unwrap();
    }
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
                        let pin18 : ActorRef = _context.children().get(&ActorPath::new_local("/user/gorynich/wings/pin18".to_owned())).cloned().unwrap();
						_context.tell(pin18,PinCommands::Blink(5));
						println!("Moving Wings");
				},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Wings {
    fn new(_: ()) -> Wings {
        Wings
    }
}

struct Mouth;

impl Actor for Mouth {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
						println!("Opening Mouth");
						},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Mouth {
    fn new(_: ()) -> Mouth {
        Mouth
    }
}

struct Eyes;

impl Actor for Eyes {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<LimbCommands>(_message){
			match *_message {
				LimbCommands::Init(max) => { println!("Initializing with maximum {}",max); },
				LimbCommands::Aggitate => {
						println!("Blinking Eyes");
						//_context.complete(_context.sender(),LimbEvents::Aggitated);
						},
				LimbCommands::Reset => { println!("Received reset"); }
			}
		} else {
			println!("Gorynich does not understand!");
		}
	}
}

impl Eyes {
    fn new(_: ()) -> Eyes {
        Eyes
    }
}

#[derive(Copy, Clone, PartialEq,Debug)]
enum PinCommands {
	Blink(u64),
	Switch,
}

struct PinActor {
	pinproxy :  Mutex<PinProxy>,
}

impl Actor for PinActor {
    fn receive(&self, _message: Box<Any>, _context: ActorCell) {
		if let Ok(_message) = Box::<Any>::downcast::<PinCommands>(_message){
			match *_message {
			    PinCommands::Blink(times) => {
                let pin = self.pinproxy.lock().unwrap();
                match pin.export() {
                  Ok(()) => {
						        println!("Pin exported");
                                for x in 1..times {
                                    pin.set_direction(DirectionProxied::Out);
                                    pin.set_direction(DirectionProxied::High);
                                    thread::sleep(time::Duration::from_millis(200));
                                    pin.set_direction(DirectionProxied::Low);
                                    thread::sleep(time::Duration::from_millis(200));
                                    println!("Blink {}",x);
                                }
                                match pin.unexport() {
                          Ok(()) => {
						                  println!("Pin unexported");
                          }
                          _ => {}
                      }
                  }
                  _ => {}
              }
          },
				PinCommands::Switch => {	}
			}
		}
	}
}

impl PinActor{
	fn new(pin_number: u64) -> PinActor {
		PinActor{ pinproxy : Mutex::new(PinProxy::new(pin_number)) }
    }
}

mod test;
<|endoftext|>