<commit_before>#![feature(rand)]

#[macro_use]
extern crate glium;
extern crate rand;

use std::collections::{HashSet, VecDeque};

use glium::Surface;
use glium::glutin;

#[derive(Clone, Copy, Debug, PartialEq)]
enum Color {
    Red,
    Yellow,
    Green,
    LightBrown,
    Purple,
    Cyan,
    Blue,
    Fuchsia,
}

const COLORS: &[Color] = &[
    Color::Red,
    Color::Yellow,
    Color::Green,
    Color::LightBrown,
    Color::Purple,
    Color::Cyan,
    Color::Blue,
    Color::Fuchsia,
];

impl Color {
    fn to_rgba(c: Color) -> [u8; 3] {
        use Color::*;

        match c {
            Red => [255, 0, 0],
            Yellow => [255, 255, 0],
            Green => [0, 176, 0],
            LightBrown => [255, 204, 102],
            Purple => [128, 0, 128],
            Cyan => [0, 255, 255],
            Blue => [0, 0, 255],
            Fuchsia => [255, 0, 255],
        }
    }
}

impl rand::Rand for Color {
    fn rand<R: rand::Rng>(rng: &mut R) -> Self {
        *rng.choose(COLORS).unwrap()
    }
}

struct Grid {
    width: u8,
    height: u8,
    num_colors: u8,

    current_color: Color,
    cells: Vec<Color>,

    max_clicks: u16,
    num_clicks: u16,
}

impl Grid {
    pub fn new(num_colors: u8, size: u8) -> Self {
        use rand::distributions::{IndependentSample, Range};
        let between = Range::new(0, num_colors as usize);
        let mut rng = rand::thread_rng();

        let cells: Vec<Color> = (0..size * size)
            .map(|_| COLORS[between.ind_sample(&mut rng)])
            .collect();
        let max_clicks = 25 * 2 * size as u16 * num_colors as u16 / (2 * 14 * 6);

        Self {
            width: size,
            height: size,
            num_colors,

            current_color: cells[0],
            cells,

            max_clicks,
            num_clicks: 0,
        }
    }

    fn index(&self, row: u8, column: u8) -> usize {
        self.width as usize * row as usize + column as usize
    }

    fn current_color(&self) -> Color {
        self.cells[0]
    }

    pub fn click(&mut self, row: u8, column: u8) -> Option<usize> {
        let i = self.index(row, column);
        let new_color = self.cells[i];
        if self.current_color() == new_color {
            return None;
        }

        self.num_clicks += 1;
        Some(self.flood(new_color))
    }

    /// Flood the grid from the top left cell and return the number of cell which are connected to
    /// the top left cell by cells of indentical color.
    fn flood(&mut self, new_color: Color) -> usize {
        let current_color = self.current_color();
        self.num_clicks += 1;

        let rows = self.height as usize;
        let columns = self.width as usize;

        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(0);
        let mut frontier = VecDeque::new();

        let mut num_cells = 0;
        while let Some(i) = queue.pop_front() {
            num_cells += 1;
            self.cells[i] = new_color;
            visited.insert(i);

            if i % columns > 0 && !visited.contains(&(i - 1)) {
                if self.cells[i - 1] == current_color {
                    queue.push_back(i - 1);
                } else if self.cells[i - 1] == new_color {
                    frontier.push_back(i - 1);
                }
            }
            if i % columns < columns - 1 && !visited.contains(&(i + 1)) {
                if self.cells[i + 1] == current_color {
                    queue.push_back(i + 1);
                } else if self.cells[i + 1] == new_color {
                    frontier.push_back(i + 1);
                }
            }
            if i >= columns && !visited.contains(&(i - columns)) {
                if self.cells[i - columns] == current_color {
                    queue.push_back(i - columns);
                } else if self.cells[i - columns] == new_color {
                    frontier.push_back(i - columns);
                }
            }
            if i <= (rows - 1) * columns && !visited.contains(&(i + columns)) {
                if self.cells[i + columns] == current_color {
                    queue.push_back(i + columns);
                } else if self.cells[i + columns] == new_color {
                    frontier.push_back(i + columns);
                }
            }
        }
        println!("Changed the color of {} cells", num_cells);

        while let Some(i) = frontier.pop_front() {
            visited.insert(i);
            num_cells += 1;
            if i % columns > 0 && self.cells[i - 1] == new_color && !visited.contains(&(i - 1)) {
                frontier.push_back(i - 1);
            }
            if i % columns < columns - 1 && self.cells[i + 1] == new_color &&
                !visited.contains(&(i + 1))
            {
                frontier.push_back(i + 1);
            }
            if i >= columns && self.cells[i - columns] == new_color &&
                !visited.contains(&(i - columns))
            {
                frontier.push_back(i - columns);
            }
            if i <= (rows - 1) * columns && self.cells[i + columns] == new_color &&
                !visited.contains(&(i + columns))
            {
                frontier.push_back(i + columns);
            }
        }

        println!(
            "The connected of component of 0 now contains {} cells",
            num_cells
        );
        num_cells
    }
}

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

implement_vertex!(Vertex, color, position);

const TITLE: &'static str = "Flood-It";

fn main() {
    use glium::glutin::{ContextBuilder, EventsLoop, WindowBuilder};

    let mut events_loop = EventsLoop::new();
    let window = WindowBuilder::new().with_title(TITLE);
    let context = ContextBuilder::new();
    let display = glium::Display::new(window, context, &events_loop).unwrap();

    let vertex_shader_src = r#"
        #version 140
        in vec2 position;
        in float color;
        uniform mat4 matrix;
        out float c;
        void main() {
            c = color;
            gl_Position = matrix * vec4(position, 0.0, 1.0);
        }
    "#;

    let fragment_shader_src = r#"
        #version 140
        in float c;
        out vec4 color;
        void main() {
            if (c <= 0.0)
                color = vec4(1.0, 0.0, 0.0, 1.0);
            else if (c <= 1.0)
                color = vec4(1.0, 1.0, 0.0, 1.0);
            else if (c <= 2.0)
                color = vec4(0.0, 0.69, 0.0, 1.0);
            else if (c <= 3.0)
                color = vec4(1.0, 0.8, 0.4, 1.0);
            else if (c <= 4.0)
                color = vec4(0.5, 0.0, 0.5, 1.0);
            else if (c <= 5.0)
                color = vec4(0.0, 1.0, 1.0, 1.0);
            else if (c <= 6.0)
                color = vec4(0.0, 0.0, 1.0, 1.0);
            else if (c <= 7.0)
                color = vec4(1.0, 0.0, 1.0, 1.0);
            else
                color = vec4(1.0, 1.0, 1.0, 1.0);
        }
    "#;

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

    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let params = glium::DrawParameters {
        backface_culling: glium::draw_parameters::BackfaceCullingMode::CullClockwise,
        ..Default::default()
    };

    let mut grid = Grid::new(8, 14);

    let mut closed = false;
    while !closed {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);
        let (width, height) = target.get_dimensions();
        let screen_aspect_ratio = height as f32 / width as f32;
        let grid_aspect_ratio = grid.height as f32 / grid.width as f32;

        let (ratio_x, ratio_y) = if screen_aspect_ratio < grid_aspect_ratio {
            (screen_aspect_ratio, 1.0)
        } else {
            (1.0, 1.0 / screen_aspect_ratio)
        };

        let uniforms =
            uniform! {
            matrix: [
                [ratio_x, 0.0, 0.0, 0.0],
                [0.0, ratio_y, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0_f32],
            ]
        };

        let mut triangles = vec![];

        for &color in COLORS.iter() {
            for i in 0..grid.cells.len() {
                let x = (i % grid.width as usize) as f32;
                let y = (i / grid.width as usize) as f32;
                if color != grid.cells[i] {
                    continue;
                }

                let cell_size = 2.0 / grid.height.max(grid.width) as f32;

                let mut quad = generate_rectangle_vertices(
                    x * cell_size - 1.0,
                    y * cell_size - 1.0,
                    (x + 1.0) * cell_size - 1.0,
                    (y + 1.0) * cell_size - 1.0,
                    color,
                );
                triangles.append(&mut quad);
            }
            let vertex_buffer = glium::VertexBuffer::new(&display, &triangles).unwrap();
            target
                .draw(&vertex_buffer, &indices, &program, &uniforms, &params)
                .unwrap();
        }

        target.finish().unwrap();

        events_loop.poll_events(|event| if let glutin::Event::WindowEvent {
            event, ..
        } = event
        {
            match event {
                glutin::WindowEvent::Closed => closed = true,
                _ => (),
            }
        })
    }
}

fn generate_rectangle_vertices(
    left: f32,
    bottom: f32,
    right: f32,
    top: f32,
    color: Color,
) -> Vec<Vertex> {
    let color = color as u32 as f32;
    vec![
        Vertex {
            color,
            position: [left, bottom],
        },
        Vertex {
            color,
            position: [right, bottom],
        },
        Vertex {
            color,
            position: [left, top],
        },
        Vertex {
            color,
            position: [right, bottom],
        },
        Vertex {
            color,
            position: [right, top],
        },
        Vertex {
            color,
            position: [left, top],
        },
    ]
}
<commit_msg>Basic implementation of the game<commit_after>#![feature(rand)]

#[macro_use]
extern crate glium;
extern crate rand;

use std::collections::{HashSet, VecDeque};

use glium::Surface;
use glium::glutin;

#[derive(Clone, Copy, Debug, PartialEq)]
enum Color {
    Red,
    Yellow,
    Green,
    LightBrown,
    Purple,
    Cyan,
    Blue,
    Fuchsia,
}

const COLORS: &[Color] = &[
    Color::Red,
    Color::Yellow,
    Color::Green,
    Color::LightBrown,
    Color::Purple,
    Color::Cyan,
    Color::Blue,
    Color::Fuchsia,
];

impl rand::Rand for Color {
    fn rand<R: rand::Rng>(rng: &mut R) -> Self {
        *rng.choose(COLORS).unwrap()
    }
}

struct Grid {
    width: u8,
    height: u8,

    cells: Vec<Color>,

    max_clicks: u16,
    num_clicks: u16,
}

impl Grid {
    pub fn new(num_colors: u8, size: u8) -> Self {
        use rand::distributions::{IndependentSample, Range};
        let between = Range::new(0, num_colors as usize);
        let mut rng = rand::thread_rng();

        let cells: Vec<Color> = (0..size as u64 * size as u64)
            .map(|_| COLORS[between.ind_sample(&mut rng)])
            .collect();
        let max_clicks = 25 * 2 * size as u16 * num_colors as u16 / (2 * 14 * 6);

        Self {
            width: size,
            height: size,

            cells,

            max_clicks,
            num_clicks: 0,
        }
    }

