<commit_before>use redox::*;
use common::*;
mod crypto;
use crypto::{Sha512, PubKey, RsaSignature};

/// Version
#[derive(Hash, Clone)]
pub enum Version {
    NewerThan(u64),
    OlderThan(u64),
    Between(u64, u64),
    Excatly(u64),
    Newest,
}

// TODO: Implement format

#[derive(Hash, Clone)]
/// A package developer
pub struct Developer {
    /// The name of the developer
    pub name: String,
    /// The public key of the developer
    pub key: PubKey,
}

#[derive(Hash, Clone)]
/// An installable package for Oxide
pub struct Package {
    /// The id of this package
    pub id: Id,
    /// Description
    pub desc: String,
    /// The developer of the package
    pub dev: Developer,
    /// The developer's signature of this package's content (tarball)
    pub dev_sign: RsaSignature,
    /// The signatures of this package
    pub sign: Vec<RsaSignature>,
    /// The files this package will create on the computer.
    pub files: Vec<String>,
    /// Dependencies of this package
    pub deps: Vec<Id>,
}

impl Package {
    /// Get content
    pub fn get_content(&self) -> Tarball {

    }

    /// Get package from string
    pub fn from_string(s: String) -> Option<Package> {

        // TODO

        for i in resp {
            let data = i.substr(5, i.len() - 5);
            let key = i.substr(0, 4);

            if key == "name" {
                name = data;
            } else if key == "desc" {
                desc = data;
            } else if key == "host" {
                host = data;
            } else if key == "file" {
                files = data;
            } else if key == "vers" {
                version = data;
            }
        }

        Package {
            host: host,
            name: name,
            desc: desc,
            files: files.split(",".to_string()).collect::<Vec<_>>(),
            version: version,
        }
    }

    /// Install package
    pub fn install(&self, col: &Collection) -> Result<u64, InstallError> {
        // Install deps
        let mut installed = 0;
        for d in self.deps {
            let pkg = d.install();
            if let Err(n) = pkg {
                installed += n;
                if n > 10000 {
                    println!("Warning: Potential infinite recursion (cyclic dependencies)");
                }
            } else {
                return pkg;
            }

        }

        // TODO install + add to local package list
    }

    /// Check validity
    pub fn check(&self, col: &Collection) -> TrustLevel {
        let con = self.get_content();

        for s in self.sign {
            if s.check(con) && col.keys.contains(s) {
                return TrustLevel::TrustedPackage
            } else if !s.check(con) {
                return TrustLevel::InvalidSignature
            }
        }

        if !self.dev_sign.check(con) {
            TrustLevel::InvalidSignature
        } else if !col.devs.contains(self.dev_sign) {
            TrustLevel::UntrustedSignature
        } else {
            TrustLevel::TrustedDev
        }
    }

}

/// Trust level
pub enum TrustLevel {
    /// 0
    InvalidSignature,
    /// 1
    UntrustedSignature,
    /// 2
    TrustedDeveloper,
    /// 3
    TrustedPackage,
}

impl TrustLevel {
    /// Is this package trusted?
    pub fn is_trusted(&self) -> bool {
        match self {
            &TrustLevel::TrustedDeveloper | TrustLevel::TrustedPackage => true,
            _ => false,
        }
    }
}

/// An error
pub enum PackageError {
    InvalidSyntax,
    InvalidSignature,
    UntrustedSignature,
    UntrustedDev,
    NotFound,
    E404,
    InfiniteDeps,
    Unknown,
}

#[derive(Hash, Clone)]
/// An package descriptor
pub struct Id {
    pub name: String,
    pub version: Version,
    pub dist_type: DistType,
}

/// Distribution type
pub enum DistType {
    Binary,
    Source,
    Other,
}

impl Id {
    pub fn to_string(&self) -> String {
        format!("{}-{}-{}", self.name, self.dist_type, self.version)
    }
}

/// Database of trusted developers
#[derive(Hash, Clone)]
pub struct DevDb {
    pub data: HashSet<Developer>,
}

/// Database of trusted keys
#[derive(Hash, Clone)]
pub struct KeyDb {
    pub data: HashSet<PubKey>,
}

/// An index of packages
#[derive(Hash, Clone)]
pub struct Index {
    /// Where the search queries can be send to
    pub host: String,
}

impl Index {
    /// Get a given package
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        let con = File::open("tcp://".to_string() + self.host);

        con.write("GET /ox/".to_string() + id.to_string() + " HTTP/1.1".to_string());

        let res = Vec::new();
        con.read_to_end(&mut res);

        Package::from_string(String::from_utf8(&res))
    }
}

/// A collection of indexes, trusted keys, and trusted developers (all stored on the users
/// computer)
#[derive(Hash, Clone)]
pub struct Collection {
    /// Indexes
    pub index: Vec<Index>,
    /// The trusted devs
    pub devs: DevDb,
    /// The trusted keys
    pub keys: KeyDb,
    /// The installed packages
    pub installed: Vec<LocalPackage>,
}

/// A package installed locally
pub struct LocalPackage {
    /// Files it owns
    pub owns: Vec<String>,
    /// Is this package installed as root (i.e. isnt just installed as a dep for another package)?
    pub root: bool,
    /// The package
    pub package: Package,
}

impl LocalPackage {
    pub fn uninstall(&self) -> bool {

    }
}

impl Collection {
    /// Get a given package (guaranteed to be valid)
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        for i in self.index {
            if let Ok(p) = i.get(id) {
                if p.check().is_trusted() {
                    return Ok(p);
                }
            }
        }
        None
    }
}

<commit_msg>More work on Oxide<commit_after>use redox::*;
use common::*;
mod crypto;
use crypto::{Sha512, PubKey, RsaSignature};
use redox::time::Duration;

// TODO: Implement format

#[derive(Hash, Clone)]
/// A package developer
pub struct Developer {
    /// The name of the developer
    pub name: String,
    /// The public key of the developer
    pub key: PubKey,
}

#[derive(Hash, Clone)]
/// An installable package for Oxide
pub struct Package {
    /// Description
    pub desc: String,
    /// The developer of the package
    pub dev: Developer,
    /// The developer's signature of this package's content (tarball)
    pub dev_sign: RsaSignature,
    /// The signatures of this package
    pub sign: HashSet<RsaSignature>,
    /// The files this package will create on the computer.
    pub files: HashSet<String>,
    /// Dependencies of this package
    /// Making sure the newest (compatible) version is the one used in the deps is up to the
    /// package provider (and is thus NOT included in the signature because it's already
    /// signed).
    pub deps: HashSet<Id>,
}

impl Package {
    /// Get content
    pub fn get_content(&self) -> Tarball {

    }

    /// Get package from string
    pub fn from_string(s: String) -> Option<Package> {

        // TODO

        for i in resp {
            let data = i.substr(5, i.len() - 5);
            let key = i.substr(0, 4);

            if key == "name" {
                name = data;
            } else if key == "desc" {
                desc = data;
            } else if key == "host" {
                host = data;
            } else if key == "file" {
                files = data;
            } else if key == "vers" {
                version = data;
            }
        }

        Package {
            host: host,
            name: name,
            desc: desc,
            files: files.split(",".to_string()).collect::<Vec<_>>(),
            version: version,
        }
    }

    /// Install package
    pub fn install(&self, col: &Collection) -> Result<u64, PackageError> {
        // Install deps
        let mut installed = 0;
        for d in self.deps {
            let pkg = d.install();
            if let Err(n) = pkg {
                installed += n;
                if n > 10000 {
                    println!("Warning: Potential infinite recursion (cyclic dependencies)");
                }
            } else {
                return pkg;
            }

        }

        // TODO install + add to local package list
    }

    /// Update packages
    pub fn update(&self, col: &Collection) -> Result<u64, PackageError> {

        // TODO install + add to local package list
    }

    /// Check validity
    pub fn check(&self, col: &Collection) -> TrustLevel {
        let con = self.get_content();

        for s in self.sign {
            if s.check(con) && col.keys.contains(s) {
                return TrustLevel::TrustedPackage
            } else if !s.check(con) {
                return TrustLevel::InvalidSignature
            }
        }

        if !self.dev_sign.check(con) {
            TrustLevel::InvalidSignature
        } else if !col.devs.contains(self.dev_sign) {
            TrustLevel::UntrustedSignature
        } else {
            TrustLevel::TrustedDev
        }
    }

}

/// Trust level
pub enum TrustLevel {
    /// 0
    InvalidSignature,
    /// 1
    UntrustedSignature,
    /// 2
    TrustedDeveloper,
    /// 3
    TrustedPackage,
}

impl TrustLevel {
    /// Is this package trusted?
    pub fn is_trusted(&self) -> bool {
        match self {
            &TrustLevel::TrustedDeveloper | TrustLevel::TrustedPackage => true,
            _ => false,
        }
    }
}

/// An error
pub enum PackageError {
    InvalidSyntax,
    InvalidSignature,
    UntrustedSignature,
    UntrustedDev,
    NotFound,
    E404,
    InfiniteDeps,
    Unknown,
}

#[derive(Hash, Clone)]
/// An package descriptor
pub struct Id {
    pub name: String,
    pub version: String,
    pub dist_type: DistType,
}

/// Distribution type
pub enum DistType {
    Binary,
    Source,
    Other,
}

impl Id {
    pub fn to_string(&self) -> String {
        format!("{}-{}-{}", self.name, self.dist_type, self.version)
    }
}

