<commit_before>// Copyright 2015 The Athena Developers.
//
// 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.

extern crate phosphorus;
extern crate glutin;
extern crate gfx;
extern crate gfx_window_glutin;

use gfx::traits::*;

static HELLO_MARKUP: &'static str = include_str!("hello-markup.jade");

fn main() {
    // Set up our window
    let window = glutin::WindowBuilder::new()
        .with_vsync()
        //.with_srgb(Some(false))
        .with_dimensions(600, 500)
        .with_title(String::from("Hello"))
        .build_strict().unwrap();
    let mut canvas = gfx_window_glutin::init(window).into_canvas();
    canvas.output.set_gamma(gfx::Gamma::Original).unwrap();

    // Set up our phosphorus gui
    let root = phosphorus::widgets::LayoutWidgetBuilder::new()
        .with_background_color([21, 23, 24])
        .with_widget(phosphorus::widgets::TextWidgetBuilder::new()
            .with_text("Hello World!")
            .build_boxed())
        .with_widget(phosphorus::widgets::TextWidgetBuilder::new()
            .with_text("Hello again, World!")
            .build_boxed())
        .with_widget(phosphorus::widgets::ImageWidgetBuilder::new()
            .with_source("./assets/test.png")
            .with_size([200, 200])
            .build_boxed(&mut canvas.factory))
        .build();
    let mut gui = phosphorus::Gui::new(&mut canvas.factory, root);

    'main: loop {
        // Quit when the window is closed
        for event in canvas.output.window.poll_events() {
            match event {
                glutin::Event::Closed => break 'main,
                _ => (),
            }
        }

        // Render our actual GUI
        gui.render(&mut canvas.output, &mut canvas.renderer, &mut canvas.factory);

        // Show the rendered to buffer on the screen
        canvas.present();
    }
}
<commit_msg>Extremely minor change<commit_after>// Copyright 2015 The Athena Developers.
//
// 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.

extern crate phosphorus;
extern crate glutin;
extern crate gfx;
extern crate gfx_window_glutin;

use gfx::traits::*;

static HELLO_MARKUP: &'static str = include_str!("hello-markup.jade");

fn main() {
    // Set up our window
    let window = glutin::WindowBuilder::new()
        .with_vsync()
        .with_dimensions(600, 500)
        .with_title(String::from("Hello"))
        .build_strict().unwrap();
    let mut canvas = gfx_window_glutin::init(window).into_canvas();
    canvas.output.set_gamma(gfx::Gamma::Original).unwrap();

    // Set up our phosphorus gui
    let root = phosphorus::widgets::LayoutWidgetBuilder::new()
        .with_background_color([21, 23, 24])
        .with_widget(phosphorus::widgets::TextWidgetBuilder::new()
            .with_text("Hello World!")
            .build_boxed())
        .with_widget(phosphorus::widgets::TextWidgetBuilder::new()
            .with_text("Hello again, World!")
            .build_boxed())
        .with_widget(phosphorus::widgets::ImageWidgetBuilder::new()
            .with_source("./assets/test.png")
            .with_size([200, 200])
            .build_boxed(&mut canvas.factory))
        .build();
    let mut gui = phosphorus::Gui::new(&mut canvas.factory, root);

    'main: loop {
        // Quit when the window is closed
        for event in canvas.output.window.poll_events() {
            match event {
                glutin::Event::Closed => break 'main,
                _ => (),
            }
        }

        // Render our actual GUI
        gui.render(&mut canvas.output, &mut canvas.renderer, &mut canvas.factory);

        // Show the rendered to buffer on the screen
        canvas.present();
    }
}
<|endoftext|>


<commit_before>extern crate getopts;
#[macro_use]
extern crate modparse_derive;
#[macro_use]
extern crate derive_builder;

#[macro_use]
extern crate torchrs;

use torchrs::autograd::{Variable, VariableArgs, BackwardArgs};
use torchrs::tensor::Tensor;
use torchrs::optim;

use torchrs::macros::*;
use torchrs::nn;
use torchrs::nn::{ModuleStruct, ModIntf, ModDelegate, Module};
use torchrs::nn::functional as F;
use torchrs::utils::data as D;

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

fn MNIST() -> D::Dataset<D::Batch<f32, i64>> {
    unimplemented!()
}

#[derive(Clone, Builder)]
struct NetArgs {
    #[builder(default="64")]
    batch_size: usize,
    #[builder(default="1000")]
    test_batch_size: usize,
    #[builder(default="10")]
    epochs: u32,
    #[builder(default="0.01")]
    lr: f32,
    #[builder(default="0.5")]
    momentum: f32,
    #[builder(default="true")]
    cuda: bool,
    #[builder(default="1")]
    seed: usize,
    #[builder(default="10")]
    log_interval: usize,
}

impl Default for NetArgs {
    fn default() -> Self {
        NetArgsBuilder::default().build().unwrap()
    }
}

fn parse_args() -> NetArgs {
    let cmd_args: Vec<String> = env::args().collect();
    let mut args = NetArgs::default();
    let mut opts = Options::new();
    unimplemented!();
    /*
    	* XXX do parsey stuff
    	*/
    args
}

#[derive(ModParse)]
struct Net<T: Default> {
    delegate: nn::Module<T>,
    conv1: nn::Conv2d<T>,
    conv2: nn::Conv2d<T>,
    fc1: nn::Linear<T>,
    fc2: nn::Linear<T>,
}

impl<T: Default> Net<T> {
    pub fn new() -> Net<T> {
        Net {
                delegate: nn::Module::new(),
                conv1: nn::Conv2d::build(1, 10, (5, 5)).done(),
                conv2: nn::Conv2d::build(10, 20, (5, 5)).done(),
                fc1: nn::Linear::build(320, 50).done(),
                fc2: nn::Linear::build(50, 10).done(),
            }
            .init_module()
    }
}
impl_mod_delegate!(Net);

// The forward operations could take on one of two implementations.
// The first supporting a near verbatim version of the python
// implementation, and the second supporting a slightly more
// idiomatic to Rust method chaining.

// a) as a near verbatim implementation of the python version
impl ModIntf<f32> for Net<f32> {
    fn forward(&mut self, args: &mut Variable<f32>) -> Variable<f32> {
        let training = self.delegate.training;
        let pool_val = F::MaxPool2dArgs::default();
        let dropout_val = F::DropoutArgs::default();
        let mut x = F::relu(&F::max_pool2d(&self.conv1.f(args), (2, 2), &pool_val));
        let mut x = F::relu(&F::max_pool2d(&F::dropout2d(&self.conv2.f(&mut x), &dropout_val),
                                           (2, 2),
                                           &pool_val));
        let mut x = x.view(&[-1, 320]);
        let x = F::relu(&self.fc1.f(&mut x));
        let mut x = F::dropout(&x, &dropout_val);
        let x = self.fc2.f(&mut x);
        F::log_softmax(&x)
    }
}

fn train(model: &mut Net<f32>,
         args: &NetArgs,
         train_loader: &D::BatchLoader<f32, i64>,
         epoch: u32,
         optimizer: &mut optim::OptIntf) {
    model.train();
    for (batch_idx, (ref data, ref target)) in train_loader.iter().enumerate() {
        let (mut data, target) = if args.cuda {
            (Variable::new(data.cuda().clone()), Variable::new(target.cuda().clone()))
        } else {
            (Variable::new(data.clone()), Variable::new(target.clone()))
        };
        optimizer.zero_grad();
        let output = model.f(&mut data);
        let mut loss = F::nll_loss(&output, &target, &F::NLLLossArgs::default());
        loss.backward();
        optimizer.step();
        if batch_idx % args.log_interval == 0 {
            println!("Train Epoch: {} [{}/{} ({:.0}%)]\tLoss: {:.6}",
                     epoch,
                     batch_idx * data.data().len(),
                     train_loader.dataset.len(),
                     100. * (batch_idx as f32) / train_loader.len() as f32,
                     loss.data()[0]);
        }
    }
}

fn test(model: &mut Net<f32>, args: &NetArgs, test_loader: &D::BatchLoader<f32, i64>, epoch: u32) {
    model.eval();
    let mut test_loss = 0.;
    let mut correct = 0;
    for (ref data, ref target) in test_loader.iter() {
        let varargs = VariableArgs {
            volatile: true,
            ..Default::default()
        };
        let (mut data, mut target) = if args.cuda {
            (Variable::new_args(data.cuda().clone(), varargs), Variable::new(target.cuda().clone()))
        } else {
            (Variable::new_args(data.clone(), varargs), Variable::new(target.clone()))
        };
        let mut output = model.f(&mut data);
        test_loss += F::nll_loss(&output, &target, &F::NLLLossArgs::default());
        let pred = output.data().reduce_max(1).1;
        correct += pred.tensor_eq(&*target.data()).cpu().sum();
    }
    test_loss /= test_loader.len() as f32;
    println!("\nTest set: Average loss: {:.4}, Accuracy: {}/{} ({:.0}%)\n",
             test_loss,
             correct,
             test_loader.dataset.len(),
             100. * (correct as f32) / (test_loader.dataset.len() as f32))

}

fn main() {
    // no data loaders yet so demonstrate with Vec placeholder
    let train_loader: D::BatchLoader<f32, i64> = D::DataLoader::new(MNIST(),
                                                                    D::DataLoaderArgs::default());
    let test_loader: D::BatchLoader<f32, i64> = D::DataLoader::new(MNIST(),
                                                                   D::DataLoaderArgs::default());
    let args = parse_args();
    let mut optimizer = optim::SGD::new();

    let mut model = Net::new();
    for epoch in 1..args.epochs + 1 {
        train(&mut model, &args, &train_loader, epoch, &mut optimizer);
        test(&mut model, &args, &test_loader, epoch);
    }
}
<commit_msg>update mnist<commit_after>extern crate getopts;
#[macro_use]
extern crate modparse_derive;
#[macro_use]
extern crate derive_builder;

#[macro_use]
extern crate torchrs;

use torchrs::autograd::{Variable, VariableArgs, VarAccess};
use torchrs::tensor::Tensor;
use torchrs::optim;

use torchrs::macros::*;
use torchrs::nn;
use torchrs::nn::{ModuleStruct, ModIntf, ModDelegate, Module};
use torchrs::nn::functional as F;
use torchrs::utils::data as D;

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

fn MNIST() -> D::Dataset<D::Batch<f32, i64>> {
    unimplemented!()
}