    fn index(&self, row: u8, column: u8) -> usize {
        self.width as usize * row as usize + column as usize
    }

    fn current_color(&self) -> Color {
        self.cells[0]
    }

    pub fn click(&mut self, row: u8, column: u8) -> Option<usize> {
        let i = self.index(row, column);
        let new_color = self.cells[i];
        if self.current_color() == new_color {
            return None;
        }

        self.num_clicks += 1;
        Some(self.flood(new_color))
    }

    /// Flood the grid from the top left cell and return the number of cell which are connected to
    /// the top left cell by cells of indentical color.
    fn flood(&mut self, new_color: Color) -> usize {
        let current_color = self.current_color();

        let rows = self.height as usize;
        let columns = self.width as usize;

        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back(0);
        let mut frontier = VecDeque::new();

        let mut num_cells = 0;
        while let Some(i) = queue.pop_front() {
            if self.cells[i] == new_color {
                continue;
            }
            num_cells += 1;
            self.cells[i] = new_color;
            visited.insert(i);

            if i % columns > 0 && !visited.contains(&(i - 1)) {
                if self.cells[i - 1] == current_color {
                    queue.push_back(i - 1);
                } else if self.cells[i - 1] == new_color {
                    frontier.push_back(i - 1);
                }
            }
            if i % columns < columns - 1 && !visited.contains(&(i + 1)) {
                if self.cells[i + 1] == current_color {
                    queue.push_back(i + 1);
                } else if self.cells[i + 1] == new_color {
                    frontier.push_back(i + 1);
                }
            }
            if i >= columns && !visited.contains(&(i - columns)) {
                if self.cells[i - columns] == current_color {
                    queue.push_back(i - columns);
                } else if self.cells[i - columns] == new_color {
                    frontier.push_back(i - columns);
                }
            }
            if i < (rows - 1) * columns && !visited.contains(&(i + columns)) {
                if self.cells[i + columns] == current_color {
                    queue.push_back(i + columns);
                } else if self.cells[i + columns] == new_color {
                    frontier.push_back(i + columns);
                }
            }
        }

        while let Some(i) = frontier.pop_front() {
            if visited.contains(&i) {
                continue;
            }

            visited.insert(i);
            num_cells += 1;
            if i % columns > 0 && self.cells[i - 1] == new_color && !visited.contains(&(i - 1)) {
                frontier.push_back(i - 1);
            }
            if i % columns < columns - 1 && self.cells[i + 1] == new_color &&
                !visited.contains(&(i + 1))
            {
                frontier.push_back(i + 1);
            }
            if i >= columns && self.cells[i - columns] == new_color &&
                !visited.contains(&(i - columns))
            {
                frontier.push_back(i - columns);
            }
            if i < (rows - 1) * columns && self.cells[i + columns] == new_color &&
                !visited.contains(&(i + columns))
            {
                frontier.push_back(i + columns);
            }
        }

        num_cells
    }
}

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

implement_vertex!(Vertex, color, position);

const TITLE: &'static str = "Flood-It";

fn main() {
    use glium::glutin::{ContextBuilder, EventsLoop, WindowBuilder};
    use glutin::{Event, WindowEvent};

    let mut events_loop = EventsLoop::new();
    let window = WindowBuilder::new().with_title(TITLE);
    let context = ContextBuilder::new();
    let display = glium::Display::new(window, context, &events_loop).unwrap();

    let vertex_shader_src = r#"
        #version 140
        in vec2 position;
        in float color;
        uniform mat4 matrix;
        out float c;
        void main() {
            c = color;
            gl_Position = matrix * vec4(position, 0.0, 1.0);
        }
    "#;

    let fragment_shader_src = r#"
        #version 140
        in float c;
        out vec4 color;
        void main() {
            if (c <= 0.0)
                color = vec4(1.0, 0.0, 0.0, 1.0);
            else if (c <= 1.0)
                color = vec4(1.0, 1.0, 0.0, 1.0);
            else if (c <= 2.0)
                color = vec4(0.0, 0.69, 0.0, 1.0);
            else if (c <= 3.0)
                color = vec4(1.0, 0.8, 0.4, 1.0);
            else if (c <= 4.0)
                color = vec4(0.5, 0.0, 0.5, 1.0);
            else if (c <= 5.0)
                color = vec4(0.0, 1.0, 1.0, 1.0);
            else if (c <= 6.0)
                color = vec4(0.0, 0.0, 1.0, 1.0);
            else if (c <= 7.0)
                color = vec4(1.0, 0.0, 1.0, 1.0);
            else
                color = vec4(1.0, 1.0, 1.0, 1.0);
        }
    "#;

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

    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let params = glium::DrawParameters {
        backface_culling: glium::draw_parameters::BackfaceCullingMode::CullCounterClockwise,
        ..Default::default()
    };

    let mut grid = Grid::new(6, 14);

    let mut cursor_position = (0.0, 0.0);
    let mut closed = false;
    while !closed {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 0.0, 1.0);
        let (width, height) = target.get_dimensions();
        let screen_aspect_ratio = height as f32 / width as f32;
        let grid_aspect_ratio = grid.height as f32 / grid.width as f32;

        let (ratio_x, ratio_y) = if screen_aspect_ratio < grid_aspect_ratio {
            (screen_aspect_ratio, 1.0)
        } else {
            (1.0, 1.0 / screen_aspect_ratio)
        };

        let uniforms =
            uniform! {
            matrix: [
                [ratio_x, 0.0, 0.0, 0.0],
                [0.0, -ratio_y, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
                [0.0, 0.0, 0.0, 1.0_f32],
            ]
        };

        let mut triangles = vec![];

        for &color in COLORS.iter() {
            for i in 0..grid.cells.len() {
                let x = (i % grid.width as usize) as f32;
                let y = (i / grid.width as usize) as f32;
                if color != grid.cells[i] {
                    continue;
                }

                let cell_size = 2.0 / grid.height.max(grid.width) as f32;

                let mut quad = generate_rectangle_vertices(
                    x * cell_size - 1.0,
                    y * cell_size - 1.0,
                    (x + 1.0) * cell_size - 1.0,
                    (y + 1.0) * cell_size - 1.0,
                    color,
                );
                triangles.append(&mut quad);
            }
            let vertex_buffer = glium::VertexBuffer::new(&display, &triangles).unwrap();
            target
                .draw(&vertex_buffer, &indices, &program, &uniforms, &params)
                .unwrap();
        }

        target.finish().unwrap();

        events_loop.poll_events(|event| match event {
            Event::WindowEvent { event, .. } => {
                match event {
                    WindowEvent::Closed => closed = true,
                    WindowEvent::MouseMoved { position, .. } => cursor_position = position,
                    WindowEvent::MouseInput {
                        state: glium::glutin::ElementState::Released,
                        button: glium::glutin::MouseButton::Left,
                        ..
                    } => {
                        let offsets = {
                            let offset = (width as f64 - height as f64).abs() / 2.0;
                            if screen_aspect_ratio < grid_aspect_ratio {
                                (offset, 0.0)
                            } else {
                                (0.0, offset)
                            }
                        };
                        if cursor_position.0 - offsets.0 >= 0.0 &&
                            cursor_position.1 - offsets.1 >= 0.0
                        {
                            let column = ((cursor_position.0 - offsets.0) * grid.width as f64 /
                                              (width as f64 - 2.0 * offsets.0))
                                .floor() as u8;
                            let row = ((cursor_position.1 - offsets.1) * grid.height as f64 /
                                           (height as f64 - 2.0 * offsets.1))
                                .floor() as u8;
                            let component = grid.click(row, column);
                            if let Some(n) = component {
                                if n == grid.cells.len() {
                                    if grid.num_clicks <= grid.max_clicks {
                                        println!("You have won using {} moves.", grid.num_clicks);
                                    } else {
                                        println!("You lose. You took {} moves but should have finished in {}.", grid.num_clicks, grid.max_clicks);
                                    }
                                }
                            }
                        }
                    }
                    _ => (),
                }
            }
            _ => (),
        });
    }
}