/// Database of trusted developers
#[derive(Hash, Clone)]
pub struct DevDb {
    pub data: HashSet<Developer>,
}

/// Database of trusted keys
#[derive(Hash, Clone)]
pub struct KeyDb {
    pub data: HashSet<PubKey>,
}

/// An index of packages
#[derive(Hash, Clone)]
pub struct Index {
    /// Where the search queries can be send to
    pub host: String,
}

impl Index {
    /// Get a given package
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        let con = File::open("tcp://".to_string() + self.host);

        con.write("GET /ox/".to_string() + id.to_string() + " HTTP/1.1".to_string());

        let res = Vec::new();
        con.read_to_end(&mut res);

        Package::from_string(String::from_utf8(&res))
    }
}

/// A collection of indexes, trusted keys, and trusted developers (all stored on the users
/// computer)
#[derive(Hash, Clone)]
pub struct Collection {
    /// Indexes
    pub index: Vec<Index>,
    /// The trusted devs
    pub devs: DevDb,
    /// The trusted keys
    pub keys: KeyDb,
    /// The installed packages
    pub installed: HashMap<Id, LocalPackage>,
    /// The root packages (packages which are not just installed as dependencies to other packages)
    pub root: HashSet<Id>,
}

/// A package installed locally
pub struct LocalPackage {
    /// Files it owns
    pub owns: HashSet<String>,
    /// The package
    pub package: Package,
    /// Dependency to
    pub dep_to: HashSet<Id>,
    /// Dependency for
    pub dep_for: HashSet<Id>,
}

impl LocalPackage {
    pub fn uninstall(&self) -> bool {

    }
}

impl Collection {
    /// Get a given package (guaranteed to be valid)
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        for i in self.index {
            if let Ok(p) = i.get(id) {
                if p.check().is_trusted() {
                    return Ok(p);
                }
            }
        }
        None
    }
}

<|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/. */

//! A windowing implementation using GLUT.
///
/// GLUT is a very old and bare-bones toolkit. However, it has good cross-platform support, at
/// least on desktops. It is designed for testing Servo without the need of a UI.

use windowing::{ApplicationMethods, CompositeCallback, LoadUrlCallback, MouseCallback};
use windowing::{ResizeCallback, ScrollCallback, WindowMethods, WindowMouseEvent, WindowClickEvent};
use windowing::{WindowMouseDownEvent, WindowMouseUpEvent, ZoomCallback};

use alert::{Alert, AlertMethods};
use core::cell::Cell;
use core::libc::c_int;
use geom::point::Point2D;
use geom::size::Size2D;
use gfx::compositor::{IdleRenderState, RenderState, RenderingRenderState};
use glut::glut::{ACTIVE_CTRL, DOUBLE, HAVE_PRECISE_MOUSE_WHEEL, WindowHeight, WindowWidth};
use glut::glut;
use glut::machack;
use script::compositor_interface::{FinishedLoading, Loading, PerformingLayout, ReadyState};

static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];

/// A structure responsible for setting up and tearing down the entire windowing system.
pub struct Application;

impl ApplicationMethods for Application {
    pub fn new() -> Application {
        glut::init();
        glut::init_display_mode(DOUBLE);
        Application
    }
}

/// The type of a window.
pub struct Window {
    glut_window: glut::Window,

    composite_callback: Option<CompositeCallback>,
    resize_callback: Option<ResizeCallback>,
    load_url_callback: Option<LoadUrlCallback>,
    mouse_callback: Option<MouseCallback>,
    scroll_callback: Option<ScrollCallback>,
    zoom_callback: Option<ZoomCallback>,

    drag_origin: Point2D<c_int>,

    mouse_down_button: @mut c_int,
    mouse_down_point: @mut Point2D<c_int>,

    ready_state: ReadyState,
    render_state: RenderState,
    throbber_frame: u8,
}

impl WindowMethods<Application> for Window {
    /// Creates a new window.
    pub fn new(_: &Application) -> @mut Window {
        // Create the GLUT window.
        let glut_window = glut::create_window(~"Servo");
        glut::reshape_window(glut_window, 800, 600);

        // Create our window object.
        let window = @mut Window {
            glut_window: glut_window,

            composite_callback: None,
            resize_callback: None,
            load_url_callback: None,
            mouse_callback: None,
            scroll_callback: None,
            zoom_callback: None,

            drag_origin: Point2D(0, 0),

            mouse_down_button: @mut 0,
            mouse_down_point: @mut Point2D(0, 0),

            ready_state: FinishedLoading,
            render_state: IdleRenderState,
            throbber_frame: 0,
        };

        // Spin the event loop every 50 ms to allow the Rust channels to be polled.
        //
        // This requirement is pretty much the nail in the coffin for GLUT's usefulness.
        //
        // FIXME(pcwalton): What a mess.
        let register_timer_callback: @mut @fn() = @mut ||{};
        *register_timer_callback = || {
            glut::timer_func(50, *register_timer_callback);
            window.throbber_frame = (window.throbber_frame + 1) % (THROBBER.len() as u8);
            window.update_window_title()
        };

        // Register event handlers.
        do glut::reshape_func(window.glut_window) |width, height| {
            match window.resize_callback {
                None => {}
                Some(callback) => callback(width as uint, height as uint),
            }
        }
        do glut::display_func {
            // FIXME(pcwalton): This will not work with multiple windows.
            match window.composite_callback {
                None => {}
                Some(callback) => callback(),
            }
        }
        do glut::keyboard_func |key, _, _| {
            window.handle_key(key)
        }
        do glut::mouse_func |button, state, x, y| {
            if button < 3 {
                window.handle_mouse(button, state, x, y);
            }
        }
        do glut::mouse_wheel_func |wheel, direction, x, y| {
            let delta = if HAVE_PRECISE_MOUSE_WHEEL {
                (direction as f32) / 10000.0
            } else {
                (direction as f32) * 30.0
            };

            match wheel {
                1 => window.handle_scroll(Point2D(delta, 0.0)),
                2 => window.handle_zoom(delta),
                _ => window.handle_scroll(Point2D(0.0, delta)),
            }
        }
        (*register_timer_callback)();

        machack::perform_scroll_wheel_hack();

        window
    }

    /// Returns the size of the window.
    pub fn size(&self) -> Size2D<f32> {
        Size2D(glut::get(WindowWidth) as f32, glut::get(WindowHeight) as f32)
    }

    /// Presents the window to the screen (perhaps by page flipping).
    pub fn present(&mut self) {
        glut::swap_buffers();
    }

    /// Registers a callback to run when a composite event occurs.
    pub fn set_composite_callback(&mut self, new_composite_callback: CompositeCallback) {
        self.composite_callback = Some(new_composite_callback)
    }

    /// Registers a callback to run when a resize event occurs.
    pub fn set_resize_callback(&mut self, new_resize_callback: ResizeCallback) {
        self.resize_callback = Some(new_resize_callback)
    }

    /// Registers a callback to be run when a new URL is to be loaded.
    pub fn set_load_url_callback(&mut self, new_load_url_callback: LoadUrlCallback) {
        self.load_url_callback = Some(new_load_url_callback)
    }

    /// Registers a callback to be run when a mouse event occurs.
    pub fn set_mouse_callback(&mut self, new_mouse_callback: MouseCallback) {
        self.mouse_callback = Some(new_mouse_callback)
    }

    /// Registers a callback to be run when the user scrolls.
    pub fn set_scroll_callback(&mut self, new_scroll_callback: ScrollCallback) {
        self.scroll_callback = Some(new_scroll_callback)
    }

    /// Registers a zoom to be run when the user zooms.
    pub fn set_zoom_callback(&mut self, new_zoom_callback: ZoomCallback) {
        self.zoom_callback = Some(new_zoom_callback)
    }

    /// Spins the event loop.
    pub fn check_loop(@mut self) {
        glut::check_loop()
    }

    /// Schedules a redisplay.
    pub fn set_needs_display(@mut self) {
        glut::post_redisplay()
    }

    /// Sets the ready state.
    pub fn set_ready_state(@mut self, ready_state: ReadyState) {
        self.ready_state = ready_state;
        self.update_window_title()
    }

    /// Sets the render state.
    pub fn set_render_state(@mut self, render_state: RenderState) {
        self.render_state = render_state;
        self.update_window_title()
    }
}

impl Window {
    /// Helper function to set the window title in accordance with the ready state.
    fn update_window_title(&self) {
        let throbber = THROBBER[self.throbber_frame];
        match self.ready_state {
            Loading => {
                glut::set_window_title(self.glut_window, fmt!("%c Loading — Servo", throbber))
            }
            PerformingLayout => {
                glut::set_window_title(self.glut_window,
                                       fmt!("%c Performing Layout — Servo", throbber))
            }
            FinishedLoading => {
                match self.render_state {
                    RenderingRenderState => {
                        glut::set_window_title(self.glut_window,
                                               fmt!("%c Rendering — Servo", throbber))
                    }
                    IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
                }
            }
        }
    }

    /// Helper function to handle keyboard events.
    fn handle_key(&self, key: u8) {
        debug!("got key: %d", key as int);
        match key {
            12 => self.load_url(),                                                      // Ctrl+L
            k if k == ('=' as u8) && (glut::get_modifiers() & ACTIVE_CTRL) != 0 => {    // Ctrl++
                for self.zoom_callback.each |&callback| {
                    callback(0.1);
                }
            }
            k if k == 31 && (glut::get_modifiers() & ACTIVE_CTRL) != 0 => {             // Ctrl+-
                for self.zoom_callback.each |&callback| {
                    callback(-0.1);
                }
            }
            _ => {}
        }
    }