#[derive(Clone, Builder)]
struct NetArgs {
    #[builder(default="64")]
    batch_size: usize,
    #[builder(default="1000")]
    test_batch_size: usize,
    #[builder(default="10")]
    epochs: u32,
    #[builder(default="0.01")]
    lr: f32,
    #[builder(default="0.5")]
    momentum: f32,
    #[builder(default="true")]
    cuda: bool,
    #[builder(default="1")]
    seed: usize,
    #[builder(default="10")]
    log_interval: usize,
}

impl Default for NetArgs {
    fn default() -> Self {
        NetArgsBuilder::default().build().unwrap()
    }
}

fn parse_args() -> NetArgs {
    let cmd_args: Vec<String> = env::args().collect();
    let mut args = NetArgs::default();
    let mut opts = Options::new();
    unimplemented!();
    /*
    	* XXX do parsey stuff
    	*/
    args
}

#[derive(ModParse)]
struct Net<T: Default> {
    delegate: nn::Module<T>,
    conv1: nn::Conv2d<T>,
    conv2: nn::Conv2d<T>,
    fc1: nn::Linear<T>,
    fc2: nn::Linear<T>,
}

impl<T: Default> Net<T> {
    pub fn new() -> Net<T> {
        Net {
                delegate: nn::Module::new(),
                conv1: nn::Conv2d::build(1, 10, (5, 5)).done(),
                conv2: nn::Conv2d::build(10, 20, (5, 5)).done(),
                fc1: nn::Linear::build(320, 50).done(),
                fc2: nn::Linear::build(50, 10).done(),
            }
            .init_module()
    }
}
impl_mod_delegate!(Net);

// The forward operations could take on one of two implementations.
// The first supporting a near verbatim version of the python
// implementation, and the second supporting a slightly more
// idiomatic to Rust method chaining.

// a) as a near verbatim implementation of the python version
impl ModIntf<f32> for Net<f32> {
    fn forward(&mut self, args: &mut Variable<f32>) -> Variable<f32> {
        let training = self.delegate.training;
        let pool_val = F::MaxPool2dArgs::default();
        let dropout_val = F::DropoutArgs::default();
        let mut x = F::relu(&F::max_pool2d(&self.conv1.f(args), (2, 2), &pool_val));
        let mut x = F::relu(&F::max_pool2d(&F::dropout2d(&self.conv2.f(&mut x), &dropout_val),
                                           (2, 2),
                                           &pool_val));
        let mut x = x.view(&[-1, 320]);
        let x = F::relu(&self.fc1.f(&mut x));
        let mut x = F::dropout(&x, &dropout_val);
        let x = self.fc2.f(&mut x);
        F::log_softmax(&x)
    }
}

fn train(model: &mut Net<f32>,
         args: &NetArgs,
         train_loader: &D::BatchLoader<f32, i64>,
         epoch: u32,
         optimizer: &mut optim::OptIntf) {
    model.train();
    for (batch_idx, (ref data, ref target)) in train_loader.iter().enumerate() {
        let (mut data, target) = if args.cuda {
            (Variable::new(data.cuda().clone()), Variable::new(target.cuda().clone()))
        } else {
            (Variable::new(data.clone()), Variable::new(target.clone()))
        };
        optimizer.zero_grad();
        let output = model.f(&mut data);
        let mut loss = F::nll_loss(&output, &target, &F::NLLLossArgs::default());
        loss.backward();
        optimizer.step();
        if batch_idx % args.log_interval == 0 {
            println!("Train Epoch: {} [{}/{} ({:.0}%)]\tLoss: {:.6}",
                     epoch,
                     batch_idx * data.data().len(),
                     train_loader.dataset.len(),
                     100. * (batch_idx as f32) / train_loader.len() as f32,
                     loss.data()[0]);
        }
    }
}

fn test(model: &mut Net<f32>, args: &NetArgs, test_loader: &D::BatchLoader<f32, i64>, epoch: u32) {
    model.eval();
    let mut test_loss = 0.;
    let mut correct = 0;
    for (ref data, ref target) in test_loader.iter() {
        let varargs = VariableArgs {
            volatile: true,
            ..Default::default()
        };
        let (mut data, mut target) = if args.cuda {
            (Variable::new_args(data.cuda().clone(), varargs), Variable::new(target.cuda().clone()))
        } else {
            (Variable::new_args(data.clone(), varargs), Variable::new(target.clone()))
        };
        let mut output = model.f(&mut data);
        test_loss += F::nll_loss(&output, &target, &F::NLLLossArgs::default());
        let pred = output.data().reduce_max(1).1;
        correct += pred.tensor_eq(&*target.data()).cpu().sum();
    }
    test_loss /= test_loader.len() as f32;
    println!("\nTest set: Average loss: {:.4}, Accuracy: {}/{} ({:.0}%)\n",
             test_loss,
             correct,
             test_loader.dataset.len(),
             100. * (correct as f32) / (test_loader.dataset.len() as f32))

}