fn generate_rectangle_vertices(
    left: f32,
    bottom: f32,
    right: f32,
    top: f32,
    color: Color,
) -> Vec<Vertex> {
    let color = color as u32 as f32;
    vec![
        Vertex {
            color,
            position: [left, bottom],
        },
        Vertex {
            color,
            position: [right, bottom],
        },
        Vertex {
            color,
            position: [left, top],
        },
        Vertex {
            color,
            position: [right, bottom],
        },
        Vertex {
            color,
            position: [right, top],
        },
        Vertex {
            color,
            position: [left, top],
        },
    ]
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#[plugin] #[no_link]
extern crate regex_macros;
extern crate regex;

use std::os;
mod cli;
mod todo {
    pub mod list;
    pub mod entry;
}

fn main() {
    let path = os::getcwd().unwrap();
    let args = os::args();
    cli::delegate(path, args);
}
<commit_msg>Suppress certain warnings (for now)<commit_after>#![allow(unstable)]

#![feature(plugin)]
#[plugin] #[no_link]
extern crate regex_macros;
extern crate regex;

use std::os;
mod cli;
mod todo {
    pub mod list;
    pub mod entry;
}

fn main() {
    let path = os::getcwd().unwrap();
    let args = os::args();
    cli::delegate(path, args);
}
<|endoftext|>


<commit_before>extern crate core;
use core::ast::*;

fn main() {
  let v_bool = Var::new("bool", 0);
  let v_true = Var::new("true", 0);
  let v_false = Var::new("false", 0);
  let v_if = Var::new("if", 0);
  let v_b = Var::new("b", 0);
  let v_r = Var::new("r", 0);
  let v_x = Var::new("x", 0);
  let v_y = Var::new("y", 0);
  let v_0 = Var::new("0", 0);
  let v_1 = Var::new("1", 0);
  let v_nat = Var::new("nat", 0);
  let v_and = Var::new("and", 0);
  let v_or = Var::new("or", 0);
  let v_xor = Var::new("xor", 0);
  let v_not = Var::new("not", 0);
  let unused = Var::new("", 0);

  let ty_bool = constant(Const::Data);
  println!("bool : {}.", ty_bool.to_string());
  let ty_true = var(&v_bool);
  println!("true : {}.", ty_true.to_string());
  let ty_false = var(&v_bool);
  println!("false : {}.", ty_false.to_string());
  let ty_if = lam(unused.clone(),
                  var(&v_bool),
                  pi(v_r.clone(),
                     constant(Const::Data),
                     lam(unused.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_r)))));
  println!("if : {}.", ty_if.to_string());
  println!("");

  let impl_bool = pi(v_r.clone(),
                     constant(Const::Data),
                     lam(unused.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_r))));
  println!("bool = {}.", impl_bool.to_string());
  let impl_true = pi(v_r.clone(),
                     constant(Const::Data),
                     lam(v_x.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_x))));
  println!("true = {}.", impl_true.to_string());
  let impl_false = pi(v_r.clone(),
                      constant(Const::Data),
                      lam(unused.clone(),
                          var(&v_r),
                          lam(v_y.clone(), var(&v_r), var(&v_y))));
  println!("false = {}.", impl_false.to_string());
  let impl_if = lam(v_b.clone(), var(&v_bool), var(&v_b));
  println!("if = {}.", impl_if.to_string());
  println!("");

  let if_true = lam(v_bool.clone(),
                    ty_bool.clone(),
                    lam(v_true.clone(),
                        ty_true.clone(),
                        lam(v_false.clone(),
                            ty_false.clone(),
                            lam(v_if.clone(),
                                ty_if.clone(),
                                app(app(app(app(var(&v_if),
                                                var(&v_true)),
                                            var(&v_nat)),
                                        var(&v_1)),
                                    var(&v_0))))));
  println!("{}", if_true.to_string());

  let program = if_true;
  let execute = app(app(app(app(program, impl_bool.clone()),
                            impl_true.clone()),
                        impl_false.clone()),
                    impl_if.clone());
  println!("{}", execute.to_string());

  let result = execute.normalize();
  println!("= {}", result.to_string());
  println!("");

  let p2 = lam(v_false.clone(),
               ty_false.clone(),
               app(app(app(var(&v_false), var(&v_nat)), var(&v_1)), var(&v_0)));
  println!("{}", p2.to_string());

  let r2 = app(p2, impl_false.clone());
  println!("{}", r2.to_string());
  println!("= {}", r2.normalize().to_string());
  println!("");

  let ty_and = lam(unused.clone(),
                   var(&v_bool),
                   lam(unused.clone(), var(&v_bool), var(&v_bool)));
  println!("and : {}.", ty_and.to_string());
  // TODO: Does this need to be applied to if?
  let impl_and = app(lam(v_if.clone(),
                         ty_if.clone(),
                         lam(v_x.clone(),
                             var(&v_bool),
                             lam(v_y.clone(),
                                 var(&v_bool),
                                 app(app(app(app(var(&v_if), var(&v_x)),
                                             var(&v_bool)),
                                         var(&v_y)),
                                     var(&v_false))))),
                     impl_if.clone());
  println!("and = {}.", impl_and.to_string());
  println!("");

  let and_prog = lam(v_bool.clone(),
                     ty_bool.clone(),
                     lam(v_true.clone(),
                         ty_true.clone(),
                         lam(v_false.clone(),
                             ty_false.clone(),
                             lam(v_if.clone(),
                                 ty_if.clone(),
                                 lam(v_and.clone(),
                                     ty_and.clone(),
                                     app(app(var(&v_and),
                                             // var(&v_if)),
                                             var(&v_true)),
                                         var(&v_false)))))));
  // println!("{}", and_prog.to_string());
  let run_and_prog = app(app(app(app(app(and_prog, impl_bool.clone()),
                                     impl_true.clone()),
                                 impl_false.clone()),
                             impl_if.clone()),
                         impl_and.clone());
  println!("{}", run_and_prog.to_string());
  println!("= {}", run_and_prog.normalize().to_string());
}
<commit_msg>Rewrite and to get it to normalize correctly.<commit_after>extern crate core;
use core::ast::*;

fn main() {
  let v_bool = Var::new("bool", 0);
  let v_true = Var::new("true", 0);
  let v_false = Var::new("false", 0);
  let v_if = Var::new("if", 0);
  let v_b = Var::new("b", 0);
  let v_r = Var::new("r", 0);
  let v_x = Var::new("x", 0);
  let v_y = Var::new("y", 0);
  let v_0 = Var::new("0", 0);
  let v_1 = Var::new("1", 0);
  let v_nat = Var::new("nat", 0);
  let v_and = Var::new("and", 0);
  let v_or = Var::new("or", 0);
  let v_xor = Var::new("xor", 0);
  let v_not = Var::new("not", 0);
  let unused = Var::new("", 0);

  let ty_bool = constant(Const::Data);
  println!("bool : {}.", ty_bool.to_string());
  let ty_true = var(&v_bool);
  println!("true : {}.", ty_true.to_string());
  let ty_false = var(&v_bool);
  println!("false : {}.", ty_false.to_string());
  let ty_if = lam(unused.clone(),
                  var(&v_bool),
                  pi(v_r.clone(),
                     constant(Const::Data),
                     lam(unused.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_r)))));
  println!("if : {}.", ty_if.to_string());
  println!("");

  let impl_bool = pi(v_r.clone(),
                     constant(Const::Data),
                     lam(unused.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_r))));
  println!("bool = {}.", impl_bool.to_string());
  let impl_true = pi(v_r.clone(),
                     constant(Const::Data),
                     lam(v_x.clone(),
                         var(&v_r),
                         lam(unused.clone(), var(&v_r), var(&v_x))));
  println!("true = {}.", impl_true.to_string());
  let impl_false = pi(v_r.clone(),
                      constant(Const::Data),
                      lam(unused.clone(),
                          var(&v_r),
                          lam(v_y.clone(), var(&v_r), var(&v_y))));
  println!("false = {}.", impl_false.to_string());
  let impl_if = lam(v_b.clone(), var(&v_bool), var(&v_b));
  println!("if = {}.", impl_if.to_string());
  println!("");

  let if_true = lam(v_bool.clone(),
                    ty_bool.clone(),
                    lam(v_true.clone(),
                        ty_true.clone(),
                        lam(v_false.clone(),
                            ty_false.clone(),
                            lam(v_if.clone(),
                                ty_if.clone(),
                                app(app(app(app(var(&v_if),
                                                var(&v_true)),
                                            var(&v_nat)),
                                        var(&v_1)),
                                    var(&v_0))))));
  println!("{}", if_true.to_string());

  let program = if_true;
  let execute = app(app(app(app(program, impl_bool.clone()),
                            impl_true.clone()),
                        impl_false.clone()),
                    impl_if.clone());
  println!("{}", execute.to_string());

  let result = execute.normalize();
  println!("= {}", result.to_string());
  println!("");

  let p2 = lam(v_false.clone(),
               ty_false.clone(),
               app(app(app(var(&v_false), var(&v_nat)), var(&v_1)), var(&v_0)));
  println!("{}", p2.to_string());

  let r2 = app(p2, impl_false.clone());
  println!("{}", r2.to_string());
  println!("= {}", r2.normalize().to_string());
  println!("");

  let ty_and = lam(unused.clone(),
                   var(&v_bool),
                   lam(unused.clone(), var(&v_bool), var(&v_bool)));
  println!("and : {}.", ty_and.to_string());
  let impl_and = lam(v_x.clone(),
                     var(&v_bool),
                     lam(v_y.clone(),
                         var(&v_bool),
                         app(app(app(app(var(&v_if), var(&v_x)),
                                     var(&v_bool)),
                                 var(&v_y)),
                             var(&v_false))));
  println!("and = {}.", impl_and.to_string());
  println!("");

  let and_prog = lam(v_and.clone(),
                     ty_and.clone(),
                     app(app(var(&v_and), var(&v_true)), var(&v_false)));
  let and_prog_app = app(and_prog.clone(), impl_and.clone());
  println!("{}", and_prog_app.to_string());

  let ctx_bool_with_and = app(app(app(app(lam(v_bool.clone(),
                                              ty_bool.clone(),
                                              lam(v_true.clone(),
                                                  ty_true.clone(),
                                                  lam(v_false.clone(),
                                                      ty_false.clone(),
                                                      lam(v_if.clone(),
                                                          ty_if.clone(),
                                                          and_prog_app)))),
                                          impl_bool.clone()),
                                      impl_true.clone()),
                                  impl_false.clone()),
                              impl_if.clone());
  println!("{}", ctx_bool_with_and.to_string());
  println!("and true false = {}.", ctx_bool_with_and.normalize().to_string());
  println!("");
}
<|endoftext|>


<commit_before>extern crate getopts;

mod trtable;

use getopts::Options;
use std::env;
use trtable::TrTable;

/// Permutes over a single term's possible alternate characters
///
fn permute(index: usize, term: &str, built: String, trtab: &TrTable) {
  // base case
  if index == term.len() {
    println!("{}", built);
    return;
  }

  let c: char = term.chars()
    .nth(index)
    .expect("");

  let list = trtab.get(c);
  if list == None {
    // just add on the next string to the built and keep going
    let mut new_built: String = (&built).to_string();
    new_built.push(c);
    permute(index + 1, &term, new_built, &trtab);
  } else {
    // go through all of the possibilities
    let u_list = list.unwrap();
    for append in u_list {
      let new_built: String = (&built).to_string() + append;
      permute(index + 1, &term, new_built, &trtab);
    }
  }
}

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

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

  let mut opts = Options::new();
  opts.optopt("p", "permute", "permute over a term with similar letters. Use the -t option to specify a table file",
    "TERM");
  opts.optopt("t", "trtab", "translation table file, in YAML format. Required with the -p option.", "FILENAME");
  opts.optflag("h", "help", "print this menu");
  let matches = match opts.parse(&args[1..]) {
    Ok(m) => { m },
    Err(f) => { panic!(f.to_string()) },
  };

  if matches.opt_present("h") {
    // print help and exit
    print_usage(&program, opts);
    return;
  }

  let table_file = matches.opt_str("t");

  // permutation
  if let Some(permute_str) = matches.opt_str("p") {
    match table_file {
      Some(trtab_fname) => {
        // load the file
        let trtab = TrTable::load(&trtab_fname)
          .ok()
          .unwrap();
        permute(0, &permute_str, "".to_string(), &trtab);
      },
      None => println!("You must specify a table file with the permute option")
    }
  }
}
<commit_msg>Add iteration of all combinations of N length<commit_after>extern crate getopts;
extern crate char_iter;

mod trtable;

use getopts::Options;
use std::env;
use trtable::TrTable;

/// Permutes over a single term's possible alternate characters
///
fn permute(index: usize, term: &str, built: String, trtab: &TrTable) {
  // base case
  if index == term.len() {
    println!("{}", built);
    return;
  }

  let c: char = term.chars()
    .nth(index)
    .expect("");

  let list = trtab.get(c);
  if list == None {
    // just add on the next string to the built and keep going
    let mut new_built: String = (&built).to_string();
    new_built.push(c);
    permute(index + 1, &term, new_built, &trtab);
  } else {
    // go through all of the possibilities
    let u_list = list.unwrap();
    for append in u_list {
      let new_built: String = (&built).to_string() + append;
      permute(index + 1, &term, new_built, &trtab);
    }
  }
}