    /// Helper function to handle a click
    fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
        // FIXME(tkuehn): max pixel dist should be based on pixel density
        let max_pixel_dist = 10f;
        match self.mouse_callback {
            None => {}
            Some(callback) => {
                let event: WindowMouseEvent;
                match state {
                    glut::MOUSE_DOWN => {
                        event = WindowMouseDownEvent(button as uint, Point2D(x as f32, y as f32));
                        *self.mouse_down_point = Point2D(x, y);
                        *self.mouse_down_button = button;
                    }
                    glut::MOUSE_UP => {
                        event = WindowMouseUpEvent(button as uint, Point2D(x as f32, y as f32));
                        if *self.mouse_down_button == button {
                            let pixel_dist = *self.mouse_down_point - Point2D(x, y);
                            let pixel_dist = ((pixel_dist.x * pixel_dist.x +
                                              pixel_dist.y * pixel_dist.y) as float).sqrt();
                            if pixel_dist < max_pixel_dist {
                                let click_event = WindowClickEvent(button as uint,
                                                                   Point2D(x as f32, y as f32));
                                callback(click_event);
                            }
                        }
                    }
                    _ => fail!("I cannot recognize the type of mouse action that occured. :-(")
                };
                callback(event);
            }
        }
    }

    /// Helper function to handle a scroll.
    fn handle_scroll(&mut self, delta: Point2D<f32>) {
        match self.scroll_callback {
            None => {}
            Some(callback) => callback(delta),
        }
    }

    /// Helper function to handle a zoom.
    fn handle_zoom(&mut self, magnification: f32) {
        match self.zoom_callback {
            None => {}
            Some(callback) => callback(magnification),
        }
    }

    /// Helper function to pop up an alert box prompting the user to load a URL.
    fn load_url(&self) {
        match self.load_url_callback {
            None => error!("no URL callback registered, doing nothing"),
            Some(callback) => {
                let mut alert: Alert = AlertMethods::new("Navigate to:");
                alert.add_prompt();
                alert.run();
                let value = alert.prompt_value();
                if "" == value {    // To avoid crashing on Linux.
                    callback("http://purple.com/")
                } else {
                    callback(value)
                }
            }
        }
    }
}

<commit_msg>Get rid of initial reshape.<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/. */

//! A windowing implementation using GLUT.
///
/// GLUT is a very old and bare-bones toolkit. However, it has good cross-platform support, at
/// least on desktops. It is designed for testing Servo without the need of a UI.

use windowing::{ApplicationMethods, CompositeCallback, LoadUrlCallback, MouseCallback};
use windowing::{ResizeCallback, ScrollCallback, WindowMethods, WindowMouseEvent, WindowClickEvent};
use windowing::{WindowMouseDownEvent, WindowMouseUpEvent, ZoomCallback};

use alert::{Alert, AlertMethods};
use core::cell::Cell;
use core::libc::c_int;
use geom::point::Point2D;
use geom::size::Size2D;
use gfx::compositor::{IdleRenderState, RenderState, RenderingRenderState};
use glut::glut::{ACTIVE_CTRL, DOUBLE, HAVE_PRECISE_MOUSE_WHEEL, WindowHeight, WindowWidth};
use glut::glut;
use glut::machack;
use script::compositor_interface::{FinishedLoading, Loading, PerformingLayout, ReadyState};

static THROBBER: [char, ..8] = [ '⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷' ];

/// A structure responsible for setting up and tearing down the entire windowing system.
pub struct Application;

impl ApplicationMethods for Application {
    pub fn new() -> Application {
        glut::init();
        glut::init_display_mode(DOUBLE);
        Application
    }
}

/// The type of a window.
pub struct Window {
    glut_window: glut::Window,

    composite_callback: Option<CompositeCallback>,
    resize_callback: Option<ResizeCallback>,
    load_url_callback: Option<LoadUrlCallback>,
    mouse_callback: Option<MouseCallback>,
    scroll_callback: Option<ScrollCallback>,
    zoom_callback: Option<ZoomCallback>,

    drag_origin: Point2D<c_int>,

    mouse_down_button: @mut c_int,
    mouse_down_point: @mut Point2D<c_int>,

    ready_state: ReadyState,
    render_state: RenderState,
    throbber_frame: u8,
}

impl WindowMethods<Application> for Window {
    /// Creates a new window.
    pub fn new(_: &Application) -> @mut Window {
        // Create the GLUT window.
        unsafe { glut::bindgen::glutInitWindowSize(800, 600); }
        let glut_window = glut::create_window(~"Servo");

        // Create our window object.
        let window = @mut Window {
            glut_window: glut_window,

            composite_callback: None,
            resize_callback: None,
            load_url_callback: None,
            mouse_callback: None,
            scroll_callback: None,
            zoom_callback: None,

            drag_origin: Point2D(0, 0),

            mouse_down_button: @mut 0,
            mouse_down_point: @mut Point2D(0, 0),

            ready_state: FinishedLoading,
            render_state: IdleRenderState,
            throbber_frame: 0,
        };

        // Spin the event loop every 50 ms to allow the Rust channels to be polled.
        //
        // This requirement is pretty much the nail in the coffin for GLUT's usefulness.
        //
        // FIXME(pcwalton): What a mess.
        let register_timer_callback: @mut @fn() = @mut ||{};
        *register_timer_callback = || {
            glut::timer_func(50, *register_timer_callback);
            window.throbber_frame = (window.throbber_frame + 1) % (THROBBER.len() as u8);
            window.update_window_title()
        };

        // Register event handlers.
        do glut::reshape_func(window.glut_window) |width, height| {
            match window.resize_callback {
                None => {}
                Some(callback) => callback(width as uint, height as uint),
            }
        }
        do glut::display_func {
            // FIXME(pcwalton): This will not work with multiple windows.
            match window.composite_callback {
                None => {}
                Some(callback) => callback(),
            }
        }
        do glut::keyboard_func |key, _, _| {
            window.handle_key(key)
        }
        do glut::mouse_func |button, state, x, y| {
            if button < 3 {
                window.handle_mouse(button, state, x, y);
            }
        }
        do glut::mouse_wheel_func |wheel, direction, x, y| {
            let delta = if HAVE_PRECISE_MOUSE_WHEEL {
                (direction as f32) / 10000.0
            } else {
                (direction as f32) * 30.0
            };

            match wheel {
                1 => window.handle_scroll(Point2D(delta, 0.0)),
                2 => window.handle_zoom(delta),
                _ => window.handle_scroll(Point2D(0.0, delta)),
            }
        }
        (*register_timer_callback)();

        machack::perform_scroll_wheel_hack();

        window
    }

    /// Returns the size of the window.
    pub fn size(&self) -> Size2D<f32> {
        Size2D(glut::get(WindowWidth) as f32, glut::get(WindowHeight) as f32)
    }

    /// Presents the window to the screen (perhaps by page flipping).
    pub fn present(&mut self) {
        glut::swap_buffers();
    }

    /// Registers a callback to run when a composite event occurs.
    pub fn set_composite_callback(&mut self, new_composite_callback: CompositeCallback) {
        self.composite_callback = Some(new_composite_callback)
    }

    /// Registers a callback to run when a resize event occurs.
    pub fn set_resize_callback(&mut self, new_resize_callback: ResizeCallback) {
        self.resize_callback = Some(new_resize_callback)
    }

    /// Registers a callback to be run when a new URL is to be loaded.
    pub fn set_load_url_callback(&mut self, new_load_url_callback: LoadUrlCallback) {
        self.load_url_callback = Some(new_load_url_callback)
    }

    /// Registers a callback to be run when a mouse event occurs.
    pub fn set_mouse_callback(&mut self, new_mouse_callback: MouseCallback) {
        self.mouse_callback = Some(new_mouse_callback)
    }

    /// Registers a callback to be run when the user scrolls.
    pub fn set_scroll_callback(&mut self, new_scroll_callback: ScrollCallback) {
        self.scroll_callback = Some(new_scroll_callback)
    }

    /// Registers a zoom to be run when the user zooms.
    pub fn set_zoom_callback(&mut self, new_zoom_callback: ZoomCallback) {
        self.zoom_callback = Some(new_zoom_callback)
    }

    /// Spins the event loop.
    pub fn check_loop(@mut self) {
        glut::check_loop()
    }

    /// Schedules a redisplay.
    pub fn set_needs_display(@mut self) {
        glut::post_redisplay()
    }

    /// Sets the ready state.
    pub fn set_ready_state(@mut self, ready_state: ReadyState) {
        self.ready_state = ready_state;
        self.update_window_title()
    }

    /// Sets the render state.
    pub fn set_render_state(@mut self, render_state: RenderState) {
        self.render_state = render_state;
        self.update_window_title()
    }
}

impl Window {
    /// Helper function to set the window title in accordance with the ready state.
    fn update_window_title(&self) {
        let throbber = THROBBER[self.throbber_frame];
        match self.ready_state {
            Loading => {
                glut::set_window_title(self.glut_window, fmt!("%c Loading — Servo", throbber))
            }
            PerformingLayout => {
                glut::set_window_title(self.glut_window,
                                       fmt!("%c Performing Layout — Servo", throbber))
            }
            FinishedLoading => {
                match self.render_state {
                    RenderingRenderState => {
                        glut::set_window_title(self.glut_window,
                                               fmt!("%c Rendering — Servo", throbber))
                    }
                    IdleRenderState => glut::set_window_title(self.glut_window, "Servo"),
                }
            }
        }
    }