fn main() {
    // no data loaders yet so demonstrate with Vec placeholder
    let train_loader: D::BatchLoader<f32, i64> = D::DataLoader::new(MNIST(),
                                                                    D::DataLoaderArgs::default());
    let test_loader: D::BatchLoader<f32, i64> = D::DataLoader::new(MNIST(),
                                                                   D::DataLoaderArgs::default());
    let args = parse_args();
    let mut optimizer = optim::SGD::new();

    let mut model = Net::new();
    for epoch in 1..args.epochs + 1 {
        train(&mut model, &args, &train_loader, epoch, &mut optimizer);
        test(&mut model, &args, &test_loader, epoch);
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Common handling of keyboard input and state management for text input controls

use dom::bindings::codegen::Bindings::KeyboardEventBinding::KeyboardEventMethods;
use dom::bindings::js::JSRef;
use dom::keyboardevent::KeyboardEvent;
use servo_util::str::DOMString;

use std::cmp::{min, max};
use std::default::Default;

#[jstraceable]
struct TextPoint {
    /// 0-based line number
    line: uint,
    /// 0-based column number
    index: uint,
}

/// Encapsulated state for handling keyboard input in a single or multiline text input control.
#[jstraceable]
pub struct TextInput {
    /// Current text input content, split across lines without trailing '\n'
    lines: Vec<DOMString>,
    /// Current cursor input point
    edit_point: TextPoint,
    /// Selection range, beginning and end point that can span multiple lines.
    _selection: Option<(TextPoint, TextPoint)>,
    /// Is this a multiline input?
    multiline: bool,
}

/// Resulting action to be taken by the owner of a text input that is handling an event.
pub enum KeyReaction {
    TriggerDefaultAction,
    DispatchInput,
    Nothing,
}

impl Default for TextPoint {
    fn default() -> TextPoint {
        TextPoint {
            line: 0,
            index: 0,
        }
    }
}

/// Control whether this control should allow multiple lines.
#[deriving(PartialEq)]
pub enum Lines {
    Single,
    Multiple,
}

/// The direction in which to delete a character.
#[deriving(PartialEq)]
enum DeleteDir {
    Forward,
    Backward
}

impl TextInput {
    /// Instantiate a new text input control
    pub fn new(lines: Lines, initial: DOMString) -> TextInput {
        let mut i = TextInput {
            lines: vec!(),
            edit_point: Default::default(),
            _selection: None,
            multiline: lines == Multiple,
        };
        i.set_content(initial);
        i
    }

    /// Return the current line under the editing point
    fn get_current_line(&self) -> &DOMString {
        &self.lines[self.edit_point.line]
    }

    /// Insert a character at the current editing point
    fn insert_char(&mut self, ch: char) {
        //TODO: handle replacing selection with character
        let new_line = {
            let prefix = self.get_current_line().as_slice().slice_chars(0, self.edit_point.index);
            let suffix = self.get_current_line().as_slice().slice_chars(self.edit_point.index,
                                                                        self.current_line_length());
            let mut new_line = prefix.to_string();
            new_line.push(ch);
            new_line.push_str(suffix.as_slice());
            new_line
        };

        self.lines[self.edit_point.line] = new_line;
        self.edit_point.index += 1;
    }

    /// Remove a character at the current editing point
    fn delete_char(&mut self, dir: DeleteDir) {
        let forward = dir == Forward;

        //TODO: handle deleting selection
        let prefix_end = if forward {
            self.edit_point.index
        } else {
            if self.multiline {
                //TODO: handle backspacing from position 0 of current line
                if self.edit_point.index == 0 {
                    return;
                }
            } else if self.edit_point.index == 0 {
                return;
            }
            self.edit_point.index - 1
        };
        let suffix_start = if forward {
            let is_eol = self.edit_point.index == self.current_line_length();
            if self.multiline {
                //TODO: handle deleting from end position of current line
                if is_eol {
                    return;
                }
            } else if is_eol {
                return;
            }
            self.edit_point.index + 1
        } else {
            self.edit_point.index
        };

        let new_line = {
            let prefix = self.get_current_line().as_slice().slice_chars(0, prefix_end);
            let suffix = self.get_current_line().as_slice().slice_chars(suffix_start,
                                                                        self.current_line_length());
            let mut new_line = prefix.to_string();
            new_line.push_str(suffix);
            new_line
        };

        self.lines[self.edit_point.line] = new_line;

        if !forward {
            self.adjust_horizontal(-1);
        }
    }

    /// Return the length of the current line under the editing point.
    fn current_line_length(&self) -> uint {
        self.lines[self.edit_point.line].char_len()
    }

    /// Adjust the editing point position by a given of lines. The resulting column is
    /// as close to the original column position as possible.
    fn adjust_vertical(&mut self, adjust: int) {
        if !self.multiline {
            return;
        }

        if adjust < 0 && self.edit_point.line as int + adjust < 0 {
            self.edit_point.index = 0;
            self.edit_point.line = 0;
            return;
        } else if adjust > 0 && self.edit_point.line + adjust as uint >= self.lines.len() {
            self.edit_point.line = self.lines.len() - 1;
            self.edit_point.index = self.current_line_length();
            return;
        }

        self.edit_point.line = (self.edit_point.line as int + adjust) as uint;
        self.edit_point.index = min(self.current_line_length(), self.edit_point.index);
    }

    /// Adjust the editing point position by a given number of columns. If the adjustment
    /// requested is larger than is available in the current line, the editing point is
    /// adjusted vertically and the process repeats with the remaining adjustment requested.
    fn adjust_horizontal(&mut self, adjust: int) {
        if adjust < 0 {
            if self.multiline {
                let remaining = self.edit_point.index;
                if adjust.abs() as uint > remaining {
                    self.edit_point.index = 0;
                    self.adjust_vertical(-1);
                    self.edit_point.index = self.current_line_length();
                    self.adjust_horizontal(adjust + remaining as int);
                } else {
                    self.edit_point.index = (self.edit_point.index as int + adjust) as uint;
                }
            } else {
                self.edit_point.index = max(0, self.edit_point.index as int + adjust) as uint;
            }
        } else {
            if self.multiline {
                let remaining = self.current_line_length() - self.edit_point.index;
                if adjust as uint > remaining {
                    self.edit_point.index = 0;
                    self.adjust_vertical(1);
                    self.adjust_horizontal(adjust - remaining as int);
                } else {
                    self.edit_point.index += adjust as uint;
                }
            } else {
                self.edit_point.index = min(self.current_line_length(),
                                            self.edit_point.index + adjust as uint);
            }
        }
    }

    /// Deal with a newline input.
    fn handle_return(&mut self) -> KeyReaction {
        if !self.multiline {
            return TriggerDefaultAction;
        }

        //TODO: support replacing selection with newline
        let prefix = self.get_current_line().as_slice().slice_chars(0, self.edit_point.index).to_string();
        let suffix = self.get_current_line().as_slice().slice_chars(self.edit_point.index,
                                                                    self.current_line_length()).to_string();
        self.lines[self.edit_point.line] = prefix;
        self.lines.insert(self.edit_point.line + 1, suffix);
        return DispatchInput;
    }

    /// Process a given `KeyboardEvent` and return an action for the caller to execute.
    pub fn handle_keydown(&mut self, event: JSRef<KeyboardEvent>) -> KeyReaction {
        match event.Key().as_slice() {
            // printable characters have single-character key values
            c if c.len() == 1 => {
                self.insert_char(c.char_at(0));
                return DispatchInput;
            }
            "Space" => {
                self.insert_char(' ');
                DispatchInput
            }
            "Delete" => {
                self.delete_char(Forward);
                DispatchInput
            }
            "Backspace" => {
                self.delete_char(Backward);
                DispatchInput
            }
            "ArrowLeft" => {
                self.adjust_horizontal(-1);
                Nothing
            }
            "ArrowRight" => {
                self.adjust_horizontal(1);
                Nothing
            }
            "ArrowUp" => {
                self.adjust_vertical(-1);
                Nothing
            }
            "ArrowDown" => {
                self.adjust_vertical(1);
                Nothing
            }
            "Enter" => self.handle_return(),
            "Home" => {
                self.edit_point.index = 0;
                Nothing
            }
            "End" => {
                self.edit_point.index = self.current_line_length();
                Nothing
            }
            "PageUp" => {
                self.adjust_vertical(-28);
                Nothing
            }
            "PageDown" => {
                self.adjust_vertical(28);
                Nothing
            }
            "Tab" => TriggerDefaultAction,
            _ => Nothing,
        }
    }

    /// Get the current contents of the text input. Multiple lines are joined by \n.
    pub fn get_content(&self) -> DOMString {
        let mut content = "".to_string();
        for (i, line) in self.lines.iter().enumerate() {
            content.push_str(line.as_slice());
            if i < self.lines.len() - 1 {
                content.push('\n');
            }
        }
        content
    }

    /// Set the current contents of the text input. If this is control supports multiple lines,
    /// any \n encountered will be stripped and force a new logical line.
    pub fn set_content(&mut self, content: DOMString) {
        self.lines = if self.multiline {
            content.as_slice().split('\n').map(|s| s.to_string()).collect()
        } else {
            vec!(content)
        };
        self.edit_point.line = min(self.edit_point.line, self.lines.len() - 1);
        self.edit_point.index = min(self.edit_point.index, self.current_line_length() - 1);
    }
}
<commit_msg>Fix bug of TextInput.adjust_horizontal causing stack overflow or wraparound<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Common handling of keyboard input and state management for text input controls

use dom::bindings::codegen::Bindings::KeyboardEventBinding::KeyboardEventMethods;
use dom::bindings::js::JSRef;
use dom::keyboardevent::KeyboardEvent;
use servo_util::str::DOMString;

use std::cmp::{min, max};
use std::default::Default;

#[jstraceable]
struct TextPoint {
    /// 0-based line number
    line: uint,
    /// 0-based column number
    index: uint,
}

/// Encapsulated state for handling keyboard input in a single or multiline text input control.
#[jstraceable]
pub struct TextInput {
    /// Current text input content, split across lines without trailing '\n'
    lines: Vec<DOMString>,
    /// Current cursor input point
    edit_point: TextPoint,
    /// Selection range, beginning and end point that can span multiple lines.
    _selection: Option<(TextPoint, TextPoint)>,
    /// Is this a multiline input?
    multiline: bool,
}

/// Resulting action to be taken by the owner of a text input that is handling an event.
pub enum KeyReaction {
    TriggerDefaultAction,
    DispatchInput,
    Nothing,
}

impl Default for TextPoint {
    fn default() -> TextPoint {
        TextPoint {
            line: 0,
            index: 0,
        }
    }
}

/// Control whether this control should allow multiple lines.
#[deriving(PartialEq)]
pub enum Lines {
    Single,
    Multiple,
}

/// The direction in which to delete a character.
#[deriving(PartialEq)]
enum DeleteDir {
    Forward,
    Backward
}

impl TextInput {
    /// Instantiate a new text input control
    pub fn new(lines: Lines, initial: DOMString) -> TextInput {
        let mut i = TextInput {
            lines: vec!(),
            edit_point: Default::default(),
            _selection: None,
            multiline: lines == Multiple,
        };
        i.set_content(initial);
        i
    }

    /// Return the current line under the editing point
    fn get_current_line(&self) -> &DOMString {
        &self.lines[self.edit_point.line]
    }

    /// Insert a character at the current editing point
    fn insert_char(&mut self, ch: char) {
        //TODO: handle replacing selection with character
        let new_line = {
            let prefix = self.get_current_line().as_slice().slice_chars(0, self.edit_point.index);
            let suffix = self.get_current_line().as_slice().slice_chars(self.edit_point.index,
                                                                        self.current_line_length());
            let mut new_line = prefix.to_string();
            new_line.push(ch);
            new_line.push_str(suffix.as_slice());
            new_line
        };

        self.lines[self.edit_point.line] = new_line;
        self.edit_point.index += 1;
    }

    /// Remove a character at the current editing point
    fn delete_char(&mut self, dir: DeleteDir) {
        let forward = dir == Forward;

        //TODO: handle deleting selection
        let prefix_end = if forward {
            self.edit_point.index
        } else {
            if self.multiline {
                //TODO: handle backspacing from position 0 of current line
                if self.edit_point.index == 0 {
                    return;
                }
            } else if self.edit_point.index == 0 {
                return;
            }
            self.edit_point.index - 1
        };
        let suffix_start = if forward {
            let is_eol = self.edit_point.index == self.current_line_length();
            if self.multiline {
                //TODO: handle deleting from end position of current line
                if is_eol {
                    return;
                }
            } else if is_eol {
                return;
            }
            self.edit_point.index + 1
        } else {
            self.edit_point.index
        };

        let new_line = {
            let prefix = self.get_current_line().as_slice().slice_chars(0, prefix_end);
            let suffix = self.get_current_line().as_slice().slice_chars(suffix_start,
                                                                        self.current_line_length());
            let mut new_line = prefix.to_string();
            new_line.push_str(suffix);
            new_line
        };

        self.lines[self.edit_point.line] = new_line;

        if !forward {
            self.adjust_horizontal(-1);
        }
    }

    /// Return the length of the current line under the editing point.
    fn current_line_length(&self) -> uint {
        self.lines[self.edit_point.line].char_len()
    }

    /// Adjust the editing point position by a given of lines. The resulting column is
    /// as close to the original column position as possible.
    fn adjust_vertical(&mut self, adjust: int) {
        if !self.multiline {
            return;
        }

        if adjust < 0 && self.edit_point.line as int + adjust < 0 {
            self.edit_point.index = 0;
            self.edit_point.line = 0;
            return;
        } else if adjust > 0 && self.edit_point.line + adjust as uint >= self.lines.len() {
            self.edit_point.line = self.lines.len() - 1;
            self.edit_point.index = self.current_line_length();
            return;
        }

        self.edit_point.line = (self.edit_point.line as int + adjust) as uint;
        self.edit_point.index = min(self.current_line_length(), self.edit_point.index);
    }

    /// Adjust the editing point position by a given number of columns. If the adjustment
    /// requested is larger than is available in the current line, the editing point is
    /// adjusted vertically and the process repeats with the remaining adjustment requested.
    fn adjust_horizontal(&mut self, adjust: int) {
        if adjust < 0 {
            let remaining = self.edit_point.index;
            if adjust.abs() as uint > remaining && self.edit_point.line > 0 {
                self.adjust_vertical(-1);
                self.edit_point.index = self.current_line_length();
                self.adjust_horizontal(adjust + remaining as int);
            } else {
                self.edit_point.index = max(0, self.edit_point.index as int + adjust) as uint;
            }
        } else {
            let remaining = self.current_line_length() - self.edit_point.index;
            if adjust as uint > remaining && self.edit_point.line < self.lines.len() - 1 {
                self.edit_point.index = 0;
                self.adjust_vertical(1);
                self.adjust_horizontal(adjust - remaining as int);
            } else {
                self.edit_point.index = min(self.current_line_length(),
                                            self.edit_point.index + adjust as uint);
            }
        }
    }

    /// Deal with a newline input.
    fn handle_return(&mut self) -> KeyReaction {
        if !self.multiline {
            return TriggerDefaultAction;
        }

        //TODO: support replacing selection with newline
        let prefix = self.get_current_line().as_slice().slice_chars(0, self.edit_point.index).to_string();
        let suffix = self.get_current_line().as_slice().slice_chars(self.edit_point.index,
                                                                    self.current_line_length()).to_string();
        self.lines[self.edit_point.line] = prefix;
        self.lines.insert(self.edit_point.line + 1, suffix);
        return DispatchInput;
    }

    /// Process a given `KeyboardEvent` and return an action for the caller to execute.
    pub fn handle_keydown(&mut self, event: JSRef<KeyboardEvent>) -> KeyReaction {
        match event.Key().as_slice() {
            // printable characters have single-character key values
            c if c.len() == 1 => {
                self.insert_char(c.char_at(0));
                return DispatchInput;
            }
            "Space" => {
                self.insert_char(' ');
                DispatchInput
            }
            "Delete" => {
                self.delete_char(Forward);
                DispatchInput
            }
            "Backspace" => {
                self.delete_char(Backward);
                DispatchInput
            }
            "ArrowLeft" => {
                self.adjust_horizontal(-1);
                Nothing
            }
            "ArrowRight" => {
                self.adjust_horizontal(1);
                Nothing
            }
            "ArrowUp" => {
                self.adjust_vertical(-1);
                Nothing
            }
            "ArrowDown" => {
                self.adjust_vertical(1);
                Nothing
            }
            "Enter" => self.handle_return(),
            "Home" => {
                self.edit_point.index = 0;
                Nothing
            }
            "End" => {
                self.edit_point.index = self.current_line_length();
                Nothing
            }
            "PageUp" => {
                self.adjust_vertical(-28);
                Nothing
            }
            "PageDown" => {
                self.adjust_vertical(28);
                Nothing
            }
            "Tab" => TriggerDefaultAction,
            _ => Nothing,
        }
    }

    /// Get the current contents of the text input. Multiple lines are joined by \n.
    pub fn get_content(&self) -> DOMString {
        let mut content = "".to_string();
        for (i, line) in self.lines.iter().enumerate() {
            content.push_str(line.as_slice());
            if i < self.lines.len() - 1 {
                content.push('\n');
            }
        }
        content
    }

    /// Set the current contents of the text input. If this is control supports multiple lines,
    /// any \n encountered will be stripped and force a new logical line.
    pub fn set_content(&mut self, content: DOMString) {
        self.lines = if self.multiline {
            content.as_slice().split('\n').map(|s| s.to_string()).collect()
        } else {
            vec!(content)
        };
        self.edit_point.line = min(self.edit_point.line, self.lines.len() - 1);
        self.edit_point.index = min(self.edit_point.index, self.current_line_length() - 1);
    }
}
<|endoftext|>


<commit_before>extern crate cc;
use cc::ToolFamily::*;

fn main() {
    let mut build = cc::Build::new();
    build.cpp(true);
    let compiler = build.try_get_compiler();
    if compiler.is_ok() && compiler.unwrap().family == Clang {
        build.flag("-std=c++11").cpp_set_stdlib("c++");
    } else {
        build.flag_if_supported("-std=c++14");
    }
    build
        .file("src/wrapper.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_cfg.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_cross.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_glsl.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_hlsl.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_msl.cpp")
        .compile("spirv-cross-rust-wrapper");
}
<commit_msg>Switch to C++14 for clang<commit_after>extern crate cc;
use cc::ToolFamily::*;

fn main() {
    let mut build = cc::Build::new();
    build.cpp(true);
    let compiler = build.try_get_compiler();
    if compiler.is_ok() && compiler.unwrap().family == Clang {
        build.flag("-std=c++14").cpp_set_stdlib("c++");
    } else {
        build.flag_if_supported("-std=c++14");
    }
    build
        .file("src/wrapper.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_cfg.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_cross.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_glsl.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_hlsl.cpp")
        .file("src/vendor/SPIRV-Cross/spirv_msl.cpp")
        .compile("spirv-cross-rust-wrapper");
}
<|endoftext|>


<commit_before>
#![deny(missing_doc)]

//! Example for Rust-Event using expression based design.
//!
//! The idea is to use combinators of events to describe more complex events.
//! An 'Action' is a variant of an event that spans across time.
//! You program the actions like a state machine, controlling how they interact with the world.
//!
//! Assume you have a complete list of the actions.
//! Any event you can construct from these actions has a corresponding `Cursor`.
//! The cursor keeps track of the combinatorial state.
//!
//! This design is useful in environments where all actions can be broken down
//! into simple interacitons while needing complex combinations of those actions.

extern crate debug;

/// Describes an event.
pub enum Event<A> {
    /// An event where some action is performed.
    Action(A),
    /// An event
    Wait(f64),
    /// An event where sub events are happening sequentially.
    Sequence(Vec<Event<A>>),
    /// While an event is executing, run a sequence of events in a loop..
    While(Box<Event<A>>, Vec<Event<A>>),
    /// An event where all sub events happen.
    WhenAll(Vec<Event<A>>),
}

/// Keeps track of an event.
pub enum Cursor<'a, A, S> {
    /// Keeps track of an event where you have a state of an action.
    State(&'a A, S),
    /// Keeps track of an event where you wait and do nothing.
    WaitCursor(f64, f64),
    /// Keeps track of an event where sub events happens sequentially.
    SequenceCursor(&'a Vec<Event<A>>, uint, Box<Cursor<'a, A, S>>),
    /// Keeps track of an event where sub events are repeated sequentially.
    WhileCursor(Box<Cursor<'a, A, S>>, &'a Vec<Event<A>>, uint, Box<Cursor<'a, A, S>>),
    /// Keeps track of an event where all sub events must happen.
    WhenAllCursor(&'a Vec<Event<A>>, Vec<Option<Cursor<'a, A, S>>>),
}

/// Implemented by all actions.
pub trait StartState<S> {
    /// Creates a state from action, which tracks the state.
    fn start_state(&self) -> S;
}

impl<A: StartState<S>, S> Event<A> {
    /// Creates a cursor structure from an event structure.
    ///
    /// The cursor structure keeps track of the state.
    /// You can define your own actions and use the combinations
    /// to create more complex states.
    pub fn to_cursor<'a>(&'a self) -> Cursor<'a, A, S> {
        match *self {
            Action(ref action)
                => State(action, action.start_state()),
            Wait(dt)
                => WaitCursor(dt, 0.0),
            Sequence(ref seq)
                => SequenceCursor(seq, 0, box seq.get(0).to_cursor()),
            While(ref ev, ref rep)
                => WhileCursor(box ev.to_cursor(), rep, 0, box rep.get(0).to_cursor()),
            WhenAll(ref all)
                => WhenAllCursor(all, all.iter().map(|ev| Some(ev.to_cursor())).collect()),
        }
    }
}

impl<'a, A: StartState<S>, S> Cursor<'a, A, S> {
    /// Updates the cursor that tracks an event.
    ///
    /// Returns `None` if the action did not terminate.
    /// or `Some(dt)` that tells how much time is left of the update time.
    pub fn update(
        &mut self,
        dt: f64,
        f: |action: &'a A, state: &S| -> Option<S>
    ) -> Option<f64> {
        match *self {
            State(action, ref mut state) => {
                // Call the function that updates the state.
                match f(action, state) {
                    Some(new_state) => {
                        *state = new_state;
                        None
                    },
                    // Actions are considered instant,
                    // so there is always a full 'dt' left.
                    None => Some(dt),
                }
            },
            WaitCursor(wait_t, ref mut t) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    Some(remaining_dt)
                } else {
                    *t += dt;
                    None
                }
            },
            SequenceCursor(
                seq,
                ref mut i,
                ref mut cursor
            ) => {
                let cur = cursor;
                let mut dt = dt;
                while *i < seq.len() {
                    match cur.update(dt, |action, state| f(action, state)) {
                        None => { break },
                        Some(new_dt) => { dt = new_dt; }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return Some(dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = seq.get(*i).to_cursor();
                }
                None
            },
            WhileCursor(
                ref mut ev_cursor,
                rep,
                ref mut i,
                ref mut cursor
            ) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(dt, |action, state| f(action, state)) {
                    Some(new_dt) => return Some(new_dt),
                    None => {}
                };
                let cur = cursor;
                let mut dt = dt;
                loop {
                    match cur.update(dt, |action, state| f(action, state)) {
                        None => { break },
                        Some(new_dt) => {
                            dt = new_dt;
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = rep.get(*i).to_cursor();
                }
                None
            },
            _ => unimplemented!(),
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////

/// Some test actions.
pub enum TestActions {
    /// Increment accumulator.
    Inc,
    /// Decrement accumulator.
    Dec,
}

impl StartState<()> for TestActions {
    fn start_state(&self) {}
}

// A test state machine that can increment and decrement.
fn exec(mut acc: u32, dt: f64, cursor: &mut Cursor<TestActions, ()>) -> u32 {
    cursor.update(dt, |action, _| {
        match *action {
            Inc => { acc += 1; None },
            Dec => { acc -= 1; None },
        }
    });
    acc
}

// Each action that terminates immediately
// consumes a time of 0.0 seconds.
// This makes it possible to execute one action
// after another without delay or waiting for next update.
fn print_2() {
    let a: u32 = 0;
    let seq = Sequence(vec![Action(Inc), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 0.0, &mut cursor);
    assert_eq!(a, 2);
}

// If you wait the exact amount before to execute an action,
// it will execute. This behavior makes it easy to predict
// when an action will run.
fn wait_sec() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(1.0), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 1.0, &mut cursor);
    assert_eq!(a, 1);
}

// When we execute half the time and then the other half,
// then the action should be executed.
fn wait_half_sec() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(1.0), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 0);
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 1);
}

// A sequence of wait events is the same as one wait event.
fn wait_two_waits() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(0.5), Wait(0.5), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 1.0, &mut cursor);
    assert_eq!(a, 1);
}