fn all_combos(chars: &Vec<char>, count: usize, built: String) {
  // base case
  if count == 0 {
    println!("{}", built);
    return;
  }

  for letter in chars {
    let mut new_built: String = (&built).to_string();
    new_built.push(*letter);
    all_combos(&chars, count - 1, new_built);
  }
}

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

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

  let mut opts = Options::new();
  opts.optopt("c", "combos", "iterate through all possible printable combinations of N letters. You may specify a comma separated list, e.g. 1,2,4,5",
    "N");
  opts.optflag("", "no-upper", "specific to -c. If this flag is set, all combinations will omit upper case letters.");
  opts.optflag("", "no-lower", "specific to -c. If this flag is set, all combinations will omit lower case letters.");
  opts.optflag("", "no-numbers", "specific to -c. If this flag is set, all combinations will omit numbers.");
  opts.optflag("", "no-symbols", "specific to -c. If this flag is set, all combinations will omit symbols.");
  opts.optopt("p", "permute", "permute over a term with similar letters. Use the -t option to specify a table file",
    "TERM");
  opts.optopt("t", "trtab", "translation table file, in YAML format. Required with the -p option.", "FILENAME");
  opts.optflag("h", "help", "print this menu");
  let matches = match opts.parse(&args[1..]) {
    Ok(m) => { m },
    Err(f) => { panic!(f.to_string()) },
  };

  if matches.opt_present("h") {
    // print help and exit
    print_usage(&program, opts);
    return;
  }

  let table_file = matches.opt_str("t");

  // permutation
  if let Some(permute_str) = matches.opt_str("p") {
    match table_file {
      Some(trtab_fname) => {
        // load the file
        let trtab = TrTable::load(&trtab_fname)
          .ok()
          .unwrap();
        permute(0, &permute_str, "".to_string(), &trtab);
      },
      None => println!("You must specify a table file with the permute option")
    }
  // all combinations
  } else if let Some(combos) = matches.opt_str("c") {
    let counts = combos.split(",")
      .map(|n| n.parse::<usize>().unwrap());

    let mut all_chars = Vec::new();
    // upper case letters
    if !matches.opt_present("no-upper") {
      for l in char_iter::new('\x41', '\x5a') {
        all_chars.push(l);
      }
    }
    // lower case letters
    if !matches.opt_present("no-lower") {
      for l in char_iter::new('\x61', '\x7a') {
        all_chars.push(l);
      }
    }
    // numbers
    if !matches.opt_present("no-numbers") {
      for l in char_iter::new('\x30', '\x39') {
        all_chars.push(l);
      }
    }
    // symbols
    if !matches.opt_present("no-symbols") {
      // <space> to /
      for l in char_iter::new('\x20', '\x2F') {
        all_chars.push(l);
      }
      // : to @
      for l in char_iter::new('\x3a', '\x40') {
        all_chars.push(l);
      }
      // [ to `
      for l in char_iter::new('\x5b', '\x60') {
        all_chars.push(l);
      }
      // { to ~
      for l in char_iter::new('\x7b', '\x7e') {
        all_chars.push(l);
      }
    }

    for n in counts {
      all_combos(&all_chars, n, String::new());
    }
  }
}
<|endoftext|>


<commit_before>extern crate trousers;
extern crate newt;

use std::io;
use std::str::FromStr;
use trousers::*;
use std::ffi::CString;

fn read_pcr_as_str(tpm: &TssTPM, pcr_index: u32) -> Result<String, TssResult> {
    let mut s = String::new();
    let vec = try!(tpm.pcr_read(pcr_index));
    s.push_str(std::str::from_utf8(format!("PCR {:02}", pcr_index).as_bytes()).unwrap());
    for j in 0..vec.len() {
        if j % 4 == 0 {
            s.push_str(" ");
        }
        s.push_str(std::str::from_utf8(format!("{:02x}", vec[j]).as_bytes()).unwrap());
    }
    s.push_str("\n");
    Ok(s)
}

fn show_view_pcrs(tpm: &TssTPM) -> Result<(), TssResult> {
    newt::centered_window(80, 30, "View PCRs");
    let form = newt::form(None, None, 0);
    for i in 0..24 {
        let pcr_str = try!(read_pcr_as_str(tpm, i));
        let pcr_label = newt::label(1, 1+(i as i32), &*pcr_str);
        newt::form_add_component(form, pcr_label);
    }
    let button = newt::button(1, 26, "OK");
    newt::form_add_component(form, button);
    newt::run_form(form);
    newt::form_destroy(form);
    Ok(())
}

fn show_extend_pcr(tpm: &TssTPM) -> Result<(), TssResult> {
    loop {
        newt::centered_window(80, 30, "Extend PCR");
        let form = newt::form(None, None, 0);
        let entry = newt::entry(1, 1, None, 10, 0);
        newt::form_add_component(form, entry);
        let ok_button = newt::button(1, 26, "OK");
        let cancel_button = newt::button(10, 26, "Cancel");
        newt::form_add_component(form, ok_button);
        newt::form_add_component(form, cancel_button);

        if newt::run_form(form) == ok_button {
            let string = newt::entry_get_value(entry);
            let parsed = string.parse::<u32>();

            if let Ok(to_extend) = parsed {
                let old_pcr_str = try!(read_pcr_as_str(tpm, to_extend));
                try!(tpm.pcr_extend(to_extend, b"abcdefghijklmnopqrst"));
                let new_pcr_str = try!(read_pcr_as_str(tpm, to_extend));
                newt::centered_window(60, 10, "Success");
                let form = newt::form(None, None, 0);
                let old_label = newt::label(0, 0, "Old value:");
                let old_text = newt::label(0, 1, &*old_pcr_str);
                let new_label = newt::label(0, 2, "New value:");
                let new_text = newt::label(0, 3, &*new_pcr_str);
                let button = newt::button(1, 5, "OK");
                newt::form_add_component(form, old_label);
                newt::form_add_component(form, old_text);
                newt::form_add_component(form, new_label);
                newt::form_add_component(form, new_text);
                newt::form_add_component(form, button);
                newt::run_form(form);
                newt::form_destroy(form);
                return Ok(());
            } else {
                show_error("Not an integer");
            }
        } else {
            newt::form_destroy(form);
            return Ok(());
        }
    }
}

fn show_reset_pcr(tpm: &TssTPM) -> Result<(), TssResult> {
    loop {
        newt::centered_window(80, 30, "Reset PCR");
        let form = newt::form(None, None, 0);
        let entry = newt::entry(1, 1, None, 10, 0);
        newt::form_add_component(form, entry);
        let ok_button = newt::button(1, 26, "OK");
        let cancel_button = newt::button(10, 26, "Cancel");
        newt::form_add_component(form, ok_button);
        newt::form_add_component(form, cancel_button);

        if newt::run_form(form) == ok_button {
            let string = newt::entry_get_value(entry);
            let parsed = string.parse::<u32>();

            if let Ok(to_reset) = parsed {
                let old_pcr_str = try!(read_pcr_as_str(tpm, to_reset));
                let pcrs = try!(tpm.context.create_pcr_composite_info_long());
                try!(pcrs.select_pcr_index_ex(to_reset, 1));
                try!(tpm.pcr_reset(&pcrs));
                let new_pcr_str = try!(read_pcr_as_str(tpm, to_reset));
                newt::centered_window(60, 10, "Success");
                let form = newt::form(None, None, 0);
                let old_label = newt::label(0, 0, "Old value:");
                let old_text = newt::label(0, 1, &*old_pcr_str);
                let new_label = newt::label(0, 2, "New value:");
                let new_text = newt::label(0, 3, &*new_pcr_str);
                let button = newt::button(1, 5, "OK");
                newt::form_add_component(form, old_label);
                newt::form_add_component(form, old_text);
                newt::form_add_component(form, new_label);
                newt::form_add_component(form, new_text);
                newt::form_add_component(form, button);
                newt::run_form(form);
                newt::form_destroy(form);
                return Ok(());
            } else {
                show_error("Not an integer");
            }
        } else {
            newt::form_destroy(form);
            return Ok(());
        }
    }
}

fn show_error(message: &str) {
    show_message("Error", message);
}

fn show_message(title: &str, message: &str) {
    newt::centered_window(60, 10, title);
    let form = newt::form(None, None, 0);
    let label = newt::label(0, 0, message);
    newt::form_add_component(form, label);
    let button = newt::button(1, 5, "OK");
    newt::form_add_component(form, button);
    newt::run_form(form);
    newt::form_destroy(form);
}

fn show_menu(tpm: &TssTPM) {
    loop {
        newt::centered_window(80, 30, "Menu");
        let form = newt::form(None, None, 0);
        let listbox = newt::listbox(0, 0, 30, newt::NEWT_FLAG_RETURNEXIT);
        newt::listbox_append_entry(listbox, "View PCRs", 0);
        newt::listbox_append_entry(listbox, "Extend PCR", 1);
        newt::listbox_append_entry(listbox, "Reset PCR", 2);
        newt::listbox_append_entry(listbox, "Exit", 3);
        newt::form_add_component(form, listbox);
        newt::run_form(form);
        newt::form_destroy(form);
        let result = newt::listbox_get_current(listbox);
        if result == 0 {
            show_view_pcrs(tpm);
        } else if result == 1 {
            show_extend_pcr(tpm);
        } else if result == 2 {
            show_reset_pcr(tpm);
        } else if result == 3 {
            return;
        }
    }
}

fn main() {
    newt::init();
    newt::cls();
    newt::draw_root_text(0, 0, "Some root text");
    newt::centered_window(80, 30, "View PCRs");
    // TODO: Any cleaner way to write this?
    let contextresult = TssContext::new();
    if let Ok(context) = contextresult {
        if let Ok(_) = context.connect() {
            if let Ok(tpm) = context.get_tpm_object() {
                show_menu(&tpm);
            } else {
                println!("Failed to get TPM handle :(")
            }
        } else {
            println!("Failed to connect :(");
        }
    } else {
        println!("Failed :(");
    }

    newt::finished();
}
<commit_msg>Reorganise main.rs<commit_after>extern crate trousers;
extern crate newt;

use std::io;
use std::str::FromStr;
use trousers::*;
use std::ffi::CString;

fn main() {
    newt::init();
    newt::cls();
    newt::draw_root_text(0, 0, "Some root text");
    newt::centered_window(80, 30, "View PCRs");
    // TODO: Any cleaner way to write this?
    let contextresult = TssContext::new();
    if let Ok(context) = contextresult {
        if let Ok(_) = context.connect() {
            if let Ok(tpm) = context.get_tpm_object() {
                show_menu(&tpm);
            } else {
                println!("Failed to get TPM handle :(")
            }
        } else {
            println!("Failed to connect :(");
        }
    } else {
        println!("Failed :(");
    }

    newt::finished();
}