    /// Helper function to handle keyboard events.
    fn handle_key(&self, key: u8) {
        debug!("got key: %d", key as int);
        match key {
            12 => self.load_url(),                                                      // Ctrl+L
            k if k == ('=' as u8) && (glut::get_modifiers() & ACTIVE_CTRL) != 0 => {    // Ctrl++
                for self.zoom_callback.each |&callback| {
                    callback(0.1);
                }
            }
            k if k == 31 && (glut::get_modifiers() & ACTIVE_CTRL) != 0 => {             // Ctrl+-
                for self.zoom_callback.each |&callback| {
                    callback(-0.1);
                }
            }
            _ => {}
        }
    }

    /// Helper function to handle a click
    fn handle_mouse(&self, button: c_int, state: c_int, x: c_int, y: c_int) {
        // FIXME(tkuehn): max pixel dist should be based on pixel density
        let max_pixel_dist = 10f;
        match self.mouse_callback {
            None => {}
            Some(callback) => {
                let event: WindowMouseEvent;
                match state {
                    glut::MOUSE_DOWN => {
                        event = WindowMouseDownEvent(button as uint, Point2D(x as f32, y as f32));
                        *self.mouse_down_point = Point2D(x, y);
                        *self.mouse_down_button = button;
                    }
                    glut::MOUSE_UP => {
                        event = WindowMouseUpEvent(button as uint, Point2D(x as f32, y as f32));
                        if *self.mouse_down_button == button {
                            let pixel_dist = *self.mouse_down_point - Point2D(x, y);
                            let pixel_dist = ((pixel_dist.x * pixel_dist.x +
                                              pixel_dist.y * pixel_dist.y) as float).sqrt();
                            if pixel_dist < max_pixel_dist {
                                let click_event = WindowClickEvent(button as uint,
                                                                   Point2D(x as f32, y as f32));
                                callback(click_event);
                            }
                        }
                    }
                    _ => fail!("I cannot recognize the type of mouse action that occured. :-(")
                };
                callback(event);
            }
        }
    }

    /// Helper function to handle a scroll.
    fn handle_scroll(&mut self, delta: Point2D<f32>) {
        match self.scroll_callback {
            None => {}
            Some(callback) => callback(delta),
        }
    }

    /// Helper function to handle a zoom.
    fn handle_zoom(&mut self, magnification: f32) {
        match self.zoom_callback {
            None => {}
            Some(callback) => callback(magnification),
        }
    }

    /// Helper function to pop up an alert box prompting the user to load a URL.
    fn load_url(&self) {
        match self.load_url_callback {
            None => error!("no URL callback registered, doing nothing"),
            Some(callback) => {
                let mut alert: Alert = AlertMethods::new("Navigate to:");
                alert.add_prompt();
                alert.run();
                let value = alert.prompt_value();
                if "" == value {    // To avoid crashing on Linux.
                    callback("http://purple.com/")
                } else {
                    callback(value)
                }
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Test unknown field in remote struct<commit_after>#[macro_use]
extern crate serde_derive;

mod remote {
    pub struct S {
        pub a: u8,
    }
}

#[derive(Serialize, Deserialize)]
#[serde(remote = "remote::S")]
struct S {
    b: u8, //~^^^ ERROR: no field `b` on type `&remote::S`
}

fn main() {}
<|endoftext|>


<commit_before>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        debugln!("Reset: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = ctrl & (0xFFFFFFFF - CTRL_HCFS);
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Enable: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = (ctrl & (0xFFFFFFFF - CTRL_HCFS)) | 0b10 << 6;
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Port Enumeration: {:X}", self.regs.control.read());

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                //TODO: Remove 1 << 13, it sets it to low speed
                flags: 0x3FF << 16 | 1 << 13 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                let mut spin = 1000000;
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 && spin > 0 {
                    spin -= 1;
                    //unsafe { context_switch(false) };
                }
                let condition = (unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28) >> 28;
                if condition != 0 {
                    debugln!("Condition: {:X}", condition);
                    break;
                }
            }

            /*
            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            */
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
        }

        count
    }
}
<commit_msg>Remove low speed flag, increase spin count<commit_after>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        debugln!("Reset: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = ctrl & (0xFFFFFFFF - CTRL_HCFS);
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Enable: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = (ctrl & (0xFFFFFFFF - CTRL_HCFS)) | 0b10 << 6;
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Port Enumeration: {:X}", self.regs.control.read());

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                flags: 0x3FF << 16 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                let mut spin = 1000000000;
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 && spin > 0 {
                    spin -= 1;
                    //unsafe { context_switch(false) };
                }
                let condition = (unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28) >> 28;
                if condition != 0 {
                    debugln!("Condition: {:X}", condition);
                    break;
                }
            }

            /*
            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            */
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
        }

        count
    }
}
<|endoftext|>


<commit_before>extern crate sdl2;
extern crate sdl2_sys;
extern crate libc;

extern crate sdl3d;

use sdl3d::vid::*;
use sdl3d::start;

fn main() {
    let mut rend_contx = start::bootstrap(1280, 720, "Hello world!");
    let (mut renderer, mut pump) = rend_contx;

    unsafe {sdl2_sys::mouse::SDL_SetRelativeMouseMode(1);}

    // Variables, some of them should be static afaik.
    let screen_w = 1280/2;
    let screen_h = 720/2;

    let mut camera_x = 0.0;
    let mut camera_y = 0.0;
    let mut camera_z = 3.0;

    let mut camera_x_z = 0.0;
    let mut camera_y_z = 0.0;
    let mut camera_x_y = 0.0;

    //A vector of arrays of points. Each array is a line from first to second point.
    let mut lines = Lines::new(vec![
                                [DepthPoint::new(-0.5, -0.5, 0.6), DepthPoint::new(-0.5, 0.5, 0.6)],
                                [DepthPoint::new(-0.5, -0.5, 0.6), DepthPoint::new(0.0, -0.5, 0.6)],
                                [DepthPoint::new(-0.5, 0.0, 0.6), DepthPoint::new(0.0, 0.0, 0.6)],
                                [DepthPoint::new(0.0, 0.0, 0.6), DepthPoint::new(0.0, -0.5, 0.6)],
                               ]);

    'game_loop: loop {
        use sdl2::pixels::Color::RGB;

        std::thread::sleep(std::time::Duration::from_millis(33));

        for event in pump.poll_iter() {
            use sdl2::event::Event::*;
            use sdl2::keyboard::Keycode::*;

            match event {
                Quit {..} => {break 'game_loop;},
                KeyDown {keycode, ..} => {
                    match keycode {
                        Some(Up) => {
                            let z = camera_z;
                            camera_z = z - 0.05;
                        },
                        Some(Down) => {
                            let z = camera_z;
                            camera_z = z + 0.05;
                        },
                        Some(Left) => {
                            let x = camera_x;
                            camera_x = x + 0.05;
                        },
                        Some(Right) => {
                            let x = camera_x;
                            camera_x = x - 0.05;
                        },
                        Some(RCtrl) => {
                            let y = camera_y;
                            camera_y = y + 0.05;
                        },
                        Some(RShift) => {
                            let y = camera_y;
                            camera_y = y - 0.05;
                        },
                        Some(Q) => {
                            camera_x_y += 0.1;
                        },
                        Some(E) => {
                            camera_x_y -= 0.1;
                        },
                        Some(Escape) => {
                            break 'game_loop;
                        }
                        _ => {println!("{:?}", keycode);}
                    }
                },
                MouseMotion {xrel, yrel, ..} => {
                    camera_x_z = (xrel as f64)/30.0;
                    //camera_y_z = (yrel as f64)/30.0;
                }
                _ => {}
            }
        }

        renderer.set_draw_color(RGB(20, 40, 60));
        renderer.clear();
        renderer.set_draw_color(RGB(200, 200, 200));

        lines.flat(screen_w, screen_h, &mut renderer,
                   camera_x, camera_y, camera_z,
                  camera_x_y, camera_x_z, camera_y_z);

        // Reset relative mouse move back to 0 as everything was already moved
        camera_x_z = 0.0;
        camera_y_z = 0.0;
        camera_x_y = 0.0;

        renderer.present();
    }
}<commit_msg>Added an option to move camera up/down.<commit_after>extern crate sdl2;
extern crate sdl2_sys;
extern crate libc;

extern crate sdl3d;

use sdl3d::vid::*;
use sdl3d::start;