// Increase counter ten times.
fn loop_ten_times() {
    let a: u32 = 0;
    let rep = While(box Wait(50.0), vec![Wait(0.5), Action(Inc), Wait(0.5)]);
    let mut cursor = rep.to_cursor();
    let a = exec(a, 10.0, &mut cursor);
    assert_eq!(a, 10);
}

fn main() {
    print_2();
    wait_sec();
    wait_half_sec();
    wait_two_waits();
    loop_ten_times();
}

<commit_msg>Added `WhenAll` to expression example<commit_after>
#![deny(missing_doc)]

//! Example for Rust-Event using expression based design.
//!
//! The idea is to use combinators of events to describe more complex events.
//! An 'Action' is a variant of an event that spans across time.
//! You program the actions like a state machine, controlling how they interact with the world.
//!
//! Assume you have a complete list of the actions.
//! Any event you can construct from these actions has a corresponding `Cursor`.
//! The cursor keeps track of the combinatorial state.
//!
//! This design is useful in environments where all actions can be broken down
//! into simple interacitons while needing complex combinations of those actions.

extern crate debug;

/// Describes an event.
pub enum Event<A> {
    /// An event where some action is performed.
    Action(A),
    /// An event
    Wait(f64),
    /// An event where sub events are happening sequentially.
    Sequence(Vec<Event<A>>),
    /// While an event is executing, run a sequence of events in a loop..
    While(Box<Event<A>>, Vec<Event<A>>),
    /// An event where all sub events happen.
    WhenAll(Vec<Event<A>>),
}