fn show_menu(tpm: &TssTPM) {
    loop {
        newt::centered_window(80, 30, "Menu");
        let form = newt::form(None, None, 0);
        let listbox = newt::listbox(0, 0, 30, newt::NEWT_FLAG_RETURNEXIT);
        newt::listbox_append_entry(listbox, "View PCRs", 0);
        newt::listbox_append_entry(listbox, "Extend PCR", 1);
        newt::listbox_append_entry(listbox, "Reset PCR", 2);
        newt::listbox_append_entry(listbox, "Exit", 3);
        newt::form_add_component(form, listbox);
        newt::run_form(form);
        newt::form_destroy(form);
        let result = newt::listbox_get_current(listbox);
        if result == 0 {
            show_view_pcrs(tpm);
        } else if result == 1 {
            show_extend_pcr(tpm);
        } else if result == 2 {
            show_reset_pcr(tpm);
        } else if result == 3 {
            return;
        }
    }
}

fn show_view_pcrs(tpm: &TssTPM) -> Result<(), TssResult> {
    newt::centered_window(80, 30, "View PCRs");
    let form = newt::form(None, None, 0);
    for i in 0..24 {
        let pcr_str = try!(read_pcr_as_str(tpm, i));
        let pcr_label = newt::label(1, 1+(i as i32), &*pcr_str);
        newt::form_add_component(form, pcr_label);
    }
    let button = newt::button(1, 26, "OK");
    newt::form_add_component(form, button);
    newt::run_form(form);
    newt::form_destroy(form);
    Ok(())
}

fn show_extend_pcr(tpm: &TssTPM) -> Result<(), TssResult> {
    loop {
        newt::centered_window(80, 30, "Extend PCR");
        let form = newt::form(None, None, 0);
        let entry = newt::entry(1, 1, None, 10, 0);
        newt::form_add_component(form, entry);
        let ok_button = newt::button(1, 26, "OK");
        let cancel_button = newt::button(10, 26, "Cancel");
        newt::form_add_component(form, ok_button);
        newt::form_add_component(form, cancel_button);

        if newt::run_form(form) == ok_button {
            let string = newt::entry_get_value(entry);
            let parsed = string.parse::<u32>();

            if let Ok(to_extend) = parsed {
                let old_pcr_str = try!(read_pcr_as_str(tpm, to_extend));
                try!(tpm.pcr_extend(to_extend, b"abcdefghijklmnopqrst"));
                let new_pcr_str = try!(read_pcr_as_str(tpm, to_extend));
                newt::centered_window(60, 10, "Success");
                let form = newt::form(None, None, 0);
                let old_label = newt::label(0, 0, "Old value:");
                let old_text = newt::label(0, 1, &*old_pcr_str);
                let new_label = newt::label(0, 2, "New value:");
                let new_text = newt::label(0, 3, &*new_pcr_str);
                let button = newt::button(1, 5, "OK");
                newt::form_add_component(form, old_label);
                newt::form_add_component(form, old_text);
                newt::form_add_component(form, new_label);
                newt::form_add_component(form, new_text);
                newt::form_add_component(form, button);
                newt::run_form(form);
                newt::form_destroy(form);
                return Ok(());
            } else {
                show_error("Not an integer");
            }
        } else {
            newt::form_destroy(form);
            return Ok(());
        }
    }
}

fn show_reset_pcr(tpm: &TssTPM) -> Result<(), TssResult> {
    loop {
        newt::centered_window(80, 30, "Reset PCR");
        let form = newt::form(None, None, 0);
        let entry = newt::entry(1, 1, None, 10, 0);
        newt::form_add_component(form, entry);
        let ok_button = newt::button(1, 26, "OK");
        let cancel_button = newt::button(10, 26, "Cancel");
        newt::form_add_component(form, ok_button);
        newt::form_add_component(form, cancel_button);

        if newt::run_form(form) == ok_button {
            let string = newt::entry_get_value(entry);
            let parsed = string.parse::<u32>();

            if let Ok(to_reset) = parsed {
                let old_pcr_str = try!(read_pcr_as_str(tpm, to_reset));
                let pcrs = try!(tpm.context.create_pcr_composite_info_long());
                try!(pcrs.select_pcr_index_ex(to_reset, 1));
                try!(tpm.pcr_reset(&pcrs));
                let new_pcr_str = try!(read_pcr_as_str(tpm, to_reset));
                newt::centered_window(60, 10, "Success");
                let form = newt::form(None, None, 0);
                let old_label = newt::label(0, 0, "Old value:");
                let old_text = newt::label(0, 1, &*old_pcr_str);
                let new_label = newt::label(0, 2, "New value:");
                let new_text = newt::label(0, 3, &*new_pcr_str);
                let button = newt::button(1, 5, "OK");
                newt::form_add_component(form, old_label);
                newt::form_add_component(form, old_text);
                newt::form_add_component(form, new_label);
                newt::form_add_component(form, new_text);
                newt::form_add_component(form, button);
                newt::run_form(form);
                newt::form_destroy(form);
                return Ok(());
            } else {
                show_error("Not an integer");
            }
        } else {
            newt::form_destroy(form);
            return Ok(());
        }
    }
}

fn show_error(message: &str) {
    show_message("Error", message);
}

fn show_message(title: &str, message: &str) {
    newt::centered_window(60, 10, title);
    let form = newt::form(None, None, 0);
    let label = newt::label(0, 0, message);
    newt::form_add_component(form, label);
    let button = newt::button(1, 5, "OK");
    newt::form_add_component(form, button);
    newt::run_form(form);
    newt::form_destroy(form);
}

fn read_pcr_as_str(tpm: &TssTPM, pcr_index: u32) -> Result<String, TssResult> {
    let mut s = String::new();
    let vec = try!(tpm.pcr_read(pcr_index));
    s.push_str(std::str::from_utf8(format!("PCR {:02}", pcr_index).as_bytes()).unwrap());
    for j in 0..vec.len() {
        if j % 4 == 0 {
            s.push_str(" ");
        }
        s.push_str(std::str::from_utf8(format!("{:02x}", vec[j]).as_bytes()).unwrap());
    }
    s.push_str("\n");
    Ok(s)
}
<|endoftext|>


<commit_before>// See LICENSE file for copyright and license details.

#[macro_use]
extern crate glium;

extern crate time;
extern crate image;
extern crate cgmath;

#[cfg(target_os = "android")]
extern crate android_glue;

mod fs;

use std::path::{Path};
use std::f32::consts::{PI};
use std::thread;
use std::time::Duration;
use glium::{glutin, Texture2d, DisplayBuild, Surface};
use glium::index::PrimitiveType;
use glium::glutin::ElementState::{Released};
use cgmath::{Matrix4, Matrix3, Vector3, Rad};

const FPS: u64 = 60;

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

implement_vertex!(Vertex, position, tex_coords);

fn load_texture<P: AsRef<Path>>(display: &glium::Display, path: P) -> Texture2d {
    let f = fs::load(path);
    let image = image::load(f, image::PNG).unwrap().to_rgba();
    let image_dimensions = image.dimensions();
    let image = glium::texture::RawImage2d::from_raw_rgba(
        image.into_raw(), image_dimensions);
    Texture2d::new(display, image).unwrap()
}

fn make_program(display: &glium::Display) -> glium::Program {
    let api = display.get_window().unwrap().get_api();
    let pre_src = fs::load_string(match api {
        glutin::Api::OpenGl => "pre_gl.glsl",
        glutin::Api::OpenGlEs => "pre_gles.glsl",
        _ => unimplemented!(),
    });
    let vs_src = pre_src.clone() + &fs::load_string("vs.glsl");
    let fs_src = pre_src + &fs::load_string("fs.glsl");
    glium::Program::from_source(display, &vs_src, &fs_src, None).unwrap()
}

fn view_matrix(angle_x: Rad<f32>, angle_y: Rad<f32>, aspect: f32) -> Matrix4<f32> {
    let perspective_mat = cgmath::perspective(Rad::new(PI / 4.0), aspect, 0.1, 100.0);
    let tr_mat = Matrix4::from_translation(Vector3{x: 0.0, y: 0.0, z: -10.0});
    let angle_x_m = Matrix4::from(Matrix3::from_angle_z(angle_x));
    let angle_y_m = Matrix4::from(Matrix3::from_angle_x(angle_y));
    perspective_mat * tr_mat * angle_y_m * angle_x_m
}

fn create_display() -> glium::Display {
    let gl_version = glutin::GlRequest::GlThenGles {
        opengles_version: (2, 0),
        opengl_version: (2, 1),
    };
    glutin::WindowBuilder::new()
        .with_gl(gl_version)
        .with_depth_buffer(24)
        .with_title("Nergal".to_string())
        .build_glium()
        .unwrap()
}

struct Visualizer {
    display: glium::Display,
    program: glium::Program,
    is_running: bool,
    accumulator: u64,
    previous_clock: u64,
    vertex_buffer: glium::VertexBuffer<Vertex>,
    index_buffer: glium::IndexBuffer<u16>,
    texture: Texture2d,
    camera_angle_x: Rad<f32>,
    camera_angle_y: Rad<f32>,
    aspect: f32,
}

impl Visualizer {
    fn new() -> Visualizer {
        let display = create_display();
        let program = make_program(&display);
        let aspect = {
            let window = display.get_window().unwrap();
            let (x, y) = window.get_inner_size().unwrap();
            x as f32 / y as f32
        };
        let vertex_buffer = {
            let vertices = [
                Vertex { position: [-0.5, -0.5, 0.0], tex_coords: [0.0, 1.0] },
                Vertex { position: [-0.5,  0.5, 0.0], tex_coords: [0.0, 0.0] },
                Vertex { position: [ 0.5, -0.5, 0.0], tex_coords: [1.0, 1.0] },
                Vertex { position: [ 0.5,  0.5, 0.0], tex_coords: [1.0, 0.0] },
            ];
            glium::VertexBuffer::new(&display, &vertices).unwrap()
        };
        let index_buffer = glium::IndexBuffer::new(
            &display, PrimitiveType::TrianglesList, &[0u16, 1, 2, 1, 2, 3]).unwrap();
        let texture = load_texture(&display, "test.png");
        let accumulator = 0;
        let previous_clock = time::precise_time_ns();
        Visualizer {
            display: display,
            program: program,
            is_running: true,
            accumulator: accumulator,
            previous_clock: previous_clock,
            vertex_buffer: vertex_buffer,
            index_buffer: index_buffer,
            texture: texture,
            camera_angle_x: Rad::new(0.0),
            camera_angle_y: Rad::new(0.0),
            aspect: aspect,
        }
    }

    fn is_running(&self) -> bool {
        self.is_running
    }