fn main() {
    let mut rend_contx = start::bootstrap(1280, 720, "Hello world!");
    let (mut renderer, mut pump) = rend_contx;

    unsafe {sdl2_sys::mouse::SDL_SetRelativeMouseMode(1);}

    // Variables, some of them should be static afaik.
    let screen_w = 1280/2;
    let screen_h = 720/2;

    let mut camera_x = 0.0;
    let mut camera_y = 0.0;
    let mut camera_z = 3.0;

    let mut camera_x_z = 0.0;
    let mut camera_y_z = 0.0;
    let mut camera_x_y = 0.0;

    //A vector of arrays of points. Each array is a line from first to second point.
    let mut lines = Lines::new(vec![
                                [DepthPoint::new(-0.5, -0.5, 0.6), DepthPoint::new(-0.5, 0.5, 0.6)],
                                [DepthPoint::new(-0.5, -0.5, 0.6), DepthPoint::new(0.0, -0.5, 0.6)],
                                [DepthPoint::new(-0.5, 0.0, 0.6), DepthPoint::new(0.0, 0.0, 0.6)],
                                [DepthPoint::new(0.0, 0.0, 0.6), DepthPoint::new(0.0, -0.5, 0.6)],
                               ]);

    'game_loop: loop {
        use sdl2::pixels::Color::RGB;

        std::thread::sleep(std::time::Duration::from_millis(33));

        for event in pump.poll_iter() {
            use sdl2::event::Event::*;
            use sdl2::keyboard::Keycode::*;

            match event {
                Quit {..} => {break 'game_loop;},
                KeyDown {keycode, ..} => {
                    match keycode {
                        Some(Up) => {
                            let z = camera_z;
                            camera_z = z - 0.05;
                        },
                        Some(Down) => {
                            let z = camera_z;
                            camera_z = z + 0.05;
                        },
                        Some(Left) => {
                            let x = camera_x;
                            camera_x = x + 0.05;
                        },
                        Some(Right) => {
                            let x = camera_x;
                            camera_x = x - 0.05;
                        },
                        Some(RCtrl) => {
                            let y = camera_y;
                            camera_y = y + 0.05;
                        },
                        Some(RShift) => {
                            let y = camera_y;
                            camera_y = y - 0.05;
                        },
                        Some(Q) => {
                            camera_x_y += 0.1;
                        },
                        Some(E) => {
                            camera_x_y -= 0.1;
                        },
                        Some(Escape) => {
                            break 'game_loop;
                        }
                        _ => {println!("{:?}", keycode);}
                    }
                },
                MouseMotion {xrel, yrel, ..} => {
                    camera_x_z = (xrel as f64)/30.0;
                    camera_y_z = (yrel as f64)/30.0;
                }
                _ => {}
            }
        }

        renderer.set_draw_color(RGB(20, 40, 60));
        renderer.clear();
        renderer.set_draw_color(RGB(200, 200, 200));

        lines.flat(screen_w, screen_h, &mut renderer,
                   camera_x, camera_y, camera_z,
                  camera_x_y, camera_x_z, camera_y_z);

        // Reset relative mouse move back to 0 as everything was already moved
        camera_x_z = 0.0;
        camera_y_z = 0.0;
        camera_x_y = 0.0;

        renderer.present();
    }
}<|endoftext|>


<commit_before><commit_msg>Add prototype macros for mock generation<commit_after>extern crate double;

trait Dependency: Clone {
    fn profit(&self, revenue: u32, costs: u32) -> i32;
}

macro_rules! mock_trait {
    ( $mock_name:ident, $($method:ident($retval:ty)($($arg_type:ty),*))* ) => (
        #[derive(Debug, Clone)]
        struct $mock_name {
            $(
                $method: double::Mock<(($($arg_type),*)), $retval>
            )*
        }

        impl Default for $mock_name {
            fn default() -> Self {
                $mock_name {
                    $(
                        $method: double::Mock::default(),
                    )*
                }
            }
        }
    );
}

macro_rules! mock_method {
    ( $method:ident($retval:ty)($($arg_name:ident: $arg_type:ty),*) ) => (
        fn $method(&self, $($arg_name: $arg_type),*) -> $retval {
            self.$method.call(($($arg_name),*))
        }
    )
}

mock_trait!(MockDependency, profit(i32)(u32, u32));

impl Dependency for MockDependency {
    mock_method!(profit(i32)(revenue: u32, costs: u32));

    /*fn profit(&self, revenue: u32, costs: u32) -> i32 {
        self.profit.call((revenue, costs))
    }*/
}

fn main() {
    // Test individual return values
    let mock = MockDependency::default();
    mock.profit.return_value(42);
    mock.profit.return_value_for((0, 0), 9001);

    let value = mock.profit(10, 20);
    assert_eq!(42, value);
    mock.profit.has_calls_exactly_in_order(vec!((10, 20)));

    let value = mock.profit(0, 0);
    assert_eq!(9001, value);
    mock.profit.has_calls_exactly_in_order(vec!((10, 20), (0, 0)));

    // Test sequence of return values
    mock.profit.return_values(vec!(1, 2, 3));
    assert_eq!(1, mock.profit.call((1, 2)));
    assert_eq!(2, mock.profit.call((2, 4)));
    assert_eq!(3, mock.profit.call((3, 6)));
    assert_eq!(42, mock.profit.call((4, 8)));
}
<|endoftext|>


<commit_before>extern crate discord;

use discord::Discord;
use discord::voice::{self, VoiceConnection};
use discord::model::{Event, ChannelId, ServerId};
use std::env;

fn main() {
	// Log in to Discord using the email and password in the environment
	let discord = Discord::new(
		&env::var("DISCORD_EMAIL").expect("DISCORD_EMAIL"),
		&env::var("DISCORD_PASSWORD").expect("DISCORD_PASSWORD")
	).expect("login failed");

	// Establish and use a websocket connection
	let (mut connection, ready) = discord.connect().expect("connect failed");
	let mut voice = VoiceConnection::new(ready.user.id.clone());

	connection.voice_connect(
		&ServerId(env::var("DISCORD_SERVER").expect("DISCORD_SERVER")),
		&ChannelId(env::var("DISCORD_CHANNEL").expect("DISCORD_CHANNEL")),
	);

	voice.play(
		voice::open_ffmpeg_stream(
			&env::var("DISCORD_AUDIO").expect("DISCORD_AUDIO")
		).expect("File read failed")
	);

	println!("Ready.");
	loop {
		let event = match connection.recv_event() {
			Ok(event) => event,
			Err(err) => {
				println!("Receive error: {:?}", err);
				break
			}
		};
		voice.update(&event);
		match event {
			Event::Closed(n) => {
				println!("Discord closed on us with status {}", n);
				break
			}
			_ => {}
		}
	}

	// Log out from the API
	discord.logout().expect("logout failed");
}
<commit_msg>Remove subpar voice example, instead see dj example<commit_after><|endoftext|>


<commit_before><commit_msg>cpsr: refactoring + tabs2space<commit_after><|endoftext|>


<commit_before><commit_msg>add a parser benchmark<commit_after>#![feature(test)]
extern crate test;

extern crate lambda_calculus as lambda;

use test::Bencher;
use lambda::parser::*;

#[bench]
fn parsing_debruijn(b: &mut Bencher) {
    let blc = "(λ11)(λλλ1(λλλλ3(λ5(3(λ2(3(λλ3(λ123)))(4(λ4(λ31(21))))))(1(2(λ12))\
        (λ4(λ4(λ2(14)))5))))(33)2)(λ1((λ11)(λ11)))";
    b.iter(|| { let _ = parse(&blc, DeBruijn); } );
}

#[bench]
fn parsing_classic(b: &mut Bencher) {
    let blc = "(λa.a a) (λa.λb.λc.c (λd.λe.λf.λg.e (λh.d (f (λi.h (g (λj.λk.i (λl.l k j)))\
     (f (λj.g (λk.i k (j k)))))) (h (g (λi.i h)) (λi.f (λj.g (λk.j (k h))) e)))) (a a) b)\
      (λa.a ((λb.b b) (λb.b b)))";
    b.iter(|| { let _ = parse(&blc, Classic); } );
}
<|endoftext|>


<commit_before><commit_msg>Add problem #127<commit_after>#[crate_type = "rlib"];

use std::{iter, vec};

pub static EXPECTED_ANSWER: &'static str = "18407904";

// [定理]
// a + b = c のとき、
// GCD(a, b) = 1 => GCD(a, c) = GCD(b, c) = 1
//
// [証明]
// まず、GCD(a, b) = 1 => GCD(a, c) = 1 を示す。
// GCD(a, b) のとき、GCD(a, c) = k > 1 であると仮定すると、
// 整数 n, m を用いて a = kn, c = km と表すことができる。
// b = c - a = km - kn = k(m, n) より、GCD(a, b) >= k となり矛盾。
// よって、GCD(a, c) = 1 である。
//
// 次に、GCD(a, b) = 1 => GCD(b, c) = 1 を示す。
// GCD(a, b) = 1 のとき、GCD(b, c) = k > 1 であると仮定すると、
// 整数 n, m を用いて b = kn, c = km と表すことができる。
// ここで、a = c - b = km - kn = k(m - n) より、 GCD(a, b) >= k となり矛盾。
// よって、GCD(b, c) = 1 である。

#[deriving(Eq)]
struct Rad(uint, ~[uint]);

fn create_rad_vec(n_limit: uint) -> ~[Rad] {
    let mut rad_vec = vec::from_fn(n_limit, |_| Rad(1, ~[]));
    for p in range(2, rad_vec.len()) {
        let Rad(n, _) = rad_vec[p];
        if n != 1 { continue }

        for np in iter::count(p, p).take_while(|&np| np < n_limit) {
            let Rad(ref mut n, ref mut facts) = rad_vec[np];
            (*n) *= p;
            facts.push(p);
        }
    }
    rad_vec
}

fn rad_has_union(&Rad(_, ref a): &Rad, &Rad(_, ref b): &Rad) -> bool {
    let mut i_a = 0;
    let mut i_b = 0;

    loop {
        if i_a >= a.len() || i_b >= b.len() { return false }
        match a[i_a].cmp(&b[i_b]) {
            Equal   => return true,
            Less    => i_a += 1,
            Greater => i_b += 1
        }
    }
}