/// Keeps track of an event.
pub enum Cursor<'a, A, S> {
    /// Keeps track of an event where you have a state of an action.
    State(&'a A, S),
    /// Keeps track of an event where you wait and do nothing.
    WaitCursor(f64, f64),
    /// Keeps track of an event where sub events happens sequentially.
    SequenceCursor(&'a Vec<Event<A>>, uint, Box<Cursor<'a, A, S>>),
    /// Keeps track of an event where sub events are repeated sequentially.
    WhileCursor(Box<Cursor<'a, A, S>>, &'a Vec<Event<A>>, uint, Box<Cursor<'a, A, S>>),
    /// Keeps track of an event where all sub events must happen.
    WhenAllCursor(Vec<Option<Cursor<'a, A, S>>>),
}

/// Implemented by all actions.
pub trait StartState<S> {
    /// Creates a state from action, which tracks the state.
    fn start_state(&self) -> S;
}

impl<A: StartState<S>, S> Event<A> {
    /// Creates a cursor structure from an event structure.
    ///
    /// The cursor structure keeps track of the state.
    /// You can define your own actions and use the combinations
    /// to create more complex states.
    pub fn to_cursor<'a>(&'a self) -> Cursor<'a, A, S> {
        match *self {
            Action(ref action)
                => State(action, action.start_state()),
            Wait(dt)
                => WaitCursor(dt, 0.0),
            Sequence(ref seq)
                => SequenceCursor(seq, 0, box seq.get(0).to_cursor()),
            While(ref ev, ref rep)
                => WhileCursor(box ev.to_cursor(), rep, 0, box rep.get(0).to_cursor()),
            WhenAll(ref all)
                => WhenAllCursor(all.iter().map(|ev| Some(ev.to_cursor())).collect()),
        }
    }
}

impl<'a, A: StartState<S>, S> Cursor<'a, A, S> {
    /// Updates the cursor that tracks an event.
    ///
    /// Returns `None` if the action did not terminate.
    /// or `Some(dt)` that tells how much time is left of the update time.
    pub fn update(
        &mut self,
        dt: f64,
        f: |action: &'a A, state: &S| -> Option<S>
    ) -> Option<f64> {
        match *self {
            State(action, ref mut state) => {
                // Call the function that updates the state.
                match f(action, state) {
                    Some(new_state) => {
                        *state = new_state;
                        None
                    },
                    // Actions are considered instant,
                    // so there is always a full 'dt' left.
                    None => Some(dt),
                }
            },
            WaitCursor(wait_t, ref mut t) => {
                if *t + dt >= wait_t {
                    let remaining_dt = *t + dt - wait_t;
                    *t = wait_t;
                    Some(remaining_dt)
                } else {
                    *t += dt;
                    None
                }
            },
            SequenceCursor(
                seq,
                ref mut i,
                ref mut cursor
            ) => {
                let cur = cursor;
                let mut dt = dt;
                while *i < seq.len() {
                    match cur.update(dt, |action, state| f(action, state)) {
                        None => { break },
                        Some(new_dt) => { dt = new_dt; }
                    };
                    *i += 1;
                    // If end of sequence,
                    // return the 'dt' that is left.
                    if *i >= seq.len() { return Some(dt); }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = seq.get(*i).to_cursor();
                }
                None
            },
            WhileCursor(
                ref mut ev_cursor,
                rep,
                ref mut i,
                ref mut cursor
            ) => {
                // If the event terminates, do not execute the loop.
                match ev_cursor.update(dt, |action, state| f(action, state)) {
                    Some(new_dt) => return Some(new_dt),
                    None => {}
                };
                let cur = cursor;
                let mut dt = dt;
                loop {
                    match cur.update(dt, |action, state| f(action, state)) {
                        None => { break },
                        Some(new_dt) => {
                            dt = new_dt;
                        }
                    };
                    *i += 1;
                    // If end of repeated events,
                    // start over from the first one.
                    if *i >= rep.len() { *i = 0; }
                    // Create a new cursor for next event.
                    // Use the same pointer to avoid allocation.
                    **cur = rep.get(*i).to_cursor();
                }
                None
            },
            WhenAllCursor(
                ref mut cursors
            ) => {
                // Get the least delta time left over.
                let mut min_dt = std::f64::MAX_VALUE;
                // Count number of terminated events.
                let mut terminated = 0;
                for cur in cursors.mut_iter() {
                    match *cur {
                        None => terminated += 1,
                        Some(ref mut cur) => {
                            match cur.update(
                                dt,
                                |action, state| f(action, state)
                            ) {
                                None => {},
                                Some(new_dt) => {
                                    min_dt = min_dt.min(new_dt);
                                    terminated += 1;
                                }
                            }
                        }
                    }
                }
                match terminated {
                    // If there are no events, there is a whole 'dt' left.
                    0 if cursors.len() == 0 => Some(dt),
                    // If all events terminated, the least delta time is left.
                    n if cursors.len() == n => Some(min_dt),
                    _ => None
                }
            }
        }
    }
}

/////////////////////////////////////////////////////////////////////////////////

/// Some test actions.
pub enum TestActions {
    /// Increment accumulator.
    Inc,
    /// Decrement accumulator.
    Dec,
}

impl StartState<()> for TestActions {
    fn start_state(&self) {}
}

// A test state machine that can increment and decrement.
fn exec(mut acc: u32, dt: f64, cursor: &mut Cursor<TestActions, ()>) -> u32 {
    cursor.update(dt, |action, _| {
        match *action {
            Inc => { acc += 1; None },
            Dec => { acc -= 1; None },
        }
    });
    acc
}

// Each action that terminates immediately
// consumes a time of 0.0 seconds.
// This makes it possible to execute one action
// after another without delay or waiting for next update.
fn print_2() {
    let a: u32 = 0;
    let seq = Sequence(vec![Action(Inc), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 0.0, &mut cursor);
    assert_eq!(a, 2);
}

// If you wait the exact amount before to execute an action,
// it will execute. This behavior makes it easy to predict
// when an action will run.
fn wait_sec() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(1.0), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 1.0, &mut cursor);
    assert_eq!(a, 1);
}

// When we execute half the time and then the other half,
// then the action should be executed.
fn wait_half_sec() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(1.0), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 0);
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 1);
}

// A sequence of wait events is the same as one wait event.
fn wait_two_waits() {
    let a: u32 = 0;
    let seq = Sequence(vec![Wait(0.5), Wait(0.5), Action(Inc)]);
    let mut cursor = seq.to_cursor();
    let a = exec(a, 1.0, &mut cursor);
    assert_eq!(a, 1);
}

// Increase counter ten times.
fn loop_ten_times() {
    let a: u32 = 0;
    let rep = While(box Wait(50.0), vec![Wait(0.5), Action(Inc), Wait(0.5)]);
    let mut cursor = rep.to_cursor();
    let a = exec(a, 10.0, &mut cursor);
    assert_eq!(a, 10);
}

fn when_all_wait() {
    let a: u32 = 0;
    let all = Sequence(vec![
            // Wait in parallel.
            WhenAll(vec![Wait(0.5), Wait(1.0)]),
            Action(Inc)
        ]);
    let mut cursor = all.to_cursor();
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 0);
    let a = exec(a, 0.5, &mut cursor);
    assert_eq!(a, 1);
}

fn main() {
    print_2();
    wait_sec();
    wait_half_sec();
    wait_two_waits();
    loop_ten_times();
    when_all_wait();
}

<|endoftext|>


<commit_before>
extern crate rand;

// importing
use std::io;
use rand::Rng;

// empty return type defaults to ()
fn main() {
    println!("Guess the number");

    let secret_number = rand::thread_rng().gen_range(1, 100);

    println!("The secret number is {}", secret_number);

    println!("Please input your guess:");

    // let creates a variable binding
    // we create a mutable variable binding
    // :: associated function ( somewhat like static function )
    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed {}", guess);
}
<commit_msg>build successfully<commit_after>
extern crate rand;

// importing
use std::io;
use std::cmp::Ordering;
use rand::Rng;

// empty return type defaults to ()
fn main() {
    println!("Guess the number");

    let secret_number = rand::thread_rng().gen_range(1, 100);

    println!("The secret number is {}", secret_number);

    println!("Please input your guess:");

    // let creates a variable binding
    // we create a mutable variable binding
    // :: associated function ( somewhat like static function )
    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("Failed to read line");

    let guess: u32 = guess.trim().parse()
                        .expect("Please enter a number");

    println!("You guessed {}", guess);

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Too small"),
        Ordering::Greater => println!("Too big"),
        Ordering::Equal => println!("Wel-done!"),
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// the json code is largely unfinished; allow these to silence a bunch of warnings
#![allow(unused_variables)]
#![allow(dead_code)]

use image::{ColorType, save_buffer};
use premultiply::unpremultiply;
use serde_json;
use std::borrow::BorrowMut;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fmt, fs};
use super::CURRENT_FRAME_NUMBER;
use time;
use webrender;
use webrender_traits::*;

enum CachedFont {
    Native(NativeFontHandle),
    Raw(Option<Vec<u8>>, u32, Option<PathBuf>),
}

struct CachedImage {
    width: u32,
    height: u32,
    stride: u32,
    format: ImageFormat,
    bytes: Option<Vec<u8>>,
    path: Option<PathBuf>,
}

pub struct JsonFrameWriter {
    frame_base: PathBuf,
    rsrc_base: PathBuf,
    rsrc_prefix: String,
    next_rsrc_num: u32,
    images: HashMap<ImageKey, CachedImage>,
    fonts: HashMap<FontKey, CachedFont>,

    last_frame_written: u32,

    dl_descriptor: Option<BuiltDisplayListDescriptor>,
    aux_descriptor: Option<AuxiliaryListsDescriptor>,
}

impl JsonFrameWriter {
    pub fn new(path: &Path) -> JsonFrameWriter {
        let mut rsrc_base = path.to_owned();
        rsrc_base.push("res");
        fs::create_dir_all(&rsrc_base).ok();

        let rsrc_prefix = format!("{}", time::get_time().sec);

        JsonFrameWriter {
            frame_base: path.to_owned(),
            rsrc_base: rsrc_base,
            rsrc_prefix: rsrc_prefix,
            next_rsrc_num: 1,
            images: HashMap::new(),
            fonts: HashMap::new(),

            dl_descriptor: None,
            aux_descriptor: None,

            last_frame_written: u32::max_value(),
        }
    }

    pub fn begin_write_display_list(&mut self,
                                    _: &Option<ColorF>,
                                    _: &Epoch,
                                    _: &PipelineId,
                                    _: &LayoutSize,
                                    display_list: &BuiltDisplayListDescriptor,
                                    auxiliary_lists: &AuxiliaryListsDescriptor)
    {
        unsafe {
            if CURRENT_FRAME_NUMBER == self.last_frame_written {
                return;
            }
            self.last_frame_written = CURRENT_FRAME_NUMBER;
        }

        self.dl_descriptor = Some(display_list.clone());
        self.aux_descriptor = Some(auxiliary_lists.clone());
    }