    fn handle_events(&mut self) {
        let rotate_step = PI / 12.0;
        let events: Vec<_> = self.display.poll_events().collect();
        for event in events {
            match event {
                glutin::Event::Resized(x, y) => {
                    self.aspect = x as f32 / y as f32;
                },
                glutin::Event::Closed => {
                    self.is_running = false;
                },
                glutin::Event::KeyboardInput(Released, _, Some(key)) => {
                    match key {
                        glutin::VirtualKeyCode::Q
                            | glutin::VirtualKeyCode::Escape =>
                        {
                            self.is_running = false;
                        },
                        glutin::VirtualKeyCode::Right => self.camera_angle_x.s += rotate_step,
                        glutin::VirtualKeyCode::Left => self.camera_angle_x.s -= rotate_step,
                        glutin::VirtualKeyCode::Down => self.camera_angle_y.s += rotate_step,
                        glutin::VirtualKeyCode::Up => self.camera_angle_y.s -= rotate_step,
                        _ => {},
                    }
                },
                _ => (),
            }
        }
    }

    fn draw(&self) {
        let view_mat: [[f32; 4]; 4] = view_matrix(
            self.camera_angle_x, self.camera_angle_y, self.aspect).into();
        let uniforms = uniform! {
            view_mat: view_mat,
            texture: &self.texture,
        };
        let mut target = self.display.draw();
        target.clear_color(0.0, 0.0, 0.0, 0.0);
        target.draw(
            &self.vertex_buffer,
            &self.index_buffer,
            &self.program,
            &uniforms,
            &Default::default(),
        ).unwrap();
        target.finish().unwrap();
    }

    fn update_timer(&mut self) {
        let fixed_time_stamp = 1_000_000_000 / FPS;
        let now = time::precise_time_ns();
        self.accumulator += now - self.previous_clock;
        self.previous_clock = now;
        while self.accumulator >= fixed_time_stamp {
            self.accumulator -= fixed_time_stamp;
            // TODO: update realtime state here
        }
        let remainder_ms = (fixed_time_stamp - self.accumulator) / 1_000_000;
        thread::sleep(Duration::from_millis(remainder_ms));
    }
}