fn abc_hits_c_sum(c_limit: uint) -> uint {
    let rad_vec = create_rad_vec(c_limit);
    let mut c_sum = 0;

    for c in range(3, c_limit) {
        let Rad(rad_c, _) = rad_vec[c];
        for a in range(1, (c + 1) / 2) {
            let b = c - a;
            let Rad(rad_a, _) = rad_vec[a];
            let Rad(rad_b, _) = rad_vec[b];
            let rad_abc = rad_a * rad_b * rad_c;
            if rad_abc >= c || (a > 1 && rad_has_union(&rad_vec[a], &rad_vec[c])) { continue; }
            c_sum += c;
        }
    }

    c_sum
}

pub fn solve() -> ~str { abc_hits_c_sum(120000).to_str() }

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

    #[test]
    fn create_rad_vec() {
        let rad_vec = ~[
            Rad(1, ~[]), Rad(1, ~[]), Rad(2, ~[2]), Rad(3, ~[3]), Rad(2, ~[2]), Rad(5, ~[5]),
            Rad(6, ~[2, 3]), Rad(7, ~[7]), Rad(2, ~[2]), Rad(3, ~[3])];
        assert_eq!(rad_vec, super::create_rad_vec(10))
    }

    #[test]
    fn rad_has_union() {
        assert!(super::rad_has_union(&Rad(2, ~[2]), &Rad(2, ~[2])));
        assert!(!super::rad_has_union(&Rad(2, ~[2]), &Rad(3, ~[4])));

        assert!(super::rad_has_union(&Rad(3, ~[3]), &Rad(6, ~[2, 3])));
        assert!(super::rad_has_union(&Rad(15, ~[3, 5]), &Rad(10, ~[2, 5])));

        assert!(!super::rad_has_union(&Rad(30, ~[2, 3, 5]), &Rad(1001, ~[7, 11, 13])));
    }

    #[test]
    fn abc_hits_c_sum() {
        assert_eq!(12523, super::abc_hits_c_sum(1000));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for #13259. Closes #13259 and #14742<commit_after>extern crate libc;
use libc::{c_void, LPVOID, DWORD};
use libc::types::os::arch::extra::LPWSTR;

extern "system" {
    fn FormatMessageW(flags: DWORD,
                      lpSrc: LPVOID,
                      msgId: DWORD,
                      langId: DWORD,
                      buf: LPWSTR,
                      nsize: DWORD,
                      args: *const c_void)
                      -> DWORD;
}

fn test() {
    let mut buf: [u16, ..50] = [0, ..50];
    let ret = unsafe {
        FormatMessageW(0x1000, 0 as *mut c_void, 1, 0x400,
                       buf.as_mut_ptr(), buf.len() as u32, 0 as *const c_void)
    };
    // On some 32-bit Windowses (Win7-8 at least) this will fail with segmented
    // stacks taking control of pvArbitrary
    assert!(ret != 0);
}
fn main() {
    test()
}<|endoftext|>


<commit_before><commit_msg>Auto merge of #360 - sru:errors-wrong-num-values, r=Vinatorul<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to add renamed header.rs<commit_after>// Non-camel case types are used for Stomp Protocol version enum variants
#![allow(non_camel_case_types)]

use std::slice::Items;

// Ideally this would be a simple typedef. However:
// See Rust bug #11047: https://github.com/mozilla/rust/issues/11047
// Cannot call static methods (`with_capacity`) on type aliases (`HeaderList`)
pub struct HeaderList {
  pub headers: Vec<Header>
}

impl HeaderList {
  pub fn new() -> HeaderList {
    HeaderList::with_capacity(0)
  }
  pub fn with_capacity(capacity: uint) -> HeaderList {
    HeaderList {
      headers: Vec::with_capacity(capacity)
    }
  }

  pub fn push(&mut self, header: Header) {
    self.headers.push(header);
  }

  pub fn iter<'a>(&'a self) -> Items<'a, Header> {
    self.headers.iter()
  }

}

pub struct Header {
  buffer : String,
  delimiter_index : uint
}

impl Header {
  fn from_string(raw_string: &str) -> Option<Header> {
    let delimiter_index = match raw_string.find(':') {
      Some(index) => index,
      None => return None
    };
    let mut header = Header{
      buffer: raw_string.to_string(),
      delimiter_index: delimiter_index
    };
    header = Header::decode_key_value(header.get_key(), header.get_value());
    Some(header)
  }

  pub fn encode_string(raw_string: &str) -> Option<Header> {
    let header = Header::from_string(raw_string);
    header.map(|h| Header::encode_key_value(h.get_key(), h.get_value()))
  }

  pub fn decode_string(raw_string: &str) -> Option<Header> {
    let header = Header::from_string(raw_string);
    header.map(|h| Header::decode_key_value(h.get_key(), h.get_value()))
  }

  pub fn encode_key_value(key: &str, value: &str) -> Header {
    let raw_string = format!("{}:{}", key, Header::encode_value(value));
    Header {
      buffer: raw_string,
      delimiter_index: key.len()
    }
  }

  pub fn decode_key_value(key: &str, value: &str) -> Header {
    let raw_string = format!("{}:{}", key, Header::decode_value(value));
    Header {
      buffer: raw_string,
      delimiter_index: key.len()
    }
  }

  //TODO: Optimize this method.
  fn decode_value(value: &str) -> String {
    value
      .replace(r"\c", ":")
      .replace(r"\n", "\n")
      .replace(r"\r", "\r")
      .replace(r"\\", "\\")
  }

//TODO: Optimize this method.
  fn encode_value(value: &str) -> String {
    value
      .replace("\\", r"\\") // Order is significant
      .replace("\r", r"\r")
      .replace("\n", r"\n")
      .replace(":", r"\c")
  }

  pub fn get_raw<'a>(&'a self) -> &'a str {
    self.buffer.as_slice()
  }

  pub fn get_key<'a>(&'a self) -> &'a str {
    self.buffer.as_slice().slice_to(self.delimiter_index)
  }

  pub fn get_value<'a>(&'a self) -> &'a str {
    self.buffer.as_slice().slice_from(self.delimiter_index+1)
  }

}

// Headers in the Spec
pub struct AcceptVersion(pub Vec<StompVersion>);
pub struct Ack<'a>(pub &'a str);
pub struct ContentLength(pub uint);
pub struct Custom(pub Header);
pub struct Destination<'a> (pub &'a str);
pub struct HeartBeat(pub uint, uint);
pub struct Host<'a>(pub &'a str);
pub struct Id<'a>(pub &'a str);
pub struct Login<'a>(pub &'a str);
pub struct MessageId<'a>(pub &'a str);
pub struct Passcode<'a>(pub &'a str);
pub struct Receipt<'a>(pub &'a str);
pub struct ReceiptId<'a>(pub &'a str);
pub struct Server<'a>(pub &'a str);
pub struct Session<'a> (pub &'a str);
pub struct Subscription<'a>(pub &'a str);
pub struct Transaction<'a>(pub &'a str);
pub struct Version(pub StompVersion);

pub enum StompVersion {
  Stomp_v1_0,
  Stomp_v1_1,
  Stomp_v1_2,
}

pub trait StompHeaderSet {
  fn get_content_length(&self) -> Option<ContentLength>;
  fn get_header<'a>(&'a self, key: &str) -> Option<&'a Header>;
  fn get_accept_version<'a>(&'a self) -> Option<Vec<StompVersion>>;
  fn get_ack<'a>(&'a self) -> Option<Ack<'a>>;
  fn get_destination<'a>(&'a self) -> Option<Destination<'a>>;
  fn get_heart_beat(&self) -> Option<HeartBeat>;
  fn get_host<'a>(&'a self) -> Option<Host<'a>>;
  fn get_id<'a>(&'a self) -> Option<Id<'a>>;
  fn get_login<'a>(&'a self) -> Option<Login<'a>>;
  fn get_message_id<'a>(&'a self) -> Option<MessageId<'a>>;
  fn get_passcode<'a>(&'a self) -> Option<Passcode<'a>>;
  fn get_receipt<'a>(&'a self) -> Option<Receipt<'a>>;
  fn get_receipt_id<'a>(&'a self) -> Option<ReceiptId<'a>>;
  fn get_server<'a>(&'a self) -> Option<Server<'a>>;
  fn get_session<'a>(&'a self) -> Option<Session<'a>>;
  fn get_subscription<'a>(&'a self) -> Option<Subscription<'a>>;
  fn get_transaction<'a>(&'a self) -> Option<Transaction<'a>>;
  fn get_version(&self) -> Option<Version>;
}

impl StompHeaderSet for HeaderList {