    pub fn finish_write_display_list(&mut self,
                                     frame: u32,
                                     data: &[u8])
    {
        let dl_desc = self.dl_descriptor.take().unwrap();
        let aux_desc = self.aux_descriptor.take().unwrap();

        assert_eq!(data.len(), dl_desc.size() + aux_desc.size() + 4);

        // there's a 4 byte epoch header that we skip
        let dl_data = data[4..dl_desc.size() + 4].to_vec();
        let aux_data = data[dl_desc.size() + 4..].to_vec();

        let dl = BuiltDisplayList::from_data(dl_data, dl_desc);
        let aux = AuxiliaryLists::from_data(aux_data, aux_desc);

        let mut frame_file_name = self.frame_base.clone();
        let current_shown_frame = unsafe { CURRENT_FRAME_NUMBER };
        frame_file_name.push(format!("frame-{}.json", current_shown_frame));

        let mut file = File::create(&frame_file_name).unwrap();

        let items: Vec<&DisplayItem> = dl.all_display_items().iter().collect();
        let s = serde_json::to_string_pretty(&items).unwrap();
        file.write_all(&s.into_bytes()).unwrap();
        file.write_all(b"\n").unwrap();
    }

    fn next_rsrc_paths(prefix: &str, counter: &mut u32, base_path: &Path, base: &str, ext: &str) -> (PathBuf, PathBuf) {
        let mut path_file = base_path.to_owned();
        let mut path = PathBuf::from("res");

        let fstr = format!("{}-{}-{}.{}", prefix, base, counter, ext);
        path_file.push(&fstr);
        path.push(&fstr);

        *counter += 1;

        (path_file, path)
    }