fn main() {
    std::env::set_var("RUST_BACKTRACE", "1");
    let mut visualizer = Visualizer::new();
    while visualizer.is_running() {
        visualizer.draw();
        visualizer.handle_events();
        visualizer.update_timer();
    }
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<commit_msg>Implemented cursor rotation<commit_after>// See LICENSE file for copyright and license details.

#[macro_use]
extern crate glium;

extern crate time;
extern crate image;
extern crate cgmath;

#[cfg(target_os = "android")]
extern crate android_glue;

mod fs;

use std::path::{Path};
use std::f32::consts::{PI};
use std::thread;
use std::time::Duration;
use glium::{glutin, Texture2d, DisplayBuild, Surface};
use glium::index::PrimitiveType;
use glium::glutin::ElementState::{Pressed, Released};
use cgmath::{Matrix4, Matrix3, Vector3, Vector2, Rad};

const FPS: u64 = 60;

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

implement_vertex!(Vertex, position, tex_coords);

fn load_texture<P: AsRef<Path>>(display: &glium::Display, path: P) -> Texture2d {
    let f = fs::load(path);
    let image = image::load(f, image::PNG).unwrap().to_rgba();
    let image_dimensions = image.dimensions();
    let image = glium::texture::RawImage2d::from_raw_rgba(
        image.into_raw(), image_dimensions);
    Texture2d::new(display, image).unwrap()
}

fn make_program(display: &glium::Display) -> glium::Program {
    let api = display.get_window().unwrap().get_api();
    let pre_src = fs::load_string(match api {
        glutin::Api::OpenGl => "pre_gl.glsl",
        glutin::Api::OpenGlEs => "pre_gles.glsl",
        _ => unimplemented!(),
    });
    let vs_src = pre_src.clone() + &fs::load_string("vs.glsl");
    let fs_src = pre_src + &fs::load_string("fs.glsl");
    glium::Program::from_source(display, &vs_src, &fs_src, None).unwrap()
}

fn view_matrix(angle_x: Rad<f32>, angle_y: Rad<f32>, aspect: f32) -> Matrix4<f32> {
    let perspective_mat = cgmath::perspective(Rad::new(PI / 4.0), aspect, 0.1, 100.0);
    let tr_mat = Matrix4::from_translation(Vector3{x: 0.0, y: 0.0, z: -10.0});
    let angle_x_m = Matrix4::from(Matrix3::from_angle_z(angle_x));
    let angle_y_m = Matrix4::from(Matrix3::from_angle_x(angle_y));
    perspective_mat * tr_mat * angle_y_m * angle_x_m
}

fn win_size(display: &glium::Display) -> (u32, u32) {
    let window = display.get_window().unwrap();
    window.get_inner_size().unwrap()
}

fn aspect(display: &glium::Display) -> f32 {
    let (x, y) = win_size(display);
    x as f32 / y as f32
}

fn create_display() -> glium::Display {
    let gl_version = glutin::GlRequest::GlThenGles {
        opengles_version: (2, 0),
        opengl_version: (2, 1),
    };
    glutin::WindowBuilder::new()
        .with_gl(gl_version)
        .with_depth_buffer(24)
        .with_title("Nergal".to_string())
        .build_glium()
        .unwrap()
}

struct Visualizer {
    display: glium::Display,
    program: glium::Program,
    is_running: bool,
    accumulator: u64,
    previous_clock: u64,
    vertex_buffer: glium::VertexBuffer<Vertex>,
    index_buffer: glium::IndexBuffer<u16>,
    texture: Texture2d,
    camera_angle_x: Rad<f32>,
    camera_angle_y: Rad<f32>,
    aspect: f32,
    mouse_pos: Vector2<i32>,
    is_lmb_pressed: bool,
}

impl Visualizer {
    fn new() -> Visualizer {
        let display = create_display();
        let program = make_program(&display);
        let aspect = aspect(&display);
        let vertex_buffer = {
            let vertices = [
                Vertex { position: [-0.5, -0.5, 0.0], tex_coords: [0.0, 1.0] },
                Vertex { position: [-0.5,  0.5, 0.0], tex_coords: [0.0, 0.0] },
                Vertex { position: [ 0.5, -0.5, 0.0], tex_coords: [1.0, 1.0] },
                Vertex { position: [ 0.5,  0.5, 0.0], tex_coords: [1.0, 0.0] },
            ];
            glium::VertexBuffer::new(&display, &vertices).unwrap()
        };
        let index_buffer = glium::IndexBuffer::new(
            &display, PrimitiveType::TrianglesList, &[0u16, 1, 2, 1, 2, 3]).unwrap();
        let texture = load_texture(&display, "test.png");
        let accumulator = 0;
        let previous_clock = time::precise_time_ns();
        Visualizer {
            display: display,
            program: program,
            is_running: true,
            accumulator: accumulator,
            previous_clock: previous_clock,
            vertex_buffer: vertex_buffer,
            index_buffer: index_buffer,
            texture: texture,
            camera_angle_x: Rad::new(0.0),
            camera_angle_y: Rad::new(0.0),
            aspect: aspect,
            mouse_pos: Vector2{x: 0, y: 0},
            is_lmb_pressed: false,
        }
    }

    fn is_running(&self) -> bool {
        self.is_running
    }

    fn handle_events(&mut self) {
        self.aspect = aspect(&self.display);
        let rotate_step = PI / 12.0;
        let events: Vec<_> = self.display.poll_events().collect();
        for event in events {
            match event {
                glutin::Event::Resized(x, y) => {
                    self.aspect = x as f32 / y as f32;
                },
                glutin::Event::Closed => {
                    self.is_running = false;
                },
                glutin::Event::KeyboardInput(Released, _, Some(key)) => {
                    match key {
                        glutin::VirtualKeyCode::Q
                            | glutin::VirtualKeyCode::Escape =>
                        {
                            self.is_running = false;
                        },
                        glutin::VirtualKeyCode::Right => self.camera_angle_x.s += rotate_step,
                        glutin::VirtualKeyCode::Left => self.camera_angle_x.s -= rotate_step,
                        glutin::VirtualKeyCode::Down => self.camera_angle_y.s += rotate_step,
                        glutin::VirtualKeyCode::Up => self.camera_angle_y.s -= rotate_step,
                        _ => {},
                    }
                },
                glutin::Event::MouseMoved(x, y) => {
                    self.handle_mouse_move(Vector2{x: x, y: y});
                },
                glutin::Event::MouseInput(Pressed, glutin::MouseButton::Left) => {
                    self.is_lmb_pressed = true;
                },
                glutin::Event::MouseInput(Released, glutin::MouseButton::Left) => {
                    self.is_lmb_pressed = false;
                },
                glutin::Event::Touch(glutin::Touch{location: (x, y), phase, ..}) => {
                    let pos = Vector2{x: x as i32, y: y as i32};
                    match phase {
                        glutin::TouchPhase::Moved => {
                            self.handle_mouse_move(pos);
                        },
                        glutin::TouchPhase::Started => {
                            self.is_lmb_pressed = true;
                            self.mouse_pos = pos;
                        },
                        glutin::TouchPhase::Ended => {
                            self.mouse_pos = pos;
                            self.is_lmb_pressed = false;
                        },
                        glutin::TouchPhase::Cancelled => unimplemented!(),
                    }
                },
                _ => (),
            }
        }
    }

    fn handle_mouse_move(&mut self, pos: Vector2<i32>) {
        let diff = self.mouse_pos - pos;
        self.mouse_pos = pos;
        if self.is_lmb_pressed {
            let (w, h) = win_size(&self.display);
            self.camera_angle_x.s += PI * (diff.x as f32 / w as f32);
            self.camera_angle_y.s += PI * (diff.y as f32 / h as f32);
        }
    }

    fn draw(&self) {
        let view_mat: [[f32; 4]; 4] = view_matrix(
            self.camera_angle_x, self.camera_angle_y, self.aspect).into();
        let uniforms = uniform! {
            view_mat: view_mat,
            texture: &self.texture,
        };
        let mut target = self.display.draw();
        target.clear_color(0.0, 0.0, 0.0, 0.0);
        target.draw(
            &self.vertex_buffer,
            &self.index_buffer,
            &self.program,
            &uniforms,
            &Default::default(),
        ).unwrap();
        target.finish().unwrap();
    }

    fn update_timer(&mut self) {
        let fixed_time_stamp = 1_000_000_000 / FPS;
        let now = time::precise_time_ns();
        self.accumulator += now - self.previous_clock;
        self.previous_clock = now;
        while self.accumulator >= fixed_time_stamp {
            self.accumulator -= fixed_time_stamp;
            // TODO: update realtime state here
        }
        let remainder_ms = (fixed_time_stamp - self.accumulator) / 1_000_000;
        thread::sleep(Duration::from_millis(remainder_ms));
    }
}

fn main() {
    std::env::set_var("RUST_BACKTRACE", "1");
    let mut visualizer = Visualizer::new();
    while visualizer.is_running() {
        visualizer.draw();
        visualizer.handle_events();
        visualizer.update_timer();
    }
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<|endoftext|>


<commit_before>use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

type Payload = i32;
type Message = (Payload, Sender<Payload>);

fn main() {
    let (tx, rx): (Sender<Message>, Receiver<Message>) = mpsc::channel();

    // Create a new thread
    let handle = thread::Builder::new()
        .name("actor".into())
        .spawn(move || {
            let (tx1, rx1): (Sender<Payload>, Receiver<Payload>) = mpsc::channel();
            tx.send((42, tx1)).unwrap();
            let num = rx1.recv().unwrap();
            println!("Got: {:?}", num);
        })
        .unwrap();

    let (num, tx1) = rx.recv().unwrap();
    tx1.send(num+1).unwrap();
    handle.join().unwrap();
}
<commit_msg>Comments and a cleaner channel<commit_after>// MSPC == 'multiple sender, single receiver'
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;

type Payload = i32;
type Message = (Payload, Sender<Payload>);

fn main() {
    // Actor Mailbox
    let (outbox, inbox): (Sender<Message>, Receiver<Message>) = mpsc::channel();

    // Create a new thread
    let handle = thread::Builder::new()
        .name("actor".into())
        .spawn(move || {
            // Forever...
            loop {
                // See if we have messages!
                match inbox.recv() {
                    // If we're given a 'special' -1 value, exit.
                    Ok((num, _)) if num == -1 => {
                        println!("[Actor] Exiting!");
                        break;
                    }
                    // Otherwise, print and respond to the message!
                    Ok((num, sender)) => {
                        println!("[Actor] Got: {:?}", num);
                        sender.send(num + 1).unwrap();
                    }
                    // Exit on error
                    Err(e) => {
                        println!("[Actor] Error: {:?}", e);
                        break;
                    },
                }
            }

        })
        .unwrap();

    // Communication channel with actor
    let (sender, receiver): (Sender<Payload>, Receiver<Payload>) = mpsc::channel();
    outbox.send((0, sender.clone())).unwrap();
    let num = receiver.recv().unwrap();
    println!("[Main] Got: {:?}", num);

    // Send another number!
    outbox.send((num + 1, sender.clone())).unwrap();
    let num = receiver.recv().unwrap();
    println!("[Main] Got: {:?}", num);

    // Send exit code
    outbox.send((-1, sender.clone())).unwrap();

    // Wait for thread to exit
    let res = handle.join().unwrap();
    println!("[Main] Res: {:?}", res);
}
<|endoftext|>


<commit_before>extern crate time;

use std::process::{Command, exit, ExitStatus};
use std::env;
use time::PreciseTime;
use std::thread::sleep;
use std::time::Duration;

#[cfg(unix)]
use std::os::unix::process::ExitStatusExt ;

#[cfg(unix)]
fn signal(status: &ExitStatus) -> Option<i32> { status.signal() }
#[cfg(not(unix))]
fn signal(_: &ExitStatus) -> Option<i32> { None }

fn main() {
    let arguments: Vec<_> = env::args().collect();
    if arguments.len() < 2 {
        println!("Usage: totalrecall <cmd ...>");
        exit(-1);
    }

    loop {
        let start = PreciseTime::now();
        match Command::new(&arguments[1])
                .args(&arguments[2..])
                .status() {
            Err(err) => {
                println!("Error running {:?}: {}", &arguments, err);
                exit(-1);
            },
            Ok(status) if status.success() => exit(0),
            Ok(status) => {
                if let Some(signum) = signal(&status) {
                    println!("totalrecall: {} exited with signal({}), exiting",
                            arguments[1], signum);
                    exit(-1);
                }

                if let Some(code) = status.code() {
                    if let Ok(elapsed) = start.to(PreciseTime::now()).to_std() {
		        if elapsed.as_secs() < 2 {
                            sleep(Duration::from_secs(1))
		        }
                        println!("totalrecall: After {}s {} exited with code({}), restarting",
                                elapsed.as_secs(),
                                arguments[1], code);
                    } else {
                        println!("totalrecall: {} exited with code({}), restarting",
                                arguments[1], code);
                    }
                } else {
                    println!("totalrecall: {} terminated", arguments[1]);
                    exit(-1);
                }
            }
        };
    }
}
<commit_msg>Cleanup: rustfmt<commit_after>extern crate time;

use std::process::{Command, exit, ExitStatus};
use std::env;
use time::PreciseTime;
use std::thread::sleep;
use std::time::Duration;

#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;

#[cfg(unix)]
fn signal(status: &ExitStatus) -> Option<i32> {
    status.signal()
}
#[cfg(not(unix))]
fn signal(_: &ExitStatus) -> Option<i32> {
    None
}

fn main() {
    let arguments: Vec<_> = env::args().collect();
    if arguments.len() < 2 {
        println!("Usage: totalrecall <cmd ...>");
        exit(-1);
    }

    loop {
        let start = PreciseTime::now();
        match Command::new(&arguments[1])
                  .args(&arguments[2..])
                  .status() {
            Err(err) => {
                println!("Error running {:?}: {}", &arguments, err);
                exit(-1);
            }
            Ok(status) if status.success() => exit(0),
            Ok(status) => {
                if let Some(signum) = signal(&status) {
                    println!("totalrecall: \"{}\" exited with signal({}), exiting",
                             arguments[1],
                             signum);
                    exit(-1);
                }

                if let Some(code) = status.code() {
                    if let Ok(elapsed) = start.to(PreciseTime::now()).to_std() {
                        if elapsed.as_secs() < 2 {
                            sleep(Duration::from_secs(1))
                        }
                        println!("totalrecall: After {}s \"{}\" exited with code({}), restarting",
                                 elapsed.as_secs(),
                                 arguments[1],
                                 code);
                    } else {
                        println!("totalrecall: \"{}\" exited with code({}), restarting",
                                 arguments[1],
                                 code);
                    }
                } else {
                    println!("totalrecall: \"{}\" terminated", arguments[1]);
                    exit(-1);
                }
            }
        };
    }
}
<|endoftext|>


<commit_before>#![feature(slice_patterns)]
#![feature(custom_attribute)]
#![feature(nll)]
#![cfg_attr(test, feature(plugin))]
// #![cfg_attr(test, plugin(quickcheck_macros))]

extern crate num;
extern crate rug;

extern crate toml;

#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate lyon;

extern crate euclid;
#[macro_use]
extern crate maplit;
extern crate itertools;

// #[cfg(test)]
// #[macro_use]
// extern crate quickcheck;

mod defs;
mod math;

mod mesh_collector;
mod mesh_gen;

mod delta;
mod draw_delta;

mod camera;
mod gamestate;
mod director;
mod polyomino;
mod shape;

mod load_universe;

use std::env;

use gfx_core::Device;
use gfx_window_glutin as gfx_glutin;
use glutin::GlContext;

use euclid::TypedSize2D;

use defs::*;
use director::*;
use math::*;
use shape::*;

const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

fn universe_filename() -> String {
    let first_argument = std::env::args().nth(1);

    match first_argument {
        Some(name) => name,
        None => "universe/minimal.toml".to_string()
    }
}

pub fn main() {
    let mut events_loop = glutin::EventsLoop::new();
    let resolution = TypedSize2D::new(1024, 768);
    let builder = glutin::WindowBuilder::new()
        .with_title("Abyme".to_string())
        .with_dimensions(resolution.width, resolution.height);
    let context = glutin::ContextBuilder::new().with_vsync(true);

    let (window, mut device, mut factory, mut main_color_view, mut main_depth) =
        gfx_glutin::init::<ColorFormat, DepthFormat>(builder, context, &events_loop);
    let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into();

    let logical_state = load_universe::load_universe(universe_filename());

    let mut director: Director<_> = Director::new(&mut factory, logical_state, resolution);

    let mut last_time = std::time::Instant::now();

    let mut running = true;
    while running {
        events_loop.poll_events(|e| {
            use glutin::WindowEvent::*;
            if let glutin::Event::WindowEvent { event, .. } = e {
                match event {
                    CloseRequested => {
                        running = false;
                    }

                    Resized(w, h) => {
                        gfx_glutin::update_views(&window, &mut main_color_view, &mut main_depth);
                        director.resolution = TypedSize2D::new(w, h);
                        // TODO: recalculate camera
                    }

                    KeyboardInput {
                        input:
                            glutin::KeyboardInput {
                                virtual_keycode: Some(key),
                                state: glutin::ElementState::Pressed,
                                ..
                            },
                        ..
                    } => {
                        use glutin::VirtualKeyCode::*;
                        match key {
                            Escape => running = false,
                            Space => director.game_state.do_zoom(),
                            Up => director.game_state.try_start_move(Direction::Up),
                            Down => director.game_state.try_start_move(Direction::Down),
                            Left => director.game_state.try_start_move(Direction::Left),
                            Right => director.game_state.try_start_move(Direction::Right),
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        });

        encoder.clear(&main_color_view, BLACK);
        director.draw(&mut encoder, &main_color_view);
        encoder.flush(&mut device);
        window.swap_buffers().unwrap();
        device.cleanup();

        let delta = std::time::Instant::now().duration_since(last_time);
        last_time = std::time::Instant::now();

        director.game_state.update(delta);
    }
}
<commit_msg>Add missing pragma<commit_after>#![feature(slice_patterns)]
#![feature(custom_attribute)]
#![feature(nll)]
#![feature(stmt_expr_attributes)]
#![cfg_attr(test, feature(plugin))]
// #![cfg_attr(test, plugin(quickcheck_macros))]

extern crate num;
extern crate rug;

extern crate toml;

#[macro_use]
extern crate gfx;
extern crate gfx_core;
extern crate gfx_window_glutin;
extern crate glutin;
extern crate lyon;

extern crate euclid;
#[macro_use]
extern crate maplit;
extern crate itertools;

// #[cfg(test)]
// #[macro_use]
// extern crate quickcheck;

mod defs;
mod math;

mod mesh_collector;
mod mesh_gen;

mod delta;
mod draw_delta;

mod camera;
mod gamestate;
mod director;
mod polyomino;
mod shape;

mod load_universe;

use std::env;

use gfx_core::Device;
use gfx_window_glutin as gfx_glutin;
use glutin::GlContext;

use euclid::TypedSize2D;

use defs::*;
use director::*;
use math::*;
use shape::*;

const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

fn universe_filename() -> String {
    let first_argument = std::env::args().nth(1);

    match first_argument {
        Some(name) => name,
        None => "universe/minimal.toml".to_string()
    }
}

pub fn main() {
    let mut events_loop = glutin::EventsLoop::new();
    let resolution = TypedSize2D::new(1024, 768);
    let builder = glutin::WindowBuilder::new()
        .with_title("Abyme".to_string())
        .with_dimensions(resolution.width, resolution.height);
    let context = glutin::ContextBuilder::new().with_vsync(true);

    let (window, mut device, mut factory, mut main_color_view, mut main_depth) =
        gfx_glutin::init::<ColorFormat, DepthFormat>(builder, context, &events_loop);
    let mut encoder: gfx::Encoder<_, _> = factory.create_command_buffer().into();

    let logical_state = load_universe::load_universe(universe_filename());

    let mut director: Director<_> = Director::new(&mut factory, logical_state, resolution);

    let mut last_time = std::time::Instant::now();

    let mut running = true;
    while running {
        events_loop.poll_events(|e| {
            use glutin::WindowEvent::*;
            if let glutin::Event::WindowEvent { event, .. } = e {
                match event {
                    CloseRequested => {
                        running = false;
                    }

                    Resized(w, h) => {
                        gfx_glutin::update_views(&window, &mut main_color_view, &mut main_depth);
                        director.resolution = TypedSize2D::new(w, h);
                        // TODO: recalculate camera
                    }

                    KeyboardInput {
                        input:
                            glutin::KeyboardInput {
                                virtual_keycode: Some(key),
                                state: glutin::ElementState::Pressed,
                                ..
                            },
                        ..
                    } => {
                        use glutin::VirtualKeyCode::*;
                        match key {
                            Escape => running = false,
                            Space => director.game_state.do_zoom(),
                            Up => director.game_state.try_start_move(Direction::Up),
                            Down => director.game_state.try_start_move(Direction::Down),
                            Left => director.game_state.try_start_move(Direction::Left),
                            Right => director.game_state.try_start_move(Direction::Right),
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        });

        encoder.clear(&main_color_view, BLACK);
        director.draw(&mut encoder, &main_color_view);
        encoder.flush(&mut device);
        window.swap_buffers().unwrap();
        device.cleanup();

        let delta = std::time::Instant::now().duration_since(last_time);
        last_time = std::time::Instant::now();

        director.game_state.update(delta);
    }
}
<|endoftext|>


<commit_before>#[derive(Clone, Copy, Debug)]
enum Const {
  Data,
  Codata,
}

impl ToString for Const {
  fn to_string(&self) -> String {
    use Const::*;
    match *self {
      Data => "data".to_string(),
      Codata => "codata".to_string(),
    }
  }
}

#[derive(Clone, Debug)]
struct Var {
  name: String,
  idx: i32,
}

impl Var {
  pub fn new(name: &str, idx: i32) -> Var {
    Var {
      name: name.to_string(),
      idx: idx,
    }
  }
}

fn v(name: &str, idx: i32) -> Var {
  Var::new(name, idx)
}

fn v0(name: &str) -> Var {
  v(name, 0)
}

impl ToString for Var {
  fn to_string(&self) -> String {
    self.name.clone()
    // + "@" + &self.idx.to_string()
  }
}

#[derive(Clone, Debug)]
enum Expr {
  // Type system constants
  Const(Const),
  // Bound variables
  Var(Var),
  // Lambda
  Lam(Var, Box<Expr>, Box<Expr>),
  // "forall"
  Pi(Var, Box<Expr>, Box<Expr>),
  // Function application
  App(Box<Expr>, Box<Expr>),
}

impl Expr {
  pub fn constant(constant: Const) -> Expr {
    Expr::Const(constant)
  }
  pub fn var(v: &Var) -> Expr {
    Expr::Var(v.clone())
  }
  pub fn lam(var: Var, ty: Expr, body: Expr) -> Expr {
    Expr::Lam(var, Box::new(ty), Box::new(body))
  }
  pub fn pi(var: Var, ty: Expr, body: Expr) -> Expr {
    Expr::Pi(var, Box::new(ty), Box::new(body))
  }
  pub fn app(f: Expr, arg: Expr) -> Expr {
    Expr::App(Box::new(f), Box::new(arg))
  }

  pub fn is_constant(&self) -> bool {
    use Expr::*;
    match *self {
      Const(_) => true,
      _ => false,
    }
  }
  pub fn is_var(&self) -> bool {
    use Expr::*;
    match *self {
      Var(_) => true,
      _ => false,
    }
  }
  pub fn is_lam(&self) -> bool {
    use Expr::*;
    match *self {
      Lam(_, _, _) => true,
      _ => false,
    }
  }
  pub fn is_pi(&self) -> bool {
    use Expr::*;
    match *self {
      Pi(_, _, _) => true,
      _ => false,
    }
  }
  pub fn is_app(&self) -> bool {
    use Expr::*;
    match *self {
      App(_, _) => true,
      _ => false,
    }
  }
}

fn constant(c: Const) -> Expr {
  Expr::constant(c)
}
fn var(v: &Var) -> Expr {
  Expr::var(v)
}
fn lam(var: Var, ty: Expr, body: Expr) -> Expr {
  Expr::lam(var, ty, body)
}
fn pi(var: Var, ty: Expr, body: Expr) -> Expr {
  Expr::pi(var, ty, body)
}
fn app(f: Expr, arg: Expr) -> Expr {
  Expr::app(f, arg)
}

impl ToString for Expr {
  fn to_string(&self) -> String {
    use Expr::*;
    match *self {
      Const(ref constant) => constant.to_string(),
      Var(ref var) => var.to_string(),
      Lam(ref var, ref ty, ref body) => {
        var.to_string() + ":" + &ty.to_string() + " -> " + &body.to_string()
      }
      Pi(ref var, ref ty, ref body) => {
        "forall (".to_string() + &var.to_string() + ":" + &ty.to_string() +
        ") -> " + &body.to_string()
      }
      App(ref f, ref arg) => {
        if f.is_lam() || f.is_pi() {
          "(".to_string() + &f.to_string() + ") " + &arg.to_string()
        } else {
          f.to_string() + " " + &arg.to_string()
        }
      }
    }
  }
}

fn main() {
  println!("{}", Const::Data.to_string());
  let a = v("a", 0);
  let x = v("x", 0);
  let expra = var(&a);
  let exprx = var(&x);
  println!("{}", x.to_string());
  let id = pi(a.clone(), constant(Const::Data), lam(x, expra, exprx));
  println!("{}", id.to_string());
  let apply_id = app(app(id, var(&v("int", 0))), var(&v("1", 0)));
  println!("{}", apply_id.to_string());
}
<commit_msg>Shorten var creation.<commit_after>#[derive(Clone, Copy, Debug)]
enum Const {
  Data,
  Codata,
}

impl ToString for Const {
  fn to_string(&self) -> String {
    use Const::*;
    match *self {
      Data => "data".to_string(),
      Codata => "codata".to_string(),
    }
  }
}

#[derive(Clone, Debug)]
struct Var {
  name: String,
  idx: i32,
}

impl Var {
  pub fn new(name: &str, idx: i32) -> Var {
    Var {
      name: name.to_string(),
      idx: idx,
    }
  }
}

fn vn(name: &str, idx: i32) -> Var {
  Var::new(name, idx)
}

fn v(name: &str) -> Var {
  vn(name, 0)
}

impl ToString for Var {
  fn to_string(&self) -> String {
    self.name.clone()
    // + "@" + &self.idx.to_string()
  }
}

#[derive(Clone, Debug)]
enum Expr {
  // Type system constants
  Const(Const),
  // Bound variables
  Var(Var),
  // Lambda
  Lam(Var, Box<Expr>, Box<Expr>),
  // "forall"
  Pi(Var, Box<Expr>, Box<Expr>),
  // Function application
  App(Box<Expr>, Box<Expr>),
}

impl Expr {
  pub fn constant(constant: Const) -> Expr {
    Expr::Const(constant)
  }
  pub fn var(v: &Var) -> Expr {
    Expr::Var(v.clone())
  }
  pub fn lam(var: Var, ty: Expr, body: Expr) -> Expr {
    Expr::Lam(var, Box::new(ty), Box::new(body))
  }
  pub fn pi(var: Var, ty: Expr, body: Expr) -> Expr {
    Expr::Pi(var, Box::new(ty), Box::new(body))
  }
  pub fn app(f: Expr, arg: Expr) -> Expr {
    Expr::App(Box::new(f), Box::new(arg))
  }

  pub fn is_constant(&self) -> bool {
    use Expr::*;
    match *self {
      Const(_) => true,
      _ => false,
    }
  }
  pub fn is_var(&self) -> bool {
    use Expr::*;
    match *self {
      Var(_) => true,
      _ => false,
    }
  }
  pub fn is_lam(&self) -> bool {
    use Expr::*;
    match *self {
      Lam(_, _, _) => true,
      _ => false,
    }
  }
  pub fn is_pi(&self) -> bool {
    use Expr::*;
    match *self {
      Pi(_, _, _) => true,
      _ => false,
    }
  }
  pub fn is_app(&self) -> bool {
    use Expr::*;
    match *self {
      App(_, _) => true,
      _ => false,
    }
  }
}

fn constant(c: Const) -> Expr {
  Expr::constant(c)
}
fn var(v: &Var) -> Expr {
  Expr::var(v)
}
fn lam(var: Var, ty: Expr, body: Expr) -> Expr {
  Expr::lam(var, ty, body)
}
fn pi(var: Var, ty: Expr, body: Expr) -> Expr {
  Expr::pi(var, ty, body)
}
fn app(f: Expr, arg: Expr) -> Expr {
  Expr::app(f, arg)
}

impl ToString for Expr {
  fn to_string(&self) -> String {
    use Expr::*;
    match *self {
      Const(ref constant) => constant.to_string(),
      Var(ref var) => var.to_string(),
      Lam(ref var, ref ty, ref body) => {
        var.to_string() + ":" + &ty.to_string() + " -> " + &body.to_string()
      }
      Pi(ref var, ref ty, ref body) => {
        "forall (".to_string() + &var.to_string() + ":" + &ty.to_string() +
        ") -> " + &body.to_string()
      }
      App(ref f, ref arg) => {
        if f.is_lam() || f.is_pi() {
          "(".to_string() + &f.to_string() + ") " + &arg.to_string()
        } else {
          f.to_string() + " " + &arg.to_string()
        }
      }
    }
  }
}

fn main() {
  println!("{}", Const::Data.to_string());
  let a = v("a");
  let x = v("x");
  let expra = var(&a);
  let exprx = var(&x);
  println!("{}", x.to_string());
  let id = pi(a.clone(), constant(Const::Data), lam(x, expra, exprx));
  println!("{}", id.to_string());
  let apply_id = app(app(id, var(&v("int"))), var(&v("1")));
  println!("{}", apply_id.to_string());
}
<|endoftext|>