  fn get_header<'a>(&'a self, key: &str) -> Option<&'a Header>{
    self.headers.iter().find(|header|
      match **header {
        ref h if h.get_key() == key => true,
        _ => false
      }
    )
  }

  fn get_accept_version(&self) -> Option<Vec<StompVersion>> {
    let versions : &str = match self.get_header("accept-version") {
      Some(h) => h.get_value(),
      None => return None
    };
    let versions: Vec<StompVersion> = versions.split(',').filter_map(|v| match v.trim() {
      "1.0" => Some(Stomp_v1_0),
      "1.1" => Some(Stomp_v1_1),
      "1.2" => Some(Stomp_v1_2),
      _ => None
    }).collect();
    Some(versions)
  }

  fn get_ack<'a>(&'a self) -> Option<Ack<'a>> {
    match self.get_header("ack") {
      Some(h) => Some(Ack(h.get_value())),
      None => None
    }
  }

  fn get_destination<'a>(&'a self) -> Option<Destination<'a>> {
    match self.get_header("destination") {
      Some(h) => Some(Destination(h.get_value())),
      None => return None
    }
  }

  fn get_heart_beat(&self) -> Option<HeartBeat> {
    let spec = match self.get_header("heart-beat") {
      Some(h) => h.get_value(),
      None => return None
    };
    let spec_list: Vec<uint> = spec.split(',').filter_map(|str_val| from_str::<uint>(str_val)).collect();
    match spec_list.as_slice() {
      [x, y] => Some(HeartBeat(x, y)),
      _ => None
    }
  }

  fn get_host<'a>(&'a self) -> Option<Host<'a>> {
    match self.get_header("host") {
      Some(h) => Some(Host(h.get_value())),
      None => None
    }
  }

  fn get_id<'a>(&'a self) -> Option<Id<'a>> {
    match self.get_header("id") {
      Some(h) => Some(Id(h.get_value())),
      None => None
    }
  }

  fn get_login<'a>(&'a self) -> Option<Login<'a>> {
    match self.get_header("login"){
      Some(h) => Some(Login(h.get_value())),
      None => None
    }
  }

  fn get_message_id<'a>(&'a self) -> Option<MessageId<'a>> {
    match self.get_header("message-id"){
      Some(h) => Some(MessageId(h.get_value())),
      None => None
    }
  }

  fn get_passcode<'a>(&'a self) -> Option<Passcode<'a>> {
    match self.get_header("passcode"){
      Some(h) => Some(Passcode(h.get_value())),
      None => None
    }
  }

  fn get_receipt<'a>(&'a self) -> Option<Receipt<'a>> {
    match self.get_header("receipt"){
      Some(h) => Some(Receipt(h.get_value())),
      None => None
    }
  }

  fn get_receipt_id<'a>(&'a self) -> Option<ReceiptId<'a>> {
    match self.get_header("receipt-id"){
      Some(h) => Some(ReceiptId(h.get_value())),
      None => None
    }
  }

  fn get_server<'a>(&'a self) -> Option<Server<'a>> {
    match self.get_header("server"){
      Some(h) => Some(Server(h.get_value())),
      None => None
    }
  }

  fn get_session<'a>(&'a self) -> Option<Session<'a>> {
    match self.get_header("session"){
      Some(h) => Some(Session(h.get_value())),
      None => None
    }
  }

  fn get_subscription<'a>(&'a self) -> Option<Subscription<'a>> {
    match self.get_header("subscription"){
      Some(h) => Some(Subscription(h.get_value())),
      None => None
    }
  }

  fn get_transaction<'a>(&'a self) -> Option<Transaction<'a>> {
    match self.get_header("transaction"){
      Some(h) => Some(Transaction(h.get_value())),
      None => None
    }
  }

  fn get_version(&self) -> Option<Version> {
    let version = match self.get_header("version"){
      Some(h) => h.get_value(),
      None => return None
    };
    match (version).as_slice() {
      "1.0" => Some(Version(Stomp_v1_0)), // TODO: Impl FromStr for StompVersion
      "1.1" => Some(Version(Stomp_v1_1)),
      "1.2" => Some(Version(Stomp_v1_2)),
      _ => None
    }
  }

  fn get_content_length(&self) -> Option<ContentLength> {
    let length = match self.get_header("content-length") {
      Some(h) => h.get_value(),
      None => return None
    };
    match from_str::<uint>(length) {
      Some(l) => Some(ContentLength(l)),
      None => None
    }
  }

}

<|endoftext|>


<commit_before><commit_msg>use the position() method instead<commit_after><|endoftext|>


<commit_before>//! Window abstraction

use std::cell::RefCell;
use input::InputEvent;
use current::{ Get, Set, Usage };

use GenericEvent;

/// Whether window should close or not.
pub struct ShouldClose(pub bool);

/// Work-around trait for `Get<ShouldClose>`.
/// Used to support generic constraints.
pub trait GetShouldClose: Get<ShouldClose> {
    /// Returns whether window should close.
    fn get_should_close(&self) -> ShouldClose {
        self.get()
    }
}

impl<T: Get<ShouldClose>> GetShouldClose for T {}

/// Work-around trait for `Set<ShouldClose>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetShouldClose: Set<ShouldClose> {
    /// Sets whether window should close.
    fn set_should_close(&mut self, val: ShouldClose);
}

/// The size of the window.
pub struct Size(pub [u32, ..2]);

/// Work-around trait for `Get<Size>`.
/// Used to support generic constraints.
pub trait GetSize: Get<Size> {
    /// Returns the size of window.
    fn get_size(&self) -> Size {
        self.get()
    }
}

impl<T: Get<Size>> GetSize for T {}

/// Work-around trait for `Get<Size>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetSize: Set<Size> {
    /// Sets size of window.
    fn set_size(&mut self, val: Size);
}

#[test]
fn test_methods() {
    use current::Modifier;

    struct Obj;

    impl Get<ShouldClose> for Obj {
        fn get(&self) -> ShouldClose { ShouldClose(false) }
    }

    impl Modifier<Obj> for ShouldClose {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetShouldClose for Obj {
        fn set_should_close(&mut self, val: ShouldClose) {
            self.set_mut(val);
        }
    }

    impl Get<Size> for Obj {
        fn get(&self) -> Size { Size([0, 0]) }
    }

    impl Modifier<Obj> for Size {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetSize for Obj {
        fn set_size(&mut self, val: Size) {
            self.set_mut(val);
        }
    }

    fn foo<T: GetShouldClose
            + GetSize
            + SetShouldClose
            + SetSize>(_obj: T) {}

    foo(Obj);
}

/// Implemented by windows that can swap buffers.
pub trait SwapBuffers {
    /// Swaps the buffers.
    fn swap_buffers(&mut self);
}

impl<'a, W: 'a + SwapBuffers> SwapBuffers for Usage<'a, W> {
    #[inline(always)]
    fn swap_buffers(&mut self) {
        self.with_unwrap(|window: &RefCell<W>| {
            window.borrow_mut().deref_mut().swap_buffers()
        })
    }
}

impl<'a, W: 'a + SwapBuffers> SwapBuffers for &'a RefCell<W> {
    #[inline(always)]
    fn swap_buffers(&mut self) {
        self.borrow_mut().deref_mut().swap_buffers()
    }
}

/// Implemented by windows that can pull events.
pub trait PollEvent<E: GenericEvent> {
    /// Polls event from window.
    fn poll_event(&mut self) -> Option<E>;
}

impl<'a, W: 'a + PollEvent<I>, I: GenericEvent> PollEvent<I> for Usage<'a, W> {
    #[inline(always)]
    fn poll_event(&mut self) -> Option<I> {
        self.with_unwrap(|window: &RefCell<W>| {
            window.borrow_mut().deref_mut().poll_event()
        })
    }
}

impl<'a, W: 'a + PollEvent<I>, I: GenericEvent> PollEvent<I> for &'a RefCell<W> {
    #[inline(always)]
    fn poll_event(&mut self) -> Option<I> {
        self.borrow_mut().deref_mut().poll_event()
    }
}

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window<E: GenericEvent = InputEvent>:
    SwapBuffers
  + PollEvent<E>
  + GetShouldClose
  + GetSize {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32);

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool);
}

/// An implementation of Window that runs without a window at all.
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Returns a new `NoWindow`.
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl SwapBuffers for NoWindow {
    fn swap_buffers(&mut self) {}
}

impl PollEvent<InputEvent> for NoWindow {
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

impl Get<ShouldClose> for NoWindow {
    fn get(&self) -> ShouldClose {
        ShouldClose(self.should_close)
    }
}

impl Get<Size> for NoWindow {
    fn get(&self) -> Size {
        Size([0, 0])
    }
}

impl Window<InputEvent> for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_draw_size(&self) -> (u32, u32) {
        let Size([w, h]) = self.get_size();
        (w, h)
    }

    fn capture_cursor(&mut self, _enabled: bool) {}
}
<commit_msg>Added property types to window module<commit_after>//! Window abstraction

use std::cell::RefCell;
use input::InputEvent;
use current::{ Get, Set, Usage };

use GenericEvent;

/// Whether window should close or not.
pub struct ShouldClose(pub bool);

/// Work-around trait for `Get<ShouldClose>`.
/// Used to support generic constraints.
pub trait GetShouldClose: Get<ShouldClose> {
    /// Returns whether window should close.
    fn get_should_close(&self) -> ShouldClose {
        self.get()
    }
}

impl<T: Get<ShouldClose>> GetShouldClose for T {}

/// Work-around trait for `Set<ShouldClose>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetShouldClose: Set<ShouldClose> {
    /// Sets whether window should close.
    fn set_should_close(&mut self, val: ShouldClose);
}

/// The size of the window.
pub struct Size(pub [u32, ..2]);

/// Work-around trait for `Get<Size>`.
/// Used to support generic constraints.
pub trait GetSize: Get<Size> {
    /// Returns the size of window.
    fn get_size(&self) -> Size {
        self.get()
    }
}

impl<T: Get<Size>> GetSize for T {}

/// Work-around trait for `Set<Size>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetSize: Set<Size> {
    /// Sets size of window.
    fn set_size(&mut self, val: Size);
}

/// The title of the window.
pub struct Title(pub String);