    fn path_for_image(&mut self, key: ImageKey) -> Option<PathBuf> {
        if let Some(ref mut data) = self.images.get_mut(&key) {
            if data.path.is_some() {
                return data.path.clone();
            }
        } else {
            return None;
        };

        // Remove the data to munge it
        let mut data = self.images.remove(&key).unwrap();
        let mut bytes = data.bytes.take().unwrap();
        let (path_file, path) = Self::next_rsrc_paths(&self.rsrc_prefix,
                                                      &mut self.next_rsrc_num,
                                                      &self.rsrc_base,
                                                      "img",
                                                      "png");

        let ok = match data.format {
            ImageFormat::RGB8 => {
                if data.stride == data.width * 3 {
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::RGB(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            ImageFormat::RGBA8 => {
                if data.stride == data.width * 4 {
                    unpremultiply(bytes.as_mut_slice());
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::RGBA(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            ImageFormat::A8 => {
                if data.stride == data.width {
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::Gray(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            _ => { false }
        };

        if !ok {
            println!("Failed to write image with format {:?}, dimensions {}x{}, stride {}",
                     data.format, data.width, data.height, data.stride);
            return None;
        }

        data.path = Some(path.clone());
        // put it back
        self.images.insert(key, data);
        Some(path)
    }
}

impl fmt::Debug for JsonFrameWriter {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "JsonFrameWriter")
    }
}

impl webrender::ApiRecordingReceiver for JsonFrameWriter {
    fn write_msg(&mut self, _: u32, msg: &ApiMsg) {
        match *msg {
            ApiMsg::SetRootPipeline(..) |
            ApiMsg::Scroll(..) |
            ApiMsg::TickScrollingBounce |
            ApiMsg::WebGLCommand(..) => {
            }

            ApiMsg::AddRawFont(ref key, ref bytes, index) => {
                self.fonts.insert(*key, CachedFont::Raw(Some(bytes.clone()), index, None));
            }

            ApiMsg::AddNativeFont(ref key, ref native_font_handle) => {
                self.fonts.insert(*key, CachedFont::Native(native_font_handle.clone()));
            }

            ApiMsg::AddImage(ref key, ref descriptor, ref data, _) => {
                let stride = descriptor.stride.unwrap_or(
                    descriptor.width * descriptor.format.bytes_per_pixel().unwrap()
                );
                let bytes = match *data {
                    ImageData::Raw(ref v) => { (**v).clone() }
                    ImageData::External(_) | ImageData::Blob(_) => { return; }
                };
                self.images.insert(*key, CachedImage {
                    width: descriptor.width,
                    height: descriptor.height,
                    stride: stride,
                    format: descriptor.format,
                    bytes: Some(bytes),
                    path: None,
                });
            }

            ApiMsg::UpdateImage(ref key, descriptor, ref img_data, _dirty_rect) => {
                if let Some(ref mut data) = self.images.get_mut(key) {
                    assert_eq!(data.width, descriptor.width);
                    assert_eq!(data.height, descriptor.height);
                    assert_eq!(data.format, descriptor.format);

                    if let ImageData::Raw(ref bytes) = *img_data {
                        *data.path.borrow_mut() = None;
                        *data.bytes.borrow_mut() = Some((**bytes).clone());
                    } else {
                        // Other existing image types only make sense within the gecko integration.
                        println!("Wrench only supports updating buffer images (ignoring update command).");
                    }
                }
            }

            ApiMsg::DeleteImage(ref key) => {
                self.images.remove(key);
            }

            ApiMsg::SetDisplayList(ref background_color,
                                    ref epoch,
                                    ref pipeline_id,
                                    ref viewport_size,
                                    ref display_list,
                                    ref auxiliary_lists,
                                    _preserve_frame_state) => {
                self.begin_write_display_list(background_color,
                                              epoch,
                                              pipeline_id,
                                              viewport_size,
                                              display_list,
                                              auxiliary_lists);
            }
            _ => {}
        }
    }

    fn write_payload(&mut self, frame: u32, data: &[u8]) {
        if self.dl_descriptor.is_some() {
            self.finish_write_display_list(frame, data);
        }
    }
}
<commit_msg>make JSON frame writer use proper payload API<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// the json code is largely unfinished; allow these to silence a bunch of warnings
#![allow(unused_variables)]
#![allow(dead_code)]

use image::{ColorType, save_buffer};
use premultiply::unpremultiply;
use serde_json;
use std::borrow::BorrowMut;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{fmt, fs};
use super::CURRENT_FRAME_NUMBER;
use time;
use webrender;
use webrender_traits::*;
use webrender_traits::channel::Payload;

enum CachedFont {
    Native(NativeFontHandle),
    Raw(Option<Vec<u8>>, u32, Option<PathBuf>),
}

struct CachedImage {
    width: u32,
    height: u32,
    stride: u32,
    format: ImageFormat,
    bytes: Option<Vec<u8>>,
    path: Option<PathBuf>,
}

pub struct JsonFrameWriter {
    frame_base: PathBuf,
    rsrc_base: PathBuf,
    rsrc_prefix: String,
    next_rsrc_num: u32,
    images: HashMap<ImageKey, CachedImage>,
    fonts: HashMap<FontKey, CachedFont>,

    last_frame_written: u32,

    dl_descriptor: Option<BuiltDisplayListDescriptor>,
    aux_descriptor: Option<AuxiliaryListsDescriptor>,
}

impl JsonFrameWriter {
    pub fn new(path: &Path) -> JsonFrameWriter {
        let mut rsrc_base = path.to_owned();
        rsrc_base.push("res");
        fs::create_dir_all(&rsrc_base).ok();

        let rsrc_prefix = format!("{}", time::get_time().sec);

        JsonFrameWriter {
            frame_base: path.to_owned(),
            rsrc_base: rsrc_base,
            rsrc_prefix: rsrc_prefix,
            next_rsrc_num: 1,
            images: HashMap::new(),
            fonts: HashMap::new(),

            dl_descriptor: None,
            aux_descriptor: None,

            last_frame_written: u32::max_value(),
        }
    }

    pub fn begin_write_display_list(&mut self,
                                    _: &Option<ColorF>,
                                    _: &Epoch,
                                    _: &PipelineId,
                                    _: &LayoutSize,
                                    display_list: &BuiltDisplayListDescriptor,
                                    auxiliary_lists: &AuxiliaryListsDescriptor)
    {
        unsafe {
            if CURRENT_FRAME_NUMBER == self.last_frame_written {
                return;
            }
            self.last_frame_written = CURRENT_FRAME_NUMBER;
        }

        self.dl_descriptor = Some(display_list.clone());
        self.aux_descriptor = Some(auxiliary_lists.clone());
    }

    pub fn finish_write_display_list(&mut self,
                                     frame: u32,
                                     data: &[u8])
    {
        let payload = Payload::from_data(data);
        let dl_desc = self.dl_descriptor.take().unwrap();
        let aux_desc = self.aux_descriptor.take().unwrap();

        let dl = BuiltDisplayList::from_data(payload.display_list_data, dl_desc);
        let aux = AuxiliaryLists::from_data(payload.auxiliary_lists_data, aux_desc);

        let mut frame_file_name = self.frame_base.clone();
        let current_shown_frame = unsafe { CURRENT_FRAME_NUMBER };
        frame_file_name.push(format!("frame-{}.json", current_shown_frame));

        let mut file = File::create(&frame_file_name).unwrap();

        let items: Vec<&DisplayItem> = dl.all_display_items().iter().collect();
        let s = serde_json::to_string_pretty(&items).unwrap();
        file.write_all(&s.into_bytes()).unwrap();
        file.write_all(b"\n").unwrap();
    }

    fn next_rsrc_paths(prefix: &str, counter: &mut u32, base_path: &Path, base: &str, ext: &str) -> (PathBuf, PathBuf) {
        let mut path_file = base_path.to_owned();
        let mut path = PathBuf::from("res");

        let fstr = format!("{}-{}-{}.{}", prefix, base, counter, ext);
        path_file.push(&fstr);
        path.push(&fstr);

        *counter += 1;

        (path_file, path)
    }

    fn path_for_image(&mut self, key: ImageKey) -> Option<PathBuf> {
        if let Some(ref mut data) = self.images.get_mut(&key) {
            if data.path.is_some() {
                return data.path.clone();
            }
        } else {
            return None;
        };

        // Remove the data to munge it
        let mut data = self.images.remove(&key).unwrap();
        let mut bytes = data.bytes.take().unwrap();
        let (path_file, path) = Self::next_rsrc_paths(&self.rsrc_prefix,
                                                      &mut self.next_rsrc_num,
                                                      &self.rsrc_base,
                                                      "img",
                                                      "png");

        let ok = match data.format {
            ImageFormat::RGB8 => {
                if data.stride == data.width * 3 {
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::RGB(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            ImageFormat::RGBA8 => {
                if data.stride == data.width * 4 {
                    unpremultiply(bytes.as_mut_slice());
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::RGBA(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            ImageFormat::A8 => {
                if data.stride == data.width {
                    save_buffer(&path_file, &bytes, data.width, data.height, ColorType::Gray(8)).unwrap();
                    true
                } else {
                    false
                }
            }
            _ => { false }
        };

        if !ok {
            println!("Failed to write image with format {:?}, dimensions {}x{}, stride {}",
                     data.format, data.width, data.height, data.stride);
            return None;
        }

        data.path = Some(path.clone());
        // put it back
        self.images.insert(key, data);
        Some(path)
    }
}

impl fmt::Debug for JsonFrameWriter {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "JsonFrameWriter")
    }
}

impl webrender::ApiRecordingReceiver for JsonFrameWriter {
    fn write_msg(&mut self, _: u32, msg: &ApiMsg) {
        match *msg {
            ApiMsg::SetRootPipeline(..) |
            ApiMsg::Scroll(..) |
            ApiMsg::TickScrollingBounce |
            ApiMsg::WebGLCommand(..) => {
            }

            ApiMsg::AddRawFont(ref key, ref bytes, index) => {
                self.fonts.insert(*key, CachedFont::Raw(Some(bytes.clone()), index, None));
            }

            ApiMsg::AddNativeFont(ref key, ref native_font_handle) => {
                self.fonts.insert(*key, CachedFont::Native(native_font_handle.clone()));
            }

            ApiMsg::AddImage(ref key, ref descriptor, ref data, _) => {
                let stride = descriptor.stride.unwrap_or(
                    descriptor.width * descriptor.format.bytes_per_pixel().unwrap()
                );
                let bytes = match *data {
                    ImageData::Raw(ref v) => { (**v).clone() }
                    ImageData::External(_) | ImageData::Blob(_) => { return; }
                };
                self.images.insert(*key, CachedImage {
                    width: descriptor.width,
                    height: descriptor.height,
                    stride: stride,
                    format: descriptor.format,
                    bytes: Some(bytes),
                    path: None,
                });
            }

            ApiMsg::UpdateImage(ref key, descriptor, ref img_data, _dirty_rect) => {
                if let Some(ref mut data) = self.images.get_mut(key) {
                    assert_eq!(data.width, descriptor.width);
                    assert_eq!(data.height, descriptor.height);
                    assert_eq!(data.format, descriptor.format);

                    if let ImageData::Raw(ref bytes) = *img_data {
                        *data.path.borrow_mut() = None;
                        *data.bytes.borrow_mut() = Some((**bytes).clone());
                    } else {
                        // Other existing image types only make sense within the gecko integration.
                        println!("Wrench only supports updating buffer images (ignoring update command).");
                    }
                }
            }

            ApiMsg::DeleteImage(ref key) => {
                self.images.remove(key);
            }

            ApiMsg::SetDisplayList(ref background_color,
                                    ref epoch,
                                    ref pipeline_id,
                                    ref viewport_size,
                                    ref display_list,
                                    ref auxiliary_lists,
                                    _preserve_frame_state) => {
                self.begin_write_display_list(background_color,
                                              epoch,
                                              pipeline_id,
                                              viewport_size,
                                              display_list,
                                              auxiliary_lists);
            }
            _ => {}
        }
    }

    fn write_payload(&mut self, frame: u32, data: &[u8]) {
        if self.dl_descriptor.is_some() {
            self.finish_write_display_list(frame, data);
        }
    }
}
<|endoftext|>


<commit_before>use app::obj;
use app::obj::*;
use rand;
use rand::Rng;
use std::collections::HashMap;
use std::slice;

pub struct State {
	age_seconds: f32,
	age_frames: usize,
	charge: f32,
	target_charge: f32,
	tau: f32,
}

impl Default for State {
	fn default() -> Self {
		State {
			age_seconds: 0.,
			age_frames: 0,
			charge: 1.,
			target_charge: 0.,
			tau: 2.0,
		}
	}
}

impl State {
	pub fn update(&mut self, dt: f32) {
		self.age_seconds += dt;
		self.age_frames += 1;
		let alpha = 1. - f32::exp(-dt / self.tau);
		self.charge = self.target_charge * alpha + self.charge * (1. - alpha);
	}

	pub fn with_charge(initial: f32, target: f32) -> Self {
		State {
			charge: initial,
			target_charge: target,
			..Self::default()
		}
	}

	pub fn charge(&self) -> f32 {
		self.charge
	}
}

pub struct Limb {
	transform: Transform,
	mesh: Mesh,
	material: Material,
	pub state: State,
}

pub struct Creature {
	id: Id,
	limbs: Vec<Limb>,
}

impl GameObject for Creature {
	fn id(&self) -> Id {
		self.id
	}
}

impl Transformable for Creature {
	fn transform(&self) -> Transform {
		self.limbs.first().unwrap().transform()
	}
	fn transform_to(&mut self, t: Transform) {
		self.limbs.first_mut().unwrap().transform_to(t);
	}
}

impl Transformable for Limb {
	fn transform(&self) -> Transform {
		self.transform
	}
	fn transform_to(&mut self, t: Transform) {
		self.transform = t;
	}
}

impl obj::Geometry for Limb {
	fn mesh(&self) -> &Mesh {
		&self.mesh
	}
}

impl obj::Solid for Limb {
	fn material(&self) -> Material {
		self.material
	}
}

impl obj::Drawable for Limb {
	fn color(&self) -> Rgba {
		// let lightness = 1. - self.material.density * 0.5;
		// [0., 10. * lightness, 0., 1.]
		[9. * self.state.charge + 0.1, 4. * self.state.charge, 0., 1.]
	}
}

impl Creature {
	pub fn id(&self) -> Id {
		self.id
	}
	pub fn limbs(&self) -> slice::Iter<Limb> {
		self.limbs.iter()
	}
	pub fn limbs_mut(&mut self) -> slice::IterMut<Limb> {
		self.limbs.iter_mut()
	}
	pub fn limb_mut(&mut self, index: LimbIndex) -> Option<&mut Limb> {
		self.limbs.get_mut(index as usize)
	}
}

pub struct Flock {
	last_id: Id,
	creatures: HashMap<Id, Creature>,
}

impl Flock {
	pub fn new() -> Flock {
		Flock {
			last_id: 0,
			creatures: HashMap::new(),
		}
	}

	pub fn get(&self, id: Id) -> Option<&Creature> {
		self.creatures.get(&id)
	}

	pub fn get_mut(&mut self, id: Id) -> Option<&mut Creature> {
		self.creatures.get_mut(&id)
	}

	pub fn next_id(&mut self) -> Id {
		self.last_id = self.last_id + 1;
		self.last_id
	}

	pub fn new_ball(&mut self, pos: Position) -> Id {
		let mut rng = rand::thread_rng();
		let radius: f32 = (rng.gen::<f32>() * 1.0) + 1.0;

		let shape = Shape::new_ball(radius);

		let id = self.new_creature(shape);

		if let Some(item) = self.get_mut(id) {
			item.transform_to(obj::Transform::with_position(pos));
		}

		id
	}

	pub fn new_creature(&mut self, shape: Shape) -> Id {
		let mut rng = rand::thread_rng();

		let id = self.next_id();
		let vertices = shape.vertices();

		let limb = Limb {
			transform: Transform::default(),
			mesh: Mesh {
				shape: shape,
				vertices: vertices,
			},
			material: Material { density: (rng.gen::<f32>() * 1.0) + 1.0, ..Default::default() },
			state: State::with_charge(rng.gen::<f32>(), 0.),
		};

		let creature = Creature {
			id: id,
			limbs: vec![limb],
		};

		self.creatures.insert(id, creature);

		id
	}

	pub fn kill(&mut self, id: &Id) {
		self.creatures.remove(id);
	}

	pub fn creatures(&self) -> &HashMap<Id, Creature> {
		&self.creatures
	}
}

#[repr(packed)]
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
pub struct CreatureRefs {
	pub creature_id: obj::Id,
	pub limb_index: obj::LimbIndex,
	pub bone_index: obj::BoneIndex,
}

impl Default for CreatureRefs {
	fn default() -> CreatureRefs {
		CreatureRefs {
			creature_id: 0xdeadbeef,
			limb_index: 0xff,
			bone_index: 0xff,
		}
	}
}

impl CreatureRefs {
	pub fn with_id(id: obj::Id) -> CreatureRefs {
		CreatureRefs { creature_id: id, ..Default::default() }
	}
	pub fn with_limb(id: obj::Id, limb_index: obj::LimbIndex) -> CreatureRefs {
		CreatureRefs {
			creature_id: id,
			limb_index: limb_index,
			..Default::default()
		}
	}
	pub fn with_bone(id: obj::Id, limb_index: obj::LimbIndex, bone_index: obj::BoneIndex) -> CreatureRefs {
		CreatureRefs {
			creature_id: id,
			limb_index: limb_index,
			bone_index: bone_index,
		}
	}
}

pub struct World {
	pub friends: Flock,
}

impl World {
	pub fn new() -> Self {
		World { friends: Flock::new() }
	}

	pub fn new_ball(&mut self, pos: obj::Position) -> obj::Id {
		self.friends.new_ball(pos)
	}

	pub fn friend(&self, id: obj::Id) -> Option<&Creature> {
		self.friends.get(id)
	}

	pub fn friend_mut(&mut self, id: obj::Id) -> Option<&mut Creature> {
		self.friends.get_mut(id)
	}
}
<commit_msg>Formatted code<commit_after>use app::obj;
use app::obj::*;
use rand;
use rand::Rng;
use std::collections::HashMap;
use std::slice;

pub struct State {
	age_seconds: f32,
	age_frames: usize,
	charge: f32,
	target_charge: f32,
	tau: f32,
}

impl Default for State {
	fn default() -> Self {
		State {
			age_seconds: 0.,
			age_frames: 0,
			charge: 1.,
			target_charge: 0.,
			tau: 2.0,
		}
	}
}

impl State {
	pub fn update(&mut self, dt: f32) {
		self.age_seconds += dt;
		self.age_frames += 1;
		let alpha = 1. - f32::exp(-dt / self.tau);
		self.charge = self.target_charge * alpha + self.charge * (1. - alpha);
	}

	pub fn with_charge(initial: f32, target: f32) -> Self {
		State {
			charge: initial,
			target_charge: target,
			..Self::default()
		}
	}

	pub fn charge(&self) -> f32 {
		self.charge
	}
}

pub struct Limb {
	transform: Transform,
	mesh: Mesh,
	material: Material,
	pub state: State,
}

pub struct Creature {
	id: Id,
	limbs: Vec<Limb>,
}

impl GameObject for Creature {
	fn id(&self) -> Id {
		self.id
	}
}

impl Transformable for Creature {
	fn transform(&self) -> Transform {
		self.limbs.first().unwrap().transform()
	}
	fn transform_to(&mut self, t: Transform) {
		self.limbs.first_mut().unwrap().transform_to(t);
	}
}

impl Transformable for Limb {
	fn transform(&self) -> Transform {
		self.transform
	}
	fn transform_to(&mut self, t: Transform) {
		self.transform = t;
	}
}

impl obj::Geometry for Limb {
	fn mesh(&self) -> &Mesh {
		&self.mesh
	}
}

impl obj::Solid for Limb {
	fn material(&self) -> Material {
		self.material
	}
}

impl obj::Drawable for Limb {
	fn color(&self) -> Rgba {
		// let lightness = 1. - self.material.density * 0.5;
		// [0., 10. * lightness, 0., 1.]
		[9. * self.state.charge + 0.1, 4. * self.state.charge, 0., 1.]
	}
}

impl Creature {
	pub fn id(&self) -> Id {
		self.id
	}

	pub fn limbs(&self) -> slice::Iter<Limb> {
		self.limbs.iter()
	}

	pub fn limbs_mut(&mut self) -> slice::IterMut<Limb> {
		self.limbs.iter_mut()
	}

	pub fn limb_mut(&mut self, index: LimbIndex) -> Option<&mut Limb> {
		self.limbs.get_mut(index as usize)
	}
}

pub struct Flock {
	last_id: Id,
	creatures: HashMap<Id, Creature>,
}

impl Flock {
	pub fn new() -> Flock {
		Flock {
			last_id: 0,
			creatures: HashMap::new(),
		}
	}

	pub fn get(&self, id: Id) -> Option<&Creature> {
		self.creatures.get(&id)
	}

	pub fn get_mut(&mut self, id: Id) -> Option<&mut Creature> {
		self.creatures.get_mut(&id)
	}

	pub fn next_id(&mut self) -> Id {
		self.last_id = self.last_id + 1;
		self.last_id
	}

	pub fn new_ball(&mut self, pos: Position) -> Id {
		let mut rng = rand::thread_rng();
		let radius: f32 = (rng.gen::<f32>() * 1.0) + 1.0;

		let shape = Shape::new_ball(radius);

		let id = self.new_creature(shape);

		if let Some(item) = self.get_mut(id) {
			item.transform_to(obj::Transform::with_position(pos));
		}

		id
	}

	pub fn new_creature(&mut self, shape: Shape) -> Id {
		let mut rng = rand::thread_rng();

		let id = self.next_id();
		let vertices = shape.vertices();

		let limb = Limb {
			transform: Transform::default(),
			mesh: Mesh {
				shape: shape,
				vertices: vertices,
			},
			material: Material { density: (rng.gen::<f32>() * 1.0) + 1.0, ..Default::default() },
			state: State::with_charge(rng.gen::<f32>(), 0.),
		};

		let creature = Creature {
			id: id,
			limbs: vec![limb],
		};

		self.creatures.insert(id, creature);

		id
	}

	pub fn kill(&mut self, id: &Id) {
		self.creatures.remove(id);
	}

	pub fn creatures(&self) -> &HashMap<Id, Creature> {
		&self.creatures
	}
}

#[repr(packed)]
#[derive(Eq, Hash, PartialEq, Clone, Copy)]
pub struct CreatureRefs {
	pub creature_id: obj::Id,
	pub limb_index: obj::LimbIndex,
	pub bone_index: obj::BoneIndex,
}

impl Default for CreatureRefs {
	fn default() -> CreatureRefs {
		CreatureRefs {
			creature_id: 0xdeadbeef,
			limb_index: 0xff,
			bone_index: 0xff,
		}
	}
}

impl CreatureRefs {
	pub fn with_id(id: obj::Id) -> CreatureRefs {
		CreatureRefs { creature_id: id, ..Default::default() }
	}

	pub fn with_limb(id: obj::Id, limb_index: obj::LimbIndex) -> CreatureRefs {
		CreatureRefs {
			creature_id: id,
			limb_index: limb_index,
			..Default::default()
		}
	}

	pub fn with_bone(id: obj::Id, limb_index: obj::LimbIndex, bone_index: obj::BoneIndex) -> CreatureRefs {
		CreatureRefs {
			creature_id: id,
			limb_index: limb_index,
			bone_index: bone_index,
		}
	}
}

pub struct World {
	pub friends: Flock,
}

impl World {
	pub fn new() -> Self {
		World { friends: Flock::new() }
	}

	pub fn new_ball(&mut self, pos: obj::Position) -> obj::Id {
		self.friends.new_ball(pos)
	}

	pub fn friend(&self, id: obj::Id) -> Option<&Creature> {
		self.friends.get(id)
	}

	pub fn friend_mut(&mut self, id: obj::Id) -> Option<&mut Creature> {
		self.friends.get_mut(id)
	}
}
<|endoftext|>


<commit_before>extern crate zstd;

use std::env;
use std::fs;
use std::str::FromStr;
use std::io::{self, Read, Write};

fn main() {
    let mut buffer = Vec::new();
    let mut sample_sizes = Vec::new();

    let mut ignore_options = false;
    let mut max_size = 110 * 1024;

    let mut expect_size = false;

    if env::args().len() == 1 {
        writeln!(io::stderr(), "Usage: `train [-c MAX_SIZE] FILES...`").unwrap();
        return;
    }

    for filename in env::args().skip(1) {
        if !ignore_options {
            match filename.as_ref() {
                "--" => {
                    ignore_options = true;
                    continue;
                }
                "-c" => {
                    expect_size = true;
                    continue;
                }
                other if expect_size => {
                    expect_size = false;
                    max_size = usize::from_str(other).expect("Invalid size");
                    continue;
                }
                _ => (),
            }
        }
        let mut file = fs::File::open(filename).unwrap();
        let size = file.read_to_end(&mut buffer).unwrap();
        sample_sizes.push(size);
    }

    let dict = zstd::dict::from_continuous(&buffer, &sample_sizes, max_size).unwrap();
    let mut dict_reader: &[u8] = &dict;
    io::copy(&mut dict_reader, &mut io::stdout()).unwrap();
}
<commit_msg>Add comments<commit_after>extern crate zstd;

use std::env;
use std::fs;
use std::str::FromStr;
use std::io::{self, Read, Write};

// This program trains a dictionary from one or more files,
// to make future compression of similar small files more efficient.
//
// The dictionary will need to be present during decompression,
// but it you need to compress many small files individually,
// it may be worth the trouble.
fn main() {
    // We will concatenate all the input files in one big buffer.
    let mut buffer = Vec::new();
    // We'll keep track of each file size
    let mut sample_sizes = Vec::new();

    // Passing "--" treats everything after that as a filename
    let mut ignore_options = false;

    // A tiny state machine to parse the max size.
    let mut expect_size = false;
    let mut max_size = 110 * 1024;

    if env::args().len() == 1 {
        writeln!(io::stderr(), "Usage: `train [-c MAX_SIZE] FILES...`").unwrap();
        return;
    }

    // We do some ugly manual option parsing, because I'm trying to avoid using `clap`.
    // When cargo allows per-binary dependencies, this may get cleaner.
    for filename in env::args().skip(1) {
        if !ignore_options {
            match filename.as_ref() {
                "--" => {
                    ignore_options = true;
                    continue;
                }
                "-c" => {
                    expect_size = true;
                    continue;
                }
                other if expect_size => {
                    expect_size = false;
                    max_size = usize::from_str(other).expect("Invalid size");
                    continue;
                }
                _ => (),
            }
        }
        let mut file = fs::File::open(filename).unwrap();
        let size = file.read_to_end(&mut buffer).unwrap();
        sample_sizes.push(size);
    }

    let dict = zstd::dict::from_continuous(&buffer, &sample_sizes, max_size).unwrap();
    let mut dict_reader: &[u8] = &dict;
    io::copy(&mut dict_reader, &mut io::stdout()).unwrap();
}
<|endoftext|>


<commit_before>extern crate mm_client;

use mm_client::Client;

use client::client::APIClient;
use client::error::{ClientError, ClientResult};
use config::APIConfig;

pub struct MMClient {
    client: Client,
}

impl APIClient for MMClient {
    fn new(config: Option<&APIConfig>) -> ClientResult<MMClient> {
        config.ok_or(ClientError::ConfigError)
            .and_then(|conf| {
                Client::staging(conf.key.as_str(), conf.secret.as_str())
                    .or(Err(ClientError::InitializationError))
            })
            .and_then(|client| Ok(MMClient { client: client }))
    }

    fn url(&self, url: &str) -> ClientResult<String> {
        self.client
            .url(url)
            .or_else(|err| {
                error!("Failed to query {} due to {}", url, err);
                Err(err)
            })
            .map_err(ClientError::API)
    }

    fn all_shows(&self) -> ClientResult<String> {
        self.client
            .shows(vec![("page-size", "50")])
            .or_else(|err| {
                error!("Failed to query all shows due to {}", err);
                Err(err)
            })
            .map_err(ClientError::API)
    }

    fn changes(&self, since: &str) -> ClientResult<String> {
        self.client
            .changelog(vec![("since", since)])
            .or_else(|err| {
                error!("Failed to query changelog from {} due to {}", since, err);
                Err(err)
            })
            .map_err(ClientError::API)
    }
}
<commit_msg>Switch to production API<commit_after>extern crate mm_client;

use mm_client::Client;

use client::client::APIClient;
use client::error::{ClientError, ClientResult};
use config::APIConfig;

pub struct MMClient {
    client: Client,
}

impl APIClient for MMClient {
    fn new(config: Option<&APIConfig>) -> ClientResult<MMClient> {
        config.ok_or(ClientError::ConfigError)
            .and_then(|conf| {
                Client::new(conf.key.as_str(), conf.secret.as_str())
                    .or(Err(ClientError::InitializationError))
            })
            .and_then(|client| Ok(MMClient { client: client }))
    }

    fn url(&self, url: &str) -> ClientResult<String> {
        self.client
            .url(url)
            .or_else(|err| {
                error!("Failed to query {} due to {}", url, err);
                Err(err)
            })
            .map_err(ClientError::API)
    }

    fn all_shows(&self) -> ClientResult<String> {
        self.client
            .shows(vec![("page-size", "50")])
            .or_else(|err| {
                error!("Failed to query all shows due to {}", err);
                Err(err)
            })
            .map_err(ClientError::API)
    }

    fn changes(&self, since: &str) -> ClientResult<String> {
        self.client
            .changelog(vec![("since", since)])
            .or_else(|err| {
                error!("Failed to query changelog from {} due to {}", since, err);
                Err(err)
            })
            .map_err(ClientError::API)
    }
}
<|endoftext|>