/// Work-around trait for `Get<Title>`.
/// Used to support generic constraints.
pub trait GetTitle: Get<Title> {
    /// Returns the title of the window.
    fn get_title(&self) -> Title {
        self.get()
    }
}

impl<T: Get<Title>> GetTitle for T {}

/// Work-around trait for `Set<Title>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetTitle: Set<Title> {
    /// Sets title of window.
    fn set_title(&mut self, val: Title);
}

/// The anti-aliasing samples when rendering.
pub struct Samples(pub u8);

/// Work-around trait for `Get<Samples>`.
/// Used to support generic constraints.
pub trait GetSamples: Get<Samples> {
    /// Returns the antialiasing samples when rendering.
    fn get_samples(&self) -> Samples {
        self.get()
    }
}

impl<T: Get<Samples>> GetSamples for T {}

/// Work-around trait for `Set<Samples>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetSamples: Set<Samples> {
    /// Sets antialiasing samples of window.
    fn set_samples(&mut self, val: Samples);
}

/// Whether window is opened in full screen mode.
pub struct Fullscreen(pub bool);

/// Work-around trait for `Get<Fullscreen>`.
/// Used to support generic constraints.
pub trait GetFullscreen: Get<Fullscreen> {
    /// Returns whether window is in full screen mode.
    fn get_fullscreen(&self) -> Fullscreen {
        self.get()
    }
}

impl<T: Get<Fullscreen>> GetFullscreen for T {}

/// Work-around trait for `Set<Fullscreen>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetFullscreen: Set<Fullscreen> {
    /// Sets window to fullscreen mode.
    fn set_fullscreen(&mut self, val: Fullscreen);
}

/// Whether to exit when pressing the Esc keyboard button.
pub struct ExitOnEsc(pub bool);

/// Work-around trait for `Get<ExitOnEsc>`.
/// Used to support generic constraints.
pub trait GetExitOnEsc: Get<ExitOnEsc> {
    /// Returns whether window exits when pressing Esc.
    fn get_exit_on_esc(&self) -> ExitOnEsc {
        self.get()
    }
}

impl<T: Get<ExitOnEsc>> GetExitOnEsc for T {}

/// Work-around trait for `Set<ExitOnEsc>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetExitOnEsc: Set<ExitOnEsc> {
    /// Sets exit when pressing Esc.
    fn set_exit_on_esc(&mut self, val: ExitOnEsc);
}

/// Whether to capture the mouse cursor.
pub struct CaptureCursor(pub bool);

/// Work-around trait for `Get<CaptureCursor>`.
/// Used to support generic constraints.
pub trait GetCaptureCursor: Get<CaptureCursor> {
    /// Returns whether window captures cursor.
    fn get_capture_cursor(&self) -> CaptureCursor {
        self.get()
    }
}

impl<T: Get<CaptureCursor>> GetCaptureCursor for T {}

/// Work-around trait for `Set<CaptureCursor>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetCaptureCursor: Set<CaptureCursor> {
    /// Sets capture cursor.
    fn set_capture_cursor(&mut self, val: CaptureCursor);
}

/// The draw size of the window.
pub struct DrawSize(pub [u32, ..2]);

/// Work-around trait for `Get<DrawSize>`.
/// Used to support generic constraints.
pub trait GetDrawSize: Get<DrawSize> {
    /// Returns the draw size of window.
    fn get_draw_size(&self) -> DrawSize {
        self.get()
    }
}

impl<T: Get<DrawSize>> GetDrawSize for T {}

/// Work-around trait for `Set<DrawSize>`.
/// Used to support generic constraints.
/// This must be implemented for every `Modifier` impl.
pub trait SetDrawSize: Set<DrawSize> {
    /// Sets draw size.
    fn set_draw_size(&mut self, val: DrawSize);
}

#[test]
fn test_methods() {
    use current::Modifier;

    struct Obj;

    impl Get<ShouldClose> for Obj {
        fn get(&self) -> ShouldClose { ShouldClose(false) }
    }

    impl Modifier<Obj> for ShouldClose {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetShouldClose for Obj {
        fn set_should_close(&mut self, val: ShouldClose) {
            self.set_mut(val);
        }
    }

    impl Get<Size> for Obj {
        fn get(&self) -> Size { Size([0, 0]) }
    }

    impl Modifier<Obj> for Size {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetSize for Obj {
        fn set_size(&mut self, val: Size) {
            self.set_mut(val);
        }
    }

    impl Get<Title> for Obj {
        fn get(&self) -> Title { Title("hello".to_string()) }
    }

    impl Modifier<Obj> for Title {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetTitle for Obj {
        fn set_title(&mut self, val: Title) {
            self.set_mut(val);
        }
    }

    impl Get<Samples> for Obj {
        fn get(&self) -> Samples { Samples(0) }
    }

    impl Modifier<Obj> for Samples {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetSamples for Obj {
        fn set_samples(&mut self, val: Samples) {
            self.set_mut(val);
        }
    }

    impl Get<Fullscreen> for Obj {
        fn get(&self) -> Fullscreen { Fullscreen(false) }
    }

    impl Modifier<Obj> for Fullscreen {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetFullscreen for Obj {
        fn set_fullscreen(&mut self, val: Fullscreen) {
            self.set_mut(val);
        }
    }

    impl Get<ExitOnEsc> for Obj {
        fn get(&self) -> ExitOnEsc { ExitOnEsc(true) }
    }

    impl Modifier<Obj> for ExitOnEsc {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetExitOnEsc for Obj {
        fn set_exit_on_esc(&mut self, val: ExitOnEsc) {
            self.set_mut(val);
        }
    }

    impl Get<CaptureCursor> for Obj {
        fn get(&self) -> CaptureCursor { CaptureCursor(false) }
    }

    impl Modifier<Obj> for CaptureCursor {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetCaptureCursor for Obj {
        fn set_capture_cursor(&mut self, val: CaptureCursor) {
            self.set_mut(val);
        }
    }

    impl Get<DrawSize> for Obj {
        fn get(&self) -> DrawSize { DrawSize([0, 0]) }
    }

    impl Modifier<Obj> for DrawSize {
        fn modify(self, _obj: &mut Obj) {}
    }

    impl SetDrawSize for Obj {
        fn set_draw_size(&mut self, val: DrawSize) {
            self.set_mut(val);
        }
    }

    fn foo<T: GetShouldClose + SetShouldClose
            + GetSize + SetSize
            + GetTitle + SetTitle
            + GetSamples + SetSamples
            + GetFullscreen + SetFullscreen
            + GetExitOnEsc + SetExitOnEsc
            + GetCaptureCursor + SetCaptureCursor
            + GetDrawSize + SetDrawSize>(_obj: T) {}

    foo(Obj);
}

/// Implemented by windows that can swap buffers.
pub trait SwapBuffers {
    /// Swaps the buffers.
    fn swap_buffers(&mut self);
}

impl<'a, W: 'a + SwapBuffers> SwapBuffers for Usage<'a, W> {
    #[inline(always)]
    fn swap_buffers(&mut self) {
        self.with_unwrap(|window: &RefCell<W>| {
            window.borrow_mut().deref_mut().swap_buffers()
        })
    }
}

impl<'a, W: 'a + SwapBuffers> SwapBuffers for &'a RefCell<W> {
    #[inline(always)]
    fn swap_buffers(&mut self) {
        self.borrow_mut().deref_mut().swap_buffers()
    }
}

/// Implemented by windows that can pull events.
pub trait PollEvent<E: GenericEvent> {
    /// Polls event from window.
    fn poll_event(&mut self) -> Option<E>;
}

impl<'a, W: 'a + PollEvent<I>, I: GenericEvent> PollEvent<I> for Usage<'a, W> {
    #[inline(always)]
    fn poll_event(&mut self) -> Option<I> {
        self.with_unwrap(|window: &RefCell<W>| {
            window.borrow_mut().deref_mut().poll_event()
        })
    }
}

impl<'a, W: 'a + PollEvent<I>, I: GenericEvent> PollEvent<I> for &'a RefCell<W> {
    #[inline(always)]
    fn poll_event(&mut self) -> Option<I> {
        self.borrow_mut().deref_mut().poll_event()
    }
}

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window<E: GenericEvent = InputEvent>:
    SwapBuffers
  + PollEvent<E>
  + GetShouldClose
  + GetSize {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32);

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool);
}

/// An implementation of Window that runs without a window at all.
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Returns a new `NoWindow`.
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl SwapBuffers for NoWindow {
    fn swap_buffers(&mut self) {}
}

impl PollEvent<InputEvent> for NoWindow {
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

impl Get<ShouldClose> for NoWindow {
    fn get(&self) -> ShouldClose {
        ShouldClose(self.should_close)
    }
}

impl Get<Size> for NoWindow {
    fn get(&self) -> Size {
        Size([0, 0])
    }
}

impl Window<InputEvent> for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_draw_size(&self) -> (u32, u32) {
        let Size([w, h]) = self.get_size();
        (w, h)
    }

    fn capture_cursor(&mut self, _enabled: bool) {}
}
<|endoftext|>


<commit_before><commit_msg>Destroying dumb buffer test<commit_after>
extern crate drm;
use drm::Device;
use drm::mode::*;

#[test]
fn destroy_dumb() {
    let dev = Device::first_card().expect("Failed to open card");
    let buf = DumbBuf::<u32>::create(&dev, 640, 480).expect("Failed to crate dumbbuf");

    drop(buf);

    println!("Didn't panic!");
}
<|endoftext|>