<commit_before>use cairo;
use gdk;
use glib::object::Cast;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags};
use gtk::{ToggleButtonSignals, ToggleButtonExt, Widget, WidgetSignals, WindowExt};
use gtk::prelude::{Inhibit, WidgetExt};
use sysinfo;

use std::cell::RefCell;
use std::iter;
use std::rc::Rc;
use std::time::Instant;

use color::Color;
use notebook::NoteBook;
use utils::RotateVec;

#[allow(dead_code)]
pub struct DisplaySysInfo {
    procs : Rc<RefCell<Vec<gtk::ProgressBar>>>,
    ram : gtk::ProgressBar,
    swap : gtk::ProgressBar,
    vertical_layout : gtk::Box,
    components: Vec<gtk::Label>,
    cpu_usage_history: Rc<RefCell<Vec<(Color, RotateVec<f64>)>>>,
}

impl DisplaySysInfo {
    pub fn new(sys1: Rc<RefCell<sysinfo::System>>, note: &mut NoteBook,
               win: &gtk::Window) -> DisplaySysInfo {
        let vertical_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
        let mut procs = Vec::new();
        let ram = gtk::ProgressBar::new();
        let swap = gtk::ProgressBar::new();
        let scroll = gtk::ScrolledWindow::new(None, None);
        let proc_scroll = gtk::ScrolledWindow::new(None, None);
        let mut components = vec!();
        let mut cpu_usage_history = vec!();
        let check_box = gtk::CheckButton::new_with_label("Graph view");

        ram.set_show_text(true);
        swap.set_show_text(true);
        vertical_layout.set_spacing(5);

        let mut total = false;
        let proc_horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);
        let proc_vertical_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
        let non_graph_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);

        vertical_layout.pack_start(&gtk::Label::new(Some("Memory usage")), false, false, 15);
        vertical_layout.add(&ram);
        vertical_layout.pack_start(&gtk::Label::new(Some("Swap usage")), false, false, 15);
        vertical_layout.add(&swap);
        vertical_layout.pack_start(&gtk::Label::new(Some("Total CPU usage")), false, false, 7);
        for (i, pro) in sys1.borrow().get_processor_list().iter().enumerate() {
            if total {
                procs.push(gtk::ProgressBar::new());
                let p : &gtk::ProgressBar = &procs[i];
                let l = gtk::Label::new(Some(&format!("{}", i)));
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);

                p.set_text(Some(&format!("{:.2} %", pro.get_cpu_usage() * 100.)));
                p.set_show_text(true);
                p.set_fraction(pro.get_cpu_usage() as f64);
                horizontal_layout.pack_start(&l, false, false, 5);
                horizontal_layout.pack_start(p, true, true, 5);
                non_graph_layout.add(&horizontal_layout);
                let c = Color::generate(i + 10);
                let l = gtk::Label::new(Some(&format!("process {}", i)));
                l.override_color(StateFlags::from_bits(0).unwrap(), &c.to_gdk());
                cpu_usage_history.push((c,
                                        RotateVec::new(iter::repeat(0f64).take(60).collect())));
                proc_vertical_layout.add(&l);
            } else {
                procs.push(gtk::ProgressBar::new());
                let p : &gtk::ProgressBar = &procs[i];

                p.set_text(Some(&format!("{:.2} %", pro.get_cpu_usage() * 100.)));
                p.set_show_text(true);
                p.set_fraction(pro.get_cpu_usage() as f64);

                vertical_layout.add(p);
                let label = gtk::Label::new(Some("Process usage"));
                let empty = gtk::Label::new(None);
                let grid = gtk::Grid::new();
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);
                horizontal_layout.pack_start(&gtk::Label::new(None), true, true, 0);
                horizontal_layout.pack_start(&check_box, false, false, 0);
                grid.attach(&empty, 0, 0, 3, 1);
                grid.attach_next_to(&label, Some(&empty), gtk::PositionType::Right, 3, 1);
                grid.attach_next_to(&horizontal_layout, Some(&label),
                                    gtk::PositionType::Right, 3, 1);
                grid.set_column_homogeneous(true);
                vertical_layout.pack_start(&grid, false, false, 15);
                total = true;
            }
        }
        vertical_layout.add(&non_graph_layout);
        proc_scroll.set_min_content_width(90);
        if sys1.borrow().get_components_list().len() > 0 {
            vertical_layout.pack_start(&gtk::Label::new(Some("Components' temperature")),
                                       false, false, 15);
            for component in sys1.borrow().get_components_list() {
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 10);
                // TODO: add max and critical temperatures as well
                let temp = gtk::Label::new(Some(&format!("{:.1} °C", component.temperature)));
                horizontal_layout.pack_start(&gtk::Label::new(Some(&component.label)),
                                             true, false, 0);
                horizontal_layout.pack_start(&temp, true, false, 0);
                horizontal_layout.set_homogeneous(true);
                vertical_layout.add(&horizontal_layout);
                components.push(temp);
            }
        }

        let area = DrawingArea::new();
        //vertical_layout.add(&area);
        let start_time = Instant::now();
        let cpu_usage_history = Rc::new(RefCell::new(cpu_usage_history));
        let c_cpu_usage_history = cpu_usage_history.clone();
        area.connect_draw(move |w, c| {
            draw_grid(&c, w.get_allocated_width() as f64, w.get_allocated_height() as f64,
                      start_time.elapsed().as_secs(),
                      &mut c_cpu_usage_history.borrow_mut());
            Inhibit(false)
        });
        proc_horizontal_layout.add(&area);
        //proc_horizontal_layout.add(&proc_vertical_layout);
        proc_scroll.add(&proc_vertical_layout);
        proc_horizontal_layout.pack_start(&proc_scroll, false, true, 15);
        vertical_layout.add(&proc_horizontal_layout);

        scroll.add(&vertical_layout);
        let scroll : Widget = scroll.upcast();
        note.create_tab("System usage", &scroll);

        let mut tmp = DisplaySysInfo {
            procs: Rc::new(RefCell::new(procs)),
            ram: ram,
            swap: swap,
            vertical_layout: vertical_layout,
            components: components,
            cpu_usage_history: cpu_usage_history,
        };
        tmp.update_ram_display(&sys1.borrow());
        win.add_events(gdk::EventType::Configure as i32);
        // ugly way to resize drawing area, I should find a better way
        win.connect_configure_event(move |w, _| {
            let w = w.clone().upcast::<gtk::Window>().get_size().0 - 130;
            area.set_size_request(w, 200);
            Inhibit(false)
        });
        let c_check_box = check_box.clone();
        let c_proc_horizontal_layout = proc_horizontal_layout.clone();
        let c_non_graph_layout = non_graph_layout.clone();
        c_check_box.upcast::<gtk::ToggleButton>().connect_toggled(move |c| {
            show_if_necessary(c, &c_proc_horizontal_layout, &c_non_graph_layout);
        });
        scroll.connect_show(move |_| {
            show_if_necessary(&check_box.clone().upcast::<gtk::ToggleButton>(),
                              &proc_horizontal_layout, &non_graph_layout);
        });
        tmp
    }

    pub fn update_ram_display(&mut self, sys: &sysinfo::System) {
        let total = sys.get_total_memory();
        let used = sys.get_used_memory();
        let disp = if total < 100000 {
            format!("{} / {}KB", used, total)
        } else if total < 10000000 {
            format!("{} / {}MB", used / 1000, total / 1000)
        } else if total < 10000000000 {
            format!("{} / {}GB", used / 1000000, total / 1000000)
        } else {
            format!("{} / {}TB", used / 1000000000, total / 1000000000)
        };

        self.ram.set_text(Some(&disp));
        self.ram.set_fraction(used as f64 / total as f64);

        let total = sys.get_total_swap();
        let used = total - sys.get_used_swap();
        let disp = if total < 100000 {
            format!("{} / {}KB", used, total)
        } else if total < 10000000 {
            format!("{} / {}MB", used / 1000, total / 1000)
        } else if total < 10000000000 {
            format!("{} / {}GB", used / 1000000, total / 1000000)
        } else {
            format!("{} / {}TB", used / 1000000000, total / 1000000000)
        };

        self.swap.set_text(Some(&disp));
        self.swap.set_fraction(used as f64 / total as f64);

        for (component, label) in sys.get_components_list().iter().zip(self.components.iter()) {
            label.set_text(&format!("{:.1} °C", component.temperature));
        }
    }

    pub fn update_process_display(&mut self, sys: &sysinfo::System) {
        let v = &*self.procs.borrow_mut();
        let mut h = &mut *self.cpu_usage_history.borrow_mut();

        for (i, pro) in sys.get_processor_list().iter().enumerate() {
            v[i].set_text(Some(&format!("{:.1} %", pro.get_cpu_usage() * 100.)));
            v[i].set_show_text(true);
            v[i].set_fraction(pro.get_cpu_usage() as f64);
            if i > 0 {
                h[i - 1].1.move_start();
                *h[i - 1].1.get_mut(0).unwrap() = pro.get_cpu_usage() as f64;
            }
        }
    }
}

fn show_if_necessary(check_box: &gtk::ToggleButton, proc_horizontal_layout: &gtk::Box,
                     non_graph_layout: &gtk::Box) {
    if check_box.get_active() {
        proc_horizontal_layout.show_all();
        non_graph_layout.hide();
    } else {
        non_graph_layout.show_all();
        proc_horizontal_layout.hide();
    }
}

fn draw_grid(c: &cairo::Context, width: f64, height: f64, mut elapsed: u64,
             cpu_usage_history: &mut [(Color, RotateVec<f64>)]) {
    c.set_source_rgb(0.8, 0.8, 0.8);
    c.rectangle(2.0, 1.0, width - 2.0, height - 2.0);
    c.fill();
    c.set_source_rgb(0.0, 0.0, 0.0);
    c.set_line_width(1.0);
    c.move_to(1.0, 0.0);
    c.line_to(1.0, height);
    c.move_to(width, 0.0);
    c.line_to(width, height);
    c.move_to(1.0, 0.0);
    c.line_to(width, 0.0);
    c.move_to(1.0, height);
    c.line_to(width, height);
    elapsed = elapsed % 5;
    let x_step = width * 5.0 / 60.0;
    let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0;
    while current > 0.0 {
        c.move_to(current, 0.0);
        c.line_to(current, height);
        current -= x_step;
    }
    let step = height / 10.0;
    current = step - 1.0;
    while current < height {
        c.move_to(1.0, current);
        c.line_to(width - 1.0, current);
        current += step;
    }
    c.stroke();
    let len = cpu_usage_history[0].1.len() - 1;
    let step = (width - 2.0) / (len as f64);
    current = 1.0;
    let mut index = len;
    while current > 0.0 && index > 0 {
        for &(ref color, ref entry) in cpu_usage_history.iter() {
            c.set_source_rgb(color.r, color.g, color.b);
            c.move_to(current + step, height - entry[index - 1] * height - 2.0);
            c.line_to(current, height - entry[index] * height - 2.0);
            c.stroke();
        }
        current += step;
        index -= 1;
    }
}
<commit_msg>* Fix invalid order of widgets in system info * Fix invalid padding of graph grid<commit_after>use cairo;
use gdk;
use glib::object::Cast;
use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags};
use gtk::{ToggleButtonSignals, ToggleButtonExt, Widget, WidgetSignals, WindowExt};
use gtk::prelude::{Inhibit, WidgetExt};
use sysinfo;

use std::cell::RefCell;
use std::iter;
use std::rc::Rc;
use std::time::Instant;

use color::Color;
use notebook::NoteBook;
use utils::RotateVec;

#[allow(dead_code)]
pub struct DisplaySysInfo {
    procs : Rc<RefCell<Vec<gtk::ProgressBar>>>,
    ram : gtk::ProgressBar,
    swap : gtk::ProgressBar,
    vertical_layout : gtk::Box,
    components: Vec<gtk::Label>,
    cpu_usage_history: Rc<RefCell<Vec<(Color, RotateVec<f64>)>>>,
}

impl DisplaySysInfo {
    pub fn new(sys1: Rc<RefCell<sysinfo::System>>, note: &mut NoteBook,
               win: &gtk::Window) -> DisplaySysInfo {
        let vertical_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
        let mut procs = Vec::new();
        let ram = gtk::ProgressBar::new();
        let swap = gtk::ProgressBar::new();
        let scroll = gtk::ScrolledWindow::new(None, None);
        let proc_scroll = gtk::ScrolledWindow::new(None, None);
        let mut components = vec!();
        let mut cpu_usage_history = vec!();
        let check_box = gtk::CheckButton::new_with_label("Graph view");

        ram.set_show_text(true);
        swap.set_show_text(true);
        vertical_layout.set_spacing(5);

        let mut total = false;
        let proc_horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);
        let proc_vertical_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);
        let non_graph_layout = gtk::Box::new(gtk::Orientation::Vertical, 0);

        vertical_layout.pack_start(&gtk::Label::new(Some("Memory usage")), false, false, 15);
        vertical_layout.add(&ram);
        vertical_layout.pack_start(&gtk::Label::new(Some("Swap usage")), false, false, 15);
        vertical_layout.add(&swap);
        vertical_layout.pack_start(&gtk::Label::new(Some("Total CPU usage")), false, false, 7);
        for (i, pro) in sys1.borrow().get_processor_list().iter().enumerate() {
            if total {
                procs.push(gtk::ProgressBar::new());
                let p : &gtk::ProgressBar = &procs[i];
                let l = gtk::Label::new(Some(&format!("{}", i)));
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);

                p.set_text(Some(&format!("{:.2} %", pro.get_cpu_usage() * 100.)));
                p.set_show_text(true);
                p.set_fraction(pro.get_cpu_usage() as f64);
                horizontal_layout.pack_start(&l, false, false, 5);
                horizontal_layout.pack_start(p, true, true, 5);
                non_graph_layout.add(&horizontal_layout);
                let c = Color::generate(i + 10);
                let l = gtk::Label::new(Some(&format!("process {}", i)));
                l.override_color(StateFlags::from_bits(0).unwrap(), &c.to_gdk());
                cpu_usage_history.push((c,
                                        RotateVec::new(iter::repeat(0f64).take(60).collect())));
                proc_vertical_layout.add(&l);
            } else {
                procs.push(gtk::ProgressBar::new());
                let p : &gtk::ProgressBar = &procs[i];

                p.set_text(Some(&format!("{:.2} %", pro.get_cpu_usage() * 100.)));
                p.set_show_text(true);
                p.set_fraction(pro.get_cpu_usage() as f64);

                vertical_layout.add(p);
                let label = gtk::Label::new(Some("Process usage"));
                let empty = gtk::Label::new(None);
                let grid = gtk::Grid::new();
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 0);
                horizontal_layout.pack_start(&gtk::Label::new(None), true, true, 0);
                horizontal_layout.pack_start(&check_box, false, false, 0);
                grid.attach(&empty, 0, 0, 3, 1);
                grid.attach_next_to(&label, Some(&empty), gtk::PositionType::Right, 3, 1);
                grid.attach_next_to(&horizontal_layout, Some(&label),
                                    gtk::PositionType::Right, 3, 1);
                grid.set_column_homogeneous(true);
                vertical_layout.pack_start(&grid, false, false, 15);
                total = true;
            }
        }
        vertical_layout.add(&non_graph_layout);
        proc_scroll.set_min_content_width(90);

        let area = DrawingArea::new();
        //vertical_layout.add(&area);
        let start_time = Instant::now();
        let cpu_usage_history = Rc::new(RefCell::new(cpu_usage_history));
        let c_cpu_usage_history = cpu_usage_history.clone();
        area.connect_draw(move |w, c| {
            draw_grid(&c, w.get_allocated_width() as f64, w.get_allocated_height() as f64,
                      start_time.elapsed().as_secs(),
                      &mut c_cpu_usage_history.borrow_mut());
            Inhibit(false)
        });
        proc_horizontal_layout.add(&area);
        //proc_horizontal_layout.add(&proc_vertical_layout);
        proc_scroll.add(&proc_vertical_layout);
        proc_horizontal_layout.pack_start(&proc_scroll, false, true, 15);
        vertical_layout.add(&proc_horizontal_layout);

        if sys1.borrow().get_components_list().len() > 0 {
            vertical_layout.pack_start(&gtk::Label::new(Some("Components' temperature")),
                                       false, false, 15);
            for component in sys1.borrow().get_components_list() {
                let horizontal_layout = gtk::Box::new(gtk::Orientation::Horizontal, 10);
                // TODO: add max and critical temperatures as well
                let temp = gtk::Label::new(Some(&format!("{:.1} °C", component.temperature)));
                horizontal_layout.pack_start(&gtk::Label::new(Some(&component.label)),
                                             true, false, 0);
                horizontal_layout.pack_start(&temp, true, false, 0);
                horizontal_layout.set_homogeneous(true);
                vertical_layout.add(&horizontal_layout);
                components.push(temp);
            }
        }

        scroll.add(&vertical_layout);
        let scroll : Widget = scroll.upcast();
        note.create_tab("System usage", &scroll);

        let mut tmp = DisplaySysInfo {
            procs: Rc::new(RefCell::new(procs)),
            ram: ram,
            swap: swap,
            vertical_layout: vertical_layout,
            components: components,
            cpu_usage_history: cpu_usage_history,
        };
        tmp.update_ram_display(&sys1.borrow());
        win.add_events(gdk::EventType::Configure as i32);
        // ugly way to resize drawing area, I should find a better way
        win.connect_configure_event(move |w, _| {
            let w = w.clone().upcast::<gtk::Window>().get_size().0 - 130;
            area.set_size_request(w, 200);
            Inhibit(false)
        });
        let c_check_box = check_box.clone();
        let c_proc_horizontal_layout = proc_horizontal_layout.clone();
        let c_non_graph_layout = non_graph_layout.clone();
        c_check_box.upcast::<gtk::ToggleButton>().connect_toggled(move |c| {
            show_if_necessary(c, &c_proc_horizontal_layout, &c_non_graph_layout);
        });
        scroll.connect_show(move |_| {
            show_if_necessary(&check_box.clone().upcast::<gtk::ToggleButton>(),
                              &proc_horizontal_layout, &non_graph_layout);
        });
        tmp
    }

    pub fn update_ram_display(&mut self, sys: &sysinfo::System) {
        let total = sys.get_total_memory();
        let used = sys.get_used_memory();
        let disp = if total < 100000 {
            format!("{} / {}KB", used, total)
        } else if total < 10000000 {
            format!("{} / {}MB", used / 1000, total / 1000)
        } else if total < 10000000000 {
            format!("{} / {}GB", used / 1000000, total / 1000000)
        } else {
            format!("{} / {}TB", used / 1000000000, total / 1000000000)
        };

        self.ram.set_text(Some(&disp));
        self.ram.set_fraction(used as f64 / total as f64);

        let total = sys.get_total_swap();
        let used = total - sys.get_used_swap();
        let disp = if total < 100000 {
            format!("{} / {}KB", used, total)
        } else if total < 10000000 {
            format!("{} / {}MB", used / 1000, total / 1000)
        } else if total < 10000000000 {
            format!("{} / {}GB", used / 1000000, total / 1000000)
        } else {
            format!("{} / {}TB", used / 1000000000, total / 1000000000)
        };

        self.swap.set_text(Some(&disp));
        self.swap.set_fraction(used as f64 / total as f64);

        for (component, label) in sys.get_components_list().iter().zip(self.components.iter()) {
            label.set_text(&format!("{:.1} °C", component.temperature));
        }
    }

    pub fn update_process_display(&mut self, sys: &sysinfo::System) {
        let v = &*self.procs.borrow_mut();
        let mut h = &mut *self.cpu_usage_history.borrow_mut();

        for (i, pro) in sys.get_processor_list().iter().enumerate() {
            v[i].set_text(Some(&format!("{:.1} %", pro.get_cpu_usage() * 100.)));
            v[i].set_show_text(true);
            v[i].set_fraction(pro.get_cpu_usage() as f64);
            if i > 0 {
                h[i - 1].1.move_start();
                *h[i - 1].1.get_mut(0).unwrap() = pro.get_cpu_usage() as f64;
            }
        }
    }
}

fn show_if_necessary(check_box: &gtk::ToggleButton, proc_horizontal_layout: &gtk::Box,
                     non_graph_layout: &gtk::Box) {
    if check_box.get_active() {
        proc_horizontal_layout.show_all();
        non_graph_layout.hide();
    } else {
        non_graph_layout.show_all();
        proc_horizontal_layout.hide();
    }
}

fn draw_grid(c: &cairo::Context, width: f64, height: f64, mut elapsed: u64,
             cpu_usage_history: &mut [(Color, RotateVec<f64>)]) {
    let len = cpu_usage_history[0].1.len() - 1;
    c.set_source_rgb(0.8, 0.8, 0.8);
    c.rectangle(2.0, 1.0, width - 2.0, height - 2.0);
    c.fill();
    c.set_source_rgb(0.0, 0.0, 0.0);
    c.set_line_width(1.0);
    c.move_to(1.0, 0.0);
    c.line_to(1.0, height);
    c.move_to(width, 0.0);
    c.line_to(width, height);
    c.move_to(1.0, 0.0);
    c.line_to(width, 0.0);
    c.move_to(1.0, height);
    c.line_to(width, height);
    elapsed = elapsed % 5;
    let x_step = (width - 2.0) * 5.0 / (len as f64);
    let mut current = width - elapsed as f64 * (x_step / 5.0) - 1.0;
    while current > 0.0 {
        c.move_to(current, 0.0);
        c.line_to(current, height);
        current -= x_step;
    }
    let step = height / 10.0;
    current = step - 1.0;
    while current < height {
        c.move_to(1.0, current);
        c.line_to(width - 1.0, current);
        current += step;
    }
    c.stroke();
    let step = (width - 2.0) / (len as f64);
    current = 1.0;
    let mut index = len;
    while current > 0.0 && index > 0 {
        for &(ref color, ref entry) in cpu_usage_history.iter() {
            c.set_source_rgb(color.r, color.g, color.b);
            c.move_to(current + step, height - entry[index - 1] * height - 2.0);
            c.line_to(current, height - entry[index] * height - 2.0);
            c.stroke();
        }
        current += step;
        index -= 1;
    }
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate futuremio;
extern crate httparse;

use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;

use futures::Future;
use futures::stream::Stream;
use futuremio::{Loop, TcpStream};

mod request;
pub use self::request::{Request, RequestHeaders};

mod response;
pub use self::response::Response;

mod io2;
pub use io2::{Parse, Serialize};
use io2::{ParseStream, StreamWriter};

pub trait Service<Req, Resp>: Send + Sync + 'static
    where Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut: Future<Item = Resp>;

    fn process(&self, req: Req) -> Self::Fut;
}

impl<Req, Resp, Fut, F> Service<Req, Resp> for F
    where F: Fn(Req) -> Fut + Send + Sync + 'static,
          Fut: Future<Item = Resp>,
          Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut = Fut;

    fn process(&self, req: Req) -> Fut {
        (self)(req)
    }
}

pub fn serve<Req, Resp, S>(addr: &SocketAddr, s: S)
                           -> Result<(), <S::Fut as Future>::Error>
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>, // TODO: simplify this?
{
    let service = Arc::new(s);
    let lp = Loop::new().unwrap();

    let listen = lp.handle().tcp_listen(addr)
        .map_err(From::from)
        .and_then(move |listener| {
            listener.incoming().map(move |(stream, _)| {
                handle(stream, service.clone())
            }).boxed().map_err(From::from).buffered(8).for_each(|()| Ok(()))
        })
    .boxed();
    lp.run(listen)
}

fn handle<Req, Resp, S>(stream: TcpStream, service: Arc<S>)
                        -> Box<Future<Item=(), Error=<S::Fut as Future>::Error>>
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>,
{
    // hack around lack of Read/Write impl on Arc<...>
    let read = SourceWrapper(stream.source.clone());
    let write = SourceWrapper(stream.source);

    let input = ParseStream::new(read, stream.ready_read)
        .map_err(From::from);
    let responses = input.boxed().and_then(move |req| service.process(req)).boxed();
    let output = StreamWriter::new(write, stream.ready_write, responses);

    output.boxed()
}

// TODO: clean this up
// Hack around the lack of forwarding Read/Write impls for Arc<TcpStream>
struct SourceWrapper<S>(Arc<S>);

impl<S> Read for SourceWrapper<S>
    where for<'a> &'a S: Read
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (&*self.0).read(buf)
    }
}

impl<S> Write for SourceWrapper<S>
    where for<'a> &'a S: Write
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        (&*self.0).write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        (&*self.0).flush()
    }
}
<commit_msg>Use buffered() correctly in http<commit_after>extern crate futures;
extern crate futuremio;
extern crate httparse;

use std::io::{self, Read, Write};
use std::net::SocketAddr;
use std::sync::Arc;

use futures::Future;
use futures::stream::Stream;
use futuremio::{Loop, TcpStream};

mod request;
pub use self::request::{Request, RequestHeaders};

mod response;
pub use self::response::Response;

mod io2;
pub use io2::{Parse, Serialize};
use io2::{ParseStream, StreamWriter};

pub trait Service<Req, Resp>: Send + Sync + 'static
    where Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut: Future<Item = Resp>;

    fn process(&self, req: Req) -> Self::Fut;
}

impl<Req, Resp, Fut, F> Service<Req, Resp> for F
    where F: Fn(Req) -> Fut + Send + Sync + 'static,
          Fut: Future<Item = Resp>,
          Req: Send + 'static,
          Resp: Send + 'static
{
    type Fut = Fut;

    fn process(&self, req: Req) -> Fut {
        (self)(req)
    }
}

pub fn serve<Req, Resp, S>(addr: &SocketAddr, s: S) -> io::Result<()>
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>, // TODO: simplify this?
{
    let service = Arc::new(s);
    let lp = Loop::new().unwrap();

    let listen = lp.handle().tcp_listen(addr)
        .map_err(From::from)
        .and_then(move |listener| {
            listener.incoming().for_each(move |(stream, _)| {
                handle(stream, service.clone());
                Ok(()) // TODO: some kind of error handling
            })
        })
        .boxed();
    lp.run(listen)
}

fn handle<Req, Resp, S>(stream: TcpStream, service: Arc<S>)
    where Req: Parse,
          Resp: Serialize,
          S: Service<Req, Resp>,
          <S::Fut as Future>::Error: From<Req::Error> + From<io::Error>,
{
    // hack around lack of Read/Write impl on Arc<...>
    let read = SourceWrapper(stream.source.clone());
    let write = SourceWrapper(stream.source);

    let input = ParseStream::new(read, stream.ready_read)
        .map_err(From::from);
    let responses = input.boxed().and_then(move |req| service.process(req)).boxed();
    let output = StreamWriter::new(write, stream.ready_write, responses);

    // Crucially use `.forget()` here instead of returning the future, allows
    // processing multiple separate connections concurrently.
    output.forget()
}

// TODO: clean this up
// Hack around the lack of forwarding Read/Write impls for Arc<TcpStream>
struct SourceWrapper<S>(Arc<S>);

impl<S> Read for SourceWrapper<S>
    where for<'a> &'a S: Read
{
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (&*self.0).read(buf)
    }
}

impl<S> Write for SourceWrapper<S>
    where for<'a> &'a S: Write
{
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        (&*self.0).write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        (&*self.0).flush()
    }
}
<|endoftext|>


<commit_before>use audio::ac97::*;
use audio::intelhda::*;

use common::debug::*;
use common::queue::*;
use common::vec::*;

use drivers::pciconfig::*;

use network::intel8254x::*;
use network::rtl8139::*;

use programs::session::Session;

use schemes::file::*;

use usb::ehci::*;
use usb::uhci::*;
use usb::xhci::*;

/// PCI device
pub unsafe fn pci_device(session: &mut Session,
                         mut pci: PCIConfig,
                         class_id: u32,
                         subclass_id: u32,
                         interface_id: u32,
                         vendor_code: u32,
                         device_code: u32) {
    if class_id == 0x01 && subclass_id == 0x01 {
        if let Some(module) = FileScheme::new(pci) {
            session.items.push(module);
        }
    } else if class_id == 0x0C && subclass_id == 0x03 {
        if interface_id == 0x30 {
            let base = pci.read(0x10) as usize;

            let module = box XHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x20 {
            let base = pci.read(0x10) as usize;

            let mut module = box EHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x10 {
            let base = pci.read(0x10) as usize;

            d("OHCI Controller on ");
            dh(base & 0xFFFFFFF0);
            dl();
        } else if interface_id == 0x00 {
            session.items.push(UHCI::new(pci));
        } else {
            d("Unknown USB interface version\n");
        }
    } else {
        match vendor_code {
            0x10EC => match device_code { // REALTEK
                0x8139 => {
                    session.items.push(RTL8139::new(pci));
                }
                _ => (),
            },
            0x8086 => match device_code { // INTEL
                0x100E => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box Intel8254x {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                        resources: Vec::new(),
                        inbound: Queue::new(),
                        outbound: Queue::new(),
                    };
                    module.init();
                    session.items.push(module);
                }
                0x2415 => session.items.push(AC97::new(pci)),
                0x24C5 => session.items.push(AC97::new(pci)),
                0x2668 => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box IntelHDA {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                    };
                    module.init();
                    session.items.push(module);
                }
                _ => (),
            },
            _ => (),
        }
    }
}

/// Initialize PCI session
pub unsafe fn pci_init(session: &mut Session) {
    for bus in 0..256 {
        for slot in 0..32 {
            for func in 0..8 {
                let mut pci = PCIConfig::new(bus as u8, slot as u8, func as u8);
                let id = pci.read(0);

                if (id & 0xFFFF) != 0xFFFF {
                    let class_id = pci.read(8);

                    d("Bus ");
                    dd(bus);
                    d(" Slot ");
                    dd(slot);
                    d(" Function ");
                    dd(func);
                    d(": ");
                    dh(id as usize);
                    d(", ");
                    dh(class_id as usize);

                    for i in 0..6 {
                        let bar = pci.read(i * 4 + 0x10);
                        if bar > 0 {
                            d(" BAR");
                            dd(i as usize);
                            d(": ");
                            dh(bar as usize);
                        }
                    }

                    dl();

                    pci_device(session,
                               pci,
                               (class_id >> 24) & 0xFF,
                               (class_id >> 16) & 0xFF,
                               (class_id >> 8) & 0xFF,
                               id & 0xFFFF,
                               (id >> 16) & 0xFFFF);
                }
            }
        }
    }
}
<commit_msg>Show size of BAR's<commit_after>use audio::ac97::*;
use audio::intelhda::*;

use common::debug::*;
use common::queue::*;
use common::vec::*;

use drivers::pciconfig::*;

use network::intel8254x::*;
use network::rtl8139::*;

use programs::session::Session;

use schemes::file::*;

use usb::ehci::*;
use usb::uhci::*;
use usb::xhci::*;

/// PCI device
pub unsafe fn pci_device(session: &mut Session,
                         mut pci: PCIConfig,
                         class_id: u32,
                         subclass_id: u32,
                         interface_id: u32,
                         vendor_code: u32,
                         device_code: u32) {
    if class_id == 0x01 && subclass_id == 0x01 {
        if let Some(module) = FileScheme::new(pci) {
            session.items.push(module);
        }
    } else if class_id == 0x0C && subclass_id == 0x03 {
        if interface_id == 0x30 {
            let base = pci.read(0x10) as usize;

            let module = box XHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x20 {
            let base = pci.read(0x10) as usize;

            let mut module = box EHCI {
                pci: pci,
                base: base & 0xFFFFFFF0,
                memory_mapped: base & 1 == 0,
                irq: pci.read(0x3C) as u8 & 0xF,
            };
            module.init();
            session.items.push(module);
        } else if interface_id == 0x10 {
            let base = pci.read(0x10) as usize;

            d("OHCI Controller on ");
            dh(base & 0xFFFFFFF0);
            dl();
        } else if interface_id == 0x00 {
            session.items.push(UHCI::new(pci));
        } else {
            d("Unknown USB interface version\n");
        }
    } else {
        match vendor_code {
            0x10EC => match device_code { // REALTEK
                0x8139 => {
                    session.items.push(RTL8139::new(pci));
                }
                _ => (),
            },
            0x8086 => match device_code { // INTEL
                0x100E => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box Intel8254x {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                        resources: Vec::new(),
                        inbound: Queue::new(),
                        outbound: Queue::new(),
                    };
                    module.init();
                    session.items.push(module);
                }
                0x2415 => session.items.push(AC97::new(pci)),
                0x24C5 => session.items.push(AC97::new(pci)),
                0x2668 => {
                    let base = pci.read(0x10) as usize;
                    let mut module = box IntelHDA {
                        pci: pci,
                        base: base & 0xFFFFFFF0,
                        memory_mapped: base & 1 == 0,
                        irq: pci.read(0x3C) as u8 & 0xF,
                    };
                    module.init();
                    session.items.push(module);
                }
                _ => (),
            },
            _ => (),
        }
    }
}

/// Initialize PCI session
pub unsafe fn pci_init(session: &mut Session) {
    for bus in 0..256 {
        for slot in 0..32 {
            for func in 0..8 {
                let mut pci = PCIConfig::new(bus as u8, slot as u8, func as u8);
                let id = pci.read(0);

                if (id & 0xFFFF) != 0xFFFF {
                    let class_id = pci.read(8);

                    d(" * PCI ");
                    dd(bus);
                    d(", ");
                    dd(slot);
                    d(", ");
                    dd(func);
                    d(": ID ");
                    dh(id as usize);
                    d(" CL ");
                    dh(class_id as usize);

                    for i in 0..6 {
                        let bar = pci.read(i * 4 + 0x10);
                        if bar > 0 {
                            d(" BAR");
                            dd(i as usize);
                            d(": ");
                            dh(bar as usize);

                            pci.write(i * 4 + 0x10, 0xFFFFFFFF);
                            let size = (0xFFFFFFFF - (pci.read(i * 4 + 0x10) & 0xFFFFFFF0)) + 1;
                            pci.write(i * 4 + 0x10, bar);

                            if size > 0 {
                                d(" ");
                                dd(size as usize);
                            }
                        }
                    }

                    dl();

                    pci_device(session,
                               pci,
                               (class_id >> 24) & 0xFF,
                               (class_id >> 16) & 0xFF,
                               (class_id >> 8) & 0xFF,
                               id & 0xFFFF,
                               (id >> 16) & 0xFFFF);
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! The tags extracted from an audio file.

use sndfile::{SndFile, Title, Copyright, Software, Artist, Comment, Date,
              Album, License, TrackNumber, Genre};

/**
 * Structure containing the tags of a sound.
 *
 * If the tags doesn't exist in the sound file, the string is ~"".
 */
#[deriving(Clone)]
pub struct Tags {
    /// The title of the sound as a ~str
    Title       : ~str,
    /// The Copyright of the sound as a ~str
    Copyright   : ~str,
    /// The name of the software used to create the sound as a ~str
    Software    : ~str,
    /// The name of the artist of the sound as a ~str
    Artist      : ~str,
    /// A comment as a ~str
    Comment     : ~str,
    /// The creation date of the sound as a ~str
    Date        : ~str,
    /// The name of the album where the sound come from as a ~str
    Album       : ~str,
    /// The license of the sound as a ~str
    License     : ~str,
    /// The tracknumber of the sound as a ~str
    TrackNumber : ~str,
    /// The genre of the sound as a ~str
    Genre       : ~str
}

pub fn empty() -> Tags {
    Tags {
        Title       : ~"",
        Copyright   : ~"",
        Software    : ~"",
        Artist      : ~"",
        Comment     : ~"",
        Date        : ~"",
        Album       : ~"",
        License     : ~"",
        TrackNumber : ~"",
        Genre       : ~""
    }
}

pub fn get_sound_tags(file : &SndFile) -> Tags {
    Tags {
        Title       : file.get_string(Title).unwrap_or(~""),
        Copyright   : file.get_string(Copyright).unwrap_or(~""),
        Software    : file.get_string(Software).unwrap_or(~""),
        Artist      : file.get_string(Artist).unwrap_or(~""),
        Comment     : file.get_string(Comment).unwrap_or(~""),
        Date        : file.get_string(Date).unwrap_or(~""),
        Album       : file.get_string(Album).unwrap_or(~""),
        License     : file.get_string(License).unwrap_or(~""),
        TrackNumber : file.get_string(TrackNumber).unwrap_or(~""),
        Genre       : file.get_string(Genre).unwrap_or(~"")
    }
}

/// AudioTags trait implemented by all struct who can provides audio.
pub trait AudioTags{
    /// Get the tags of the audio source.
    fn get_tags(&self) -> Tags;
}
<commit_msg>fix warnings from last rust.<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2013 Jeremy Letang (letang.jeremy@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! The tags extracted from an audio file.

use sndfile::{SndFile, Title, Copyright, Software, Artist, Comment, Date,
              Album, License, TrackNumber, Genre};

/**
 * Structure containing the tags of a sound.
 *
 * If the tags doesn't exist in the sound file, the string is ~"".
 */
#[deriving(Clone)]
pub struct Tags {
    /// The title of the sound as a ~str
    title       : ~str,
    /// The Copyright of the sound as a ~str
    copyright   : ~str,
    /// The name of the software used to create the sound as a ~str
    software    : ~str,
    /// The name of the artist of the sound as a ~str
    artist      : ~str,
    /// A comment as a ~str
    comment     : ~str,
    /// The creation date of the sound as a ~str
    date        : ~str,
    /// The name of the album where the sound come from as a ~str
    album       : ~str,
    /// The license of the sound as a ~str
    license     : ~str,
    /// The tracknumber of the sound as a ~str
    trackNumber : ~str,
    /// The genre of the sound as a ~str
    genre       : ~str
}

pub fn empty() -> Tags {
    Tags {
        title       : ~"",
        copyright   : ~"",
        software    : ~"",
        artist      : ~"",
        comment     : ~"",
        date        : ~"",
        album       : ~"",
        license     : ~"",
        trackNumber : ~"",
        genre       : ~""
    }
}

pub fn get_sound_tags(file : &SndFile) -> Tags {
    Tags {
        title       : file.get_string(Title).unwrap_or(~""),
        copyright   : file.get_string(Copyright).unwrap_or(~""),
        software    : file.get_string(Software).unwrap_or(~""),
        artist      : file.get_string(Artist).unwrap_or(~""),
        comment     : file.get_string(Comment).unwrap_or(~""),
        date        : file.get_string(Date).unwrap_or(~""),
        album       : file.get_string(Album).unwrap_or(~""),
        license     : file.get_string(License).unwrap_or(~""),
        trackNumber : file.get_string(TrackNumber).unwrap_or(~""),
        genre       : file.get_string(Genre).unwrap_or(~"")
    }
}

/// AudioTags trait implemented by all struct who can provides audio.
pub trait AudioTags{
    /// Get the tags of the audio source.
    fn get_tags(&self) -> Tags;
}
<|endoftext|>


<commit_before>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match key_event.character {
                '0' if !no_mult => times *= 10,

                '1' if no_mult => times = 1,
                '1' => times = times * 10 + 1,

                '2' if no_mult => times = 2,
                '2' => times = times * 10 + 2,

                '3' if no_mult => times = 3,
                '3' => times = times * 10 + 3,

                '4' if no_mult => times = 4,
                '4' => times = times * 10 + 4,

                '5' if no_mult => times = 5,
                '5' => times = times * 10 + 5,

                '6' if no_mult => times = 6,
                '6' => times = times * 10 + 6,

                '7' if no_mult => times = 7,
                '7' => times = times * 10 + 7,

                '8' if no_mult => times = 8,
                '8' => times = times * 10 + 8,

                '9' if no_mult => times = 9,
                '9' => times = times * 10 + 9,
                _ => {
                    for _ in 0 .. times {
                        match (m, key_event.character) {
                            (Normal, 'i') => {
                                *mode = Insert;
                                *last_change = editor.string.clone();
                            },
                            (Normal, 'h') => editor.left(),
                            (Normal, 'l') => editor.right(),
                            (Normal, 'k') => editor.up(),
                            (Normal, 'j') => editor.down(),
                            (Normal, 'G') => editor.offset = editor.string.len(),
                            (Normal, 'a') => {
                                editor.right();
                                *mode = Insert;
                                *last_change = editor.string.clone();
                            },
                            (Normal, 'x') => editor.delete(window),
                            (Normal, 'X') => editor.backspace(window),
                            (Normal, 'u') => {
                                editor.offset = 0;
                                ::core::mem::swap(last_change, &mut editor.string);
                            },
                            (Normal, '$') => {
                                let mut new_offset = editor.string.len();
                                for i in editor.offset..editor.string.len() {
                                    match editor.string.as_bytes()[i] {
                                        0 => break,
                                        10 => {
                                            new_offset = i;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                editor.offset = new_offset;
                            },
                            (Normal, '0') => {

                                let mut new_offset = 0;
                                for i in 2..editor.offset {
                                    match editor.string.as_bytes()[editor.offset - i] {
                                        0 => break,
                                        10 => {
                                            new_offset = editor.offset - i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                editor.offset = new_offset;
                            },
                            (Insert, '\0') => (),
                            (Insert, _) => {
                                window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                editor.string = editor.string[0 .. editor.offset].to_string() +
                                    &key_event.character.to_string() +
                                    &editor.string[editor.offset .. editor.string.len()];
                                editor.offset += 1;
                            },
                            _ => {},
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<commit_msg>Add `o` command to editor<commit_after>use redox::*;

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match key_event.character {
                '0' if !no_mult => times *= 10,

                '1' if no_mult => times = 1,
                '1' => times = times * 10 + 1,

                '2' if no_mult => times = 2,
                '2' => times = times * 10 + 2,

                '3' if no_mult => times = 3,
                '3' => times = times * 10 + 3,

                '4' if no_mult => times = 4,
                '4' => times = times * 10 + 4,

                '5' if no_mult => times = 5,
                '5' => times = times * 10 + 5,

                '6' if no_mult => times = 6,
                '6' => times = times * 10 + 6,

                '7' if no_mult => times = 7,
                '7' => times = times * 10 + 7,

                '8' if no_mult => times = 8,
                '8' => times = times * 10 + 8,

                '9' if no_mult => times = 9,
                '9' => times = times * 10 + 9,
                _ => {
                    for _ in 0 .. times {
                        match (m, key_event.character) {
                            (Normal, 'i') => {
                                *mode = Insert;
                                *last_change = editor.string.clone();
                            },
                            (Normal, 'h') => editor.left(),
                            (Normal, 'l') => editor.right(),
                            (Normal, 'k') => editor.up(),
                            (Normal, 'j') => editor.down(),
                            (Normal, 'G') => editor.offset = editor.string.len(),
                            (Normal, 'a') => {
                                editor.right();
                                *mode = Insert;
                                *last_change = editor.string.clone();
                            },
                            (Normal, 'x') => editor.delete(window),
                            (Normal, 'X') => editor.backspace(window),
                            (Normal, 'u') => {
                                editor.offset = 0;
                                ::core::mem::swap(last_change, &mut editor.string);
                            },
                            (Normal, 'o') => {
                                exec(editor, mode, multiplier, last_change, KeyEvent {
                                    character: '$',
                                    scancode: 0,
                                    pressed: true,
                                }, window);
                                exec(editor, mode, multiplier, last_change, KeyEvent {
                                    character: 'i',
                                    scancode: 0,
                                    pressed: true,
                                }, window);
                                exec(editor, mode, multiplier, last_change, KeyEvent {
                                    character: '\n',
                                    scancode: 0,
                                    pressed: true,
                                }, window);
                            },
                            (Normal, '$') => {
                                let mut new_offset = editor.string.len();
                                for i in editor.offset..editor.string.len() {
                                    match editor.string.as_bytes()[i] {
                                        0 => break,
                                        10 => {
                                            new_offset = i;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                editor.offset = new_offset;
                            },
                            (Normal, '0') => {

                                let mut new_offset = 0;
                                for i in 2..editor.offset {
                                    match editor.string.as_bytes()[editor.offset - i] {
                                        0 => break,
                                        10 => {
                                            new_offset = editor.offset - i + 1;
                                            break;
                                        }
                                        _ => (),
                                    }
                                }
                                editor.offset = new_offset;
                            },
                            (Insert, '\0') => (),
                            (Insert, _) => {
                                window.set_title(&format!("{}{}{}","Editor (", &editor.url, ") Changed"));
                                editor.string = editor.string[0 .. editor.offset].to_string() +
                                    &key_event.character.to_string() +
                                    &editor.string[editor.offset .. editor.string.len()];
                                editor.offset += 1;
                            },
                            _ => {},
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<|endoftext|>


<commit_before>extern crate gfx;

pub mod backend;
pub mod frontend;
pub mod ir;
<commit_msg>add crate desc to amethyst_renderer<commit_after>//! High-level rendering engine with multiple backends.

extern crate gfx;

pub mod backend;
pub mod frontend;
pub mod ir;
<|endoftext|>


<commit_before>// Copyright (c) 2020, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

use crate::cpu_features::CpuFeatureLevel;
use crate::dist::*;
use crate::partition::BlockSize;
use crate::tiling::*;
use crate::util::*;

type SadFn = unsafe extern fn(
  src: *const u8,
  src_stride: isize,
  dst: *const u8,
  dst_stride: isize,
) -> u32;

macro_rules! declare_asm_dist_fn {
  ($(($name: ident, $T: ident)),+) => (
    $(
      extern { fn $name (
        src: *const $T, src_stride: isize, dst: *const $T, dst_stride: isize
      ) -> u32; }
    )+
  )
}

declare_asm_dist_fn![
  (rav1e_sad4x4_neon, u8),
  (rav1e_sad4x8_neon, u8),
  (rav1e_sad4x16_neon, u8),
  (rav1e_sad8x4_neon, u8),
  (rav1e_sad8x8_neon, u8),
  (rav1e_sad8x16_neon, u8),
  (rav1e_sad8x32_neon, u8),
  (rav1e_sad16x4_neon, u8),
  (rav1e_sad16x8_neon, u8),
  (rav1e_sad16x16_neon, u8),
  (rav1e_sad16x32_neon, u8),
  (rav1e_sad16x64_neon, u8),
  (rav1e_sad32x8_neon, u8),
  (rav1e_sad32x16_neon, u8),
  (rav1e_sad32x32_neon, u8),
  (rav1e_sad32x64_neon, u8),
  (rav1e_sad64x16_neon, u8),
  (rav1e_sad64x32_neon, u8),
  (rav1e_sad64x64_neon, u8),
  (rav1e_sad64x128_neon, u8),
  (rav1e_sad128x64_neon, u8),
  (rav1e_sad128x128_neon, u8)
];

// BlockSize::BLOCK_SIZES.next_power_of_two();
const DIST_FNS_LENGTH: usize = 32;

#[inline]
const fn to_index(bsize: BlockSize) -> usize {
  bsize as usize & (DIST_FNS_LENGTH - 1)
}

#[inline(always)]
#[allow(clippy::let_and_return)]
pub fn get_sad<T: Pixel>(
  src: &PlaneRegion<'_, T>, dst: &PlaneRegion<'_, T>, w: usize, h: usize,
  bit_depth: usize, cpu: CpuFeatureLevel,
) -> u32 {
  let bsize_opt = BlockSize::from_width_and_height_opt(w, h);

  let call_rust = || -> u32 { rust::get_sad(dst, src, w, h, bit_depth, cpu) };

  #[cfg(feature = "check_asm")]
  let ref_dist = call_rust();

  let dist = match (bsize_opt, T::type_enum()) {
    (Err(_), _) => call_rust(),
    (Ok(bsize), PixelType::U8) => {
      match SAD_FNS[cpu.as_index()][to_index(bsize)] {
        Some(func) => unsafe {
          (func)(
            src.data_ptr() as *const _,
            T::to_asm_stride(src.plane_cfg.stride),
            dst.data_ptr() as *const _,
            T::to_asm_stride(dst.plane_cfg.stride),
          )
        },
        None => call_rust(),
      }
    }
    (Ok(bsize), PixelType::U16) => call_rust(),
  };

  #[cfg(feature = "check_asm")]
  assert_eq!(dist, ref_dist);

  dist
}

static SAD_FNS_NEON: [Option<SadFn>; DIST_FNS_LENGTH] = {
  let mut out: [Option<SadFn>; DIST_FNS_LENGTH] = [None; DIST_FNS_LENGTH];

  use BlockSize::*;

  out[BLOCK_4X4 as usize] = Some(rav1e_sad4x4_neon);
  out[BLOCK_4X8 as usize] = Some(rav1e_sad4x8_neon);
  out[BLOCK_4X16 as usize] = Some(rav1e_sad4x16_neon);

  out[BLOCK_8X4 as usize] = Some(rav1e_sad8x4_neon);
  out[BLOCK_8X8 as usize] = Some(rav1e_sad8x8_neon);
  out[BLOCK_8X16 as usize] = Some(rav1e_sad8x16_neon);
  out[BLOCK_8X32 as usize] = Some(rav1e_sad8x32_neon);

  out[BLOCK_16X4 as usize] = Some(rav1e_sad16x4_neon);
  out[BLOCK_16X8 as usize] = Some(rav1e_sad16x8_neon);
  out[BLOCK_16X16 as usize] = Some(rav1e_sad16x16_neon);
  out[BLOCK_16X32 as usize] = Some(rav1e_sad16x32_neon);
  out[BLOCK_16X64 as usize] = Some(rav1e_sad16x64_neon);

  out[BLOCK_32X8 as usize] = Some(rav1e_sad32x8_neon);
  out[BLOCK_32X16 as usize] = Some(rav1e_sad32x16_neon);
  out[BLOCK_32X32 as usize] = Some(rav1e_sad32x32_neon);
  out[BLOCK_32X64 as usize] = Some(rav1e_sad32x64_neon);

  out[BLOCK_64X16 as usize] = Some(rav1e_sad64x16_neon);
  out[BLOCK_64X32 as usize] = Some(rav1e_sad64x32_neon);
  out[BLOCK_64X64 as usize] = Some(rav1e_sad64x64_neon);
  out[BLOCK_64X128 as usize] = Some(rav1e_sad64x128_neon);

  out[BLOCK_128X64 as usize] = Some(rav1e_sad128x64_neon);
  out[BLOCK_128X128 as usize] = Some(rav1e_sad128x128_neon);

  out
};

cpu_function_lookup_table!(
  SAD_FNS: [[Option<SadFn>; DIST_FNS_LENGTH]],
  default: [None; DIST_FNS_LENGTH],
  [NEON]
);

#[cfg(test)]
mod test {
  use super::*;
  use crate::frame::{AsRegion, Plane};
  use rand::random;
  use std::str::FromStr;

  macro_rules! test_dist_fns {
    ($(($W:expr, $H:expr)),*, $DIST_TY:ident, $BD:expr, $OPT:ident, $OPTLIT:tt) => {
      $(
        paste::item! {
          #[test]
          fn [<get_ $DIST_TY _ $W x $H _bd_ $BD _ $OPT>]() {
            if $BD > 8 {
              // dynamic allocation: test
              let mut src = Plane::from_slice(&vec![0u16; $W * $H], $W);
              // dynamic allocation: test
              let mut dst = Plane::from_slice(&vec![0u16; $W * $H], $W);
              for (s, d) in src.data.iter_mut().zip(dst.data.iter_mut()) {
                *s = random::<u8>() as u16 * $BD / 8;
                *d = random::<u8>() as u16 * $BD / 8;
              }
              let result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::from_str($OPTLIT).unwrap());
              let rust_result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::RUST);

              assert_eq!(rust_result, result);
            } else {
              // dynamic allocation: test
              let mut src = Plane::from_slice(&vec![0u8; $W * $H], $W);
              // dynamic allocation: test
              let mut dst = Plane::from_slice(&vec![0u8; $W * $H], $W);
              for (s, d) in src.data.iter_mut().zip(dst.data.iter_mut()) {
                *s = random::<u8>();
                *d = random::<u8>();
              }
              let result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::from_str($OPTLIT).unwrap());
              let rust_result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::RUST);

              assert_eq!(rust_result, result);
            }
          }
        }
      )*
    }
  }

  test_dist_fns!(
    (4, 4),
    (4, 8),
    (4, 16),
    (8, 4),
    (8, 8),
    (8, 16),
    (8, 32),
    (16, 4),
    (16, 8),
    (16, 16),
    (16, 32),
    (16, 64),
    (32, 8),
    (32, 16),
    (32, 32),
    (32, 64),
    (64, 16),
    (64, 32),
    (64, 64),
    (64, 128),
    (128, 64),
    (128, 128),
    sad,
    8,
    neon,
    "neon"
  );
}
<commit_msg>Silence unused variable warning.<commit_after>// Copyright (c) 2020, The rav1e contributors. All rights reserved
//
// This source code is subject to the terms of the BSD 2 Clause License and
// the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
// was not distributed with this source code in the LICENSE file, you can
// obtain it at www.aomedia.org/license/software. If the Alliance for Open
// Media Patent License 1.0 was not distributed with this source code in the
// PATENTS file, you can obtain it at www.aomedia.org/license/patent.

use crate::cpu_features::CpuFeatureLevel;
use crate::dist::*;
use crate::partition::BlockSize;
use crate::tiling::*;
use crate::util::*;

type SadFn = unsafe extern fn(
  src: *const u8,
  src_stride: isize,
  dst: *const u8,
  dst_stride: isize,
) -> u32;

macro_rules! declare_asm_dist_fn {
  ($(($name: ident, $T: ident)),+) => (
    $(
      extern { fn $name (
        src: *const $T, src_stride: isize, dst: *const $T, dst_stride: isize
      ) -> u32; }
    )+
  )
}

declare_asm_dist_fn![
  (rav1e_sad4x4_neon, u8),
  (rav1e_sad4x8_neon, u8),
  (rav1e_sad4x16_neon, u8),
  (rav1e_sad8x4_neon, u8),
  (rav1e_sad8x8_neon, u8),
  (rav1e_sad8x16_neon, u8),
  (rav1e_sad8x32_neon, u8),
  (rav1e_sad16x4_neon, u8),
  (rav1e_sad16x8_neon, u8),
  (rav1e_sad16x16_neon, u8),
  (rav1e_sad16x32_neon, u8),
  (rav1e_sad16x64_neon, u8),
  (rav1e_sad32x8_neon, u8),
  (rav1e_sad32x16_neon, u8),
  (rav1e_sad32x32_neon, u8),
  (rav1e_sad32x64_neon, u8),
  (rav1e_sad64x16_neon, u8),
  (rav1e_sad64x32_neon, u8),
  (rav1e_sad64x64_neon, u8),
  (rav1e_sad64x128_neon, u8),
  (rav1e_sad128x64_neon, u8),
  (rav1e_sad128x128_neon, u8)
];

// BlockSize::BLOCK_SIZES.next_power_of_two();
const DIST_FNS_LENGTH: usize = 32;

#[inline]
const fn to_index(bsize: BlockSize) -> usize {
  bsize as usize & (DIST_FNS_LENGTH - 1)
}

#[inline(always)]
#[allow(clippy::let_and_return)]
pub fn get_sad<T: Pixel>(
  src: &PlaneRegion<'_, T>, dst: &PlaneRegion<'_, T>, w: usize, h: usize,
  bit_depth: usize, cpu: CpuFeatureLevel,
) -> u32 {
  let bsize_opt = BlockSize::from_width_and_height_opt(w, h);

  let call_rust = || -> u32 { rust::get_sad(dst, src, w, h, bit_depth, cpu) };

  #[cfg(feature = "check_asm")]
  let ref_dist = call_rust();

  let dist = match (bsize_opt, T::type_enum()) {
    (Err(_), _) => call_rust(),
    (Ok(bsize), PixelType::U8) => {
      match SAD_FNS[cpu.as_index()][to_index(bsize)] {
        Some(func) => unsafe {
          (func)(
            src.data_ptr() as *const _,
            T::to_asm_stride(src.plane_cfg.stride),
            dst.data_ptr() as *const _,
            T::to_asm_stride(dst.plane_cfg.stride),
          )
        },
        None => call_rust(),
      }
    }
    (Ok(_bsize), PixelType::U16) => call_rust(),
  };

  #[cfg(feature = "check_asm")]
  assert_eq!(dist, ref_dist);

  dist
}

static SAD_FNS_NEON: [Option<SadFn>; DIST_FNS_LENGTH] = {
  let mut out: [Option<SadFn>; DIST_FNS_LENGTH] = [None; DIST_FNS_LENGTH];

  use BlockSize::*;

  out[BLOCK_4X4 as usize] = Some(rav1e_sad4x4_neon);
  out[BLOCK_4X8 as usize] = Some(rav1e_sad4x8_neon);
  out[BLOCK_4X16 as usize] = Some(rav1e_sad4x16_neon);

  out[BLOCK_8X4 as usize] = Some(rav1e_sad8x4_neon);
  out[BLOCK_8X8 as usize] = Some(rav1e_sad8x8_neon);
  out[BLOCK_8X16 as usize] = Some(rav1e_sad8x16_neon);
  out[BLOCK_8X32 as usize] = Some(rav1e_sad8x32_neon);

  out[BLOCK_16X4 as usize] = Some(rav1e_sad16x4_neon);
  out[BLOCK_16X8 as usize] = Some(rav1e_sad16x8_neon);
  out[BLOCK_16X16 as usize] = Some(rav1e_sad16x16_neon);
  out[BLOCK_16X32 as usize] = Some(rav1e_sad16x32_neon);
  out[BLOCK_16X64 as usize] = Some(rav1e_sad16x64_neon);

  out[BLOCK_32X8 as usize] = Some(rav1e_sad32x8_neon);
  out[BLOCK_32X16 as usize] = Some(rav1e_sad32x16_neon);
  out[BLOCK_32X32 as usize] = Some(rav1e_sad32x32_neon);
  out[BLOCK_32X64 as usize] = Some(rav1e_sad32x64_neon);

  out[BLOCK_64X16 as usize] = Some(rav1e_sad64x16_neon);
  out[BLOCK_64X32 as usize] = Some(rav1e_sad64x32_neon);
  out[BLOCK_64X64 as usize] = Some(rav1e_sad64x64_neon);
  out[BLOCK_64X128 as usize] = Some(rav1e_sad64x128_neon);

  out[BLOCK_128X64 as usize] = Some(rav1e_sad128x64_neon);
  out[BLOCK_128X128 as usize] = Some(rav1e_sad128x128_neon);

  out
};

cpu_function_lookup_table!(
  SAD_FNS: [[Option<SadFn>; DIST_FNS_LENGTH]],
  default: [None; DIST_FNS_LENGTH],
  [NEON]
);

#[cfg(test)]
mod test {
  use super::*;
  use crate::frame::{AsRegion, Plane};
  use rand::random;
  use std::str::FromStr;

  macro_rules! test_dist_fns {
    ($(($W:expr, $H:expr)),*, $DIST_TY:ident, $BD:expr, $OPT:ident, $OPTLIT:tt) => {
      $(
        paste::item! {
          #[test]
          fn [<get_ $DIST_TY _ $W x $H _bd_ $BD _ $OPT>]() {
            if $BD > 8 {
              // dynamic allocation: test
              let mut src = Plane::from_slice(&vec![0u16; $W * $H], $W);
              // dynamic allocation: test
              let mut dst = Plane::from_slice(&vec![0u16; $W * $H], $W);
              for (s, d) in src.data.iter_mut().zip(dst.data.iter_mut()) {
                *s = random::<u8>() as u16 * $BD / 8;
                *d = random::<u8>() as u16 * $BD / 8;
              }
              let result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::from_str($OPTLIT).unwrap());
              let rust_result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::RUST);

              assert_eq!(rust_result, result);
            } else {
              // dynamic allocation: test
              let mut src = Plane::from_slice(&vec![0u8; $W * $H], $W);
              // dynamic allocation: test
              let mut dst = Plane::from_slice(&vec![0u8; $W * $H], $W);
              for (s, d) in src.data.iter_mut().zip(dst.data.iter_mut()) {
                *s = random::<u8>();
                *d = random::<u8>();
              }
              let result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::from_str($OPTLIT).unwrap());
              let rust_result = [<get_ $DIST_TY>](&src.as_region(), &dst.as_region(), $W, $H, $BD, CpuFeatureLevel::RUST);

              assert_eq!(rust_result, result);
            }
          }
        }
      )*
    }
  }

  test_dist_fns!(
    (4, 4),
    (4, 8),
    (4, 16),
    (8, 4),
    (8, 8),
    (8, 16),
    (8, 32),
    (16, 4),
    (16, 8),
    (16, 16),
    (16, 32),
    (16, 64),
    (32, 8),
    (32, 16),
    (32, 32),
    (32, 64),
    (64, 16),
    (64, 32),
    (64, 64),
    (64, 128),
    (128, 64),
    (128, 128),
    sad,
    8,
    neon,
    "neon"
  );
}
<|endoftext|>


<commit_before>use core::libc::*;

use allegro5::rust_util::c_bool;

pub mod C
{
	use core::libc::*;

	use allegro5::events::C::ALLEGRO_EVENT_SOURCE;
	use allegro5::bitmap::C::ALLEGRO_BITMAP;
	use allegro5::rust_util::c_bool;

	pub struct ALLEGRO_DISPLAY;

	pub extern "C"
	{
		fn al_set_new_display_refresh_rate(refresh_rate : c_int);
		fn al_set_new_display_flags(flags : c_int);
		fn al_get_new_display_refresh_rate() -> c_int;
		fn al_get_new_display_flags() -> c_int;

		fn al_get_display_width(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_height(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_format(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_refresh_rate(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_flags(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_orientation(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_set_display_flag(display : *mut ALLEGRO_DISPLAY, flag : c_int, onoff : c_bool) -> c_bool;

		fn al_create_display(w : c_int, h : c_int) -> *mut ALLEGRO_DISPLAY;
		fn al_destroy_display(display : *mut ALLEGRO_DISPLAY);
		fn al_get_current_display() -> *mut ALLEGRO_DISPLAY;
		fn al_set_target_bitmap(bitmap : *mut ALLEGRO_BITMAP);
		fn al_set_target_backbuffer(display : *mut ALLEGRO_DISPLAY);
		fn al_get_backbuffer(display : *mut ALLEGRO_DISPLAY) -> *mut ALLEGRO_BITMAP;
		fn al_get_target_bitmap() -> *mut ALLEGRO_BITMAP;

		fn al_acknowledge_resize(display : *mut ALLEGRO_DISPLAY) -> c_bool;
		fn al_resize_display(display : *mut ALLEGRO_DISPLAY, width : c_int, height : c_int) -> c_bool;
		fn al_flip_display();
		fn al_update_display_region(x : c_int, y : c_int, width : c_int, height : c_int);
		fn al_is_compatible_bitmap(bitmap : *mut ALLEGRO_BITMAP) -> c_bool;

		fn al_wait_for_vsync() -> c_bool;

		fn al_get_display_event_source(display : *mut ALLEGRO_DISPLAY) -> *mut ALLEGRO_EVENT_SOURCE;

		fn al_set_display_icon(display : *mut ALLEGRO_DISPLAY, icon : *mut ALLEGRO_BITMAP);
		fn al_set_display_icons(display : *mut ALLEGRO_DISPLAY, num_icons : c_int, icons : *mut *mut ALLEGRO_BITMAP);

		fn al_get_new_display_adapter() -> c_int;
		fn al_set_new_display_adapter(adapter : c_int);
		fn al_set_new_window_position(x : c_int, y : c_int);
		fn al_get_new_window_position(x : *mut c_int, y : *mut c_int);
		fn al_set_window_position(display : *mut ALLEGRO_DISPLAY, x : c_int, y : c_int);
		fn al_get_window_position(display : *mut ALLEGRO_DISPLAY, x : *mut c_int, y : *mut c_int);
		fn al_set_window_constraints(display : *mut ALLEGRO_DISPLAY, min_w : c_int, min_h : c_int, max_w : c_int, max_h : c_int) -> c_bool;
		fn al_get_window_constraints(display : *mut ALLEGRO_DISPLAY, min_w : *mut c_int, min_h : *mut c_int, max_w : *mut c_int, max_h : *mut c_int) -> c_bool;

		fn al_set_window_title(display : *mut ALLEGRO_DISPLAY, title : *c_char);

		fn al_set_new_display_option(option : c_int, value : c_int, importance : c_int);
		fn al_get_new_display_option(option : c_int, importance : *mut c_int) -> c_int;
		fn al_reset_new_display_options();
		fn al_set_display_option(display : *mut ALLEGRO_DISPLAY, option : c_int, value : c_int);
		fn al_get_display_option(display : *mut ALLEGRO_DISPLAY, option : c_int) -> c_int;

		fn al_hold_bitmap_drawing(hold : c_bool);
		fn al_is_bitmap_drawing_held() -> c_bool;

		fn al_acknowledge_drawing_halt(display : *mut ALLEGRO_DISPLAY);
		fn al_acknowledge_drawing_resume(display : *mut ALLEGRO_DISPLAY);
	}
}

pub static ALLEGRO_WINDOWED : i32                  = 1 << 0;
pub static ALLEGRO_FULLSCREEN : i32                = 1 << 1;
pub static ALLEGRO_OPENGL : i32                    = 1 << 2;
pub static ALLEGRO_DIRECT3D_INTERNAL : i32         = 1 << 3;
pub static ALLEGRO_RESIZABLE : i32                 = 1 << 4;
pub static ALLEGRO_FRAMELESS : i32                 = 1 << 5;
pub static ALLEGRO_NOFRAME : i32                   = ALLEGRO_FRAMELESS;
pub static ALLEGRO_GENERATE_EXPOSE_EVENTS : i32    = 1 << 6;
pub static ALLEGRO_OPENGL_3_0 : i32                = 1 << 7;
pub static ALLEGRO_OPENGL_FORWARD_COMPATIBLE : i32 = 1 << 8;
pub static ALLEGRO_FULLSCREEN_WINDOW : i32         = 1 << 9;
pub static ALLEGRO_MINIMIZED : i32                 = 1 << 10;
pub static ALLEGRO_PROGRAMMABLE_PIPELINE : i32     = 1 << 11;
pub static ALLEGRO_GTK_TOPLEVEL_INTERNAL : i32     = 1 << 12;

pub static ALLEGRO_RED_SIZE : i32 = 0;
pub static ALLEGRO_GREEN_SIZE : i32 = 1;
pub static ALLEGRO_BLUE_SIZE : i32 = 2;
pub static ALLEGRO_ALPHA_SIZE : i32 = 3;
pub static ALLEGRO_RED_SHIFT : i32 = 4;
pub static ALLEGRO_GREEN_SHIFT : i32 = 5;
pub static ALLEGRO_BLUE_SHIFT : i32 = 6;
pub static ALLEGRO_ALPHA_SHIFT : i32 = 7;
pub static ALLEGRO_ACC_RED_SIZE : i32 = 8;
pub static ALLEGRO_ACC_GREEN_SIZE : i32 = 9;
pub static ALLEGRO_ACC_BLUE_SIZE : i32 = 10;
pub static ALLEGRO_ACC_ALPHA_SIZE : i32 = 11;
pub static ALLEGRO_STEREO : i32 = 12;
pub static ALLEGRO_AUX_BUFFERS : i32 = 13;
pub static ALLEGRO_COLOR_SIZE : i32 = 14;
pub static ALLEGRO_DEPTH_SIZE : i32 = 15;
pub static ALLEGRO_STENCIL_SIZE : i32 = 16;
pub static ALLEGRO_SAMPLE_BUFFERS : i32 = 17;
pub static ALLEGRO_SAMPLES : i32 = 18;
pub static ALLEGRO_RENDER_METHOD : i32 = 19;
pub static ALLEGRO_FLOAT_COLOR : i32 = 20;
pub static ALLEGRO_FLOAT_DEPTH : i32 = 21;
pub static ALLEGRO_SINGLE_BUFFER : i32 = 22;
pub static ALLEGRO_SWAP_METHOD : i32 = 23;
pub static ALLEGRO_COMPATIBLE_DISPLAY : i32 = 24;
pub static ALLEGRO_UPDATE_DISPLAY_REGION : i32 = 25;
pub static ALLEGRO_VSYNC : i32 = 26;
pub static ALLEGRO_MAX_BITMAP_SIZE : i32 = 27;
pub static ALLEGRO_SUPPORT_NPOT_BITMAP : i32 = 28;
pub static ALLEGRO_CAN_DRAW_INTO_BITMAP : i32 = 29;
pub static ALLEGRO_SUPPORT_SEPARATE_ALPHA : i32 = 30;
pub static ALLEGRO_AUTO_CONVERT_BITMAPS : i32 = 31;
pub static ALLEGRO_SUPPORTED_ORIENTATIONS : i32 = 32;
pub static ALLEGRO_DISPLAY_OPTIONS_COUNT : i32 = 33;

pub static ALLEGRO_DONTCARE : i32 = 0;
pub static ALLEGRO_REQUIRE : i32 = 1;
pub static ALLEGRO_SUGGEST : i32 = 2;

pub static ALLEGRO_DISPLAY_ORIENTATION_UNKNOWN : i32 = 0;
pub static ALLEGRO_DISPLAY_ORIENTATION_0_DEGREES : i32 = 1;
pub static ALLEGRO_DISPLAY_ORIENTATION_90_DEGREES : i32 = 2;
pub static ALLEGRO_DISPLAY_ORIENTATION_180_DEGREES : i32 = 4;
pub static ALLEGRO_DISPLAY_ORIENTATION_270_DEGREES : i32 = 8;
pub static ALLEGRO_DISPLAY_ORIENTATION_PORTRAIT : i32 = 5;
pub static ALLEGRO_DISPLAY_ORIENTATION_LANDSCAPE : i32 = 10;
pub static ALLEGRO_DISPLAY_ORIENTATION_ALL : i32 = 15;
pub static ALLEGRO_DISPLAY_ORIENTATION_FACE_UP : i32 = 16;
pub static ALLEGRO_DISPLAY_ORIENTATION_FACE_DOWN : i32 = 32;

pub struct ALLEGRO_DISPLAY
{
	Payload : *mut C::ALLEGRO_DISPLAY
}

impl Drop for ALLEGRO_DISPLAY
{
	fn finalize(&self)
	{
		debug!("%s", "Finalizing display.");
		unsafe
		{
			C::al_destroy_display(self.Payload);
		}
	}
}

pub fn al_set_new_display_refresh_rate(refresh_rate : i32)
{
	unsafe
	{
		C::al_set_new_display_refresh_rate(refresh_rate as c_int);
	}
}

pub fn al_set_new_display_flags(flags : i32)
{
	unsafe
	{
		C::al_set_new_display_flags(flags as c_int);
	}
}

pub fn al_get_new_display_refresh_rate() -> i32
{
	unsafe
	{
		return C::al_get_new_display_refresh_rate() as i32;
	}
}

pub fn al_get_new_display_flags() -> i32
{
	unsafe
	{
		return C::al_get_new_display_flags() as i32;
	}
}

pub fn al_get_display_width(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_width(display.Payload) as i32;
	}
}

pub fn al_get_display_height(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_height(display.Payload) as i32;
	}
}

pub fn al_get_display_format(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_format(display.Payload) as i32;
	}
}

pub fn al_get_display_refresh_rate(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_refresh_rate(display.Payload) as i32;
	}
}

pub fn al_get_display_flags(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_flags(display.Payload) as i32;
	}
}

pub fn al_get_display_orientation(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_orientation(display.Payload) as i32;
	}
}

pub fn al_set_display_flag(display : &ALLEGRO_DISPLAY, flag : i32, onoff : bool) -> bool
{
	unsafe
	{
		return C::al_set_display_flag(display.Payload, flag as c_int, onoff as c_bool) as bool;
	}
}

pub fn al_create_display(w : i32, h : i32) -> Option<ALLEGRO_DISPLAY>
{
	unsafe
	{
		match C::al_create_display(w, h)
		{
			d if ptr::is_null(d) => None,
			d => Some(ALLEGRO_DISPLAY{Payload : d})
		}
	}
}

pub fn al_flip_display()
{
	unsafe
	{
		C::al_flip_display();
	}
}
<commit_msg>Move the ALLEGRO_DISPLAY definition to the top<commit_after>use core::libc::*;

use allegro5::rust_util::c_bool;

pub mod C
{
	use core::libc::*;

	use allegro5::events::C::ALLEGRO_EVENT_SOURCE;
	use allegro5::bitmap::C::ALLEGRO_BITMAP;
	use allegro5::rust_util::c_bool;

	pub struct ALLEGRO_DISPLAY;

	pub extern "C"
	{
		fn al_set_new_display_refresh_rate(refresh_rate : c_int);
		fn al_set_new_display_flags(flags : c_int);
		fn al_get_new_display_refresh_rate() -> c_int;
		fn al_get_new_display_flags() -> c_int;

		fn al_get_display_width(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_height(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_format(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_refresh_rate(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_flags(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_get_display_orientation(display : *mut ALLEGRO_DISPLAY) -> c_int;
		fn al_set_display_flag(display : *mut ALLEGRO_DISPLAY, flag : c_int, onoff : c_bool) -> c_bool;

		fn al_create_display(w : c_int, h : c_int) -> *mut ALLEGRO_DISPLAY;
		fn al_destroy_display(display : *mut ALLEGRO_DISPLAY);
		fn al_get_current_display() -> *mut ALLEGRO_DISPLAY;
		fn al_set_target_bitmap(bitmap : *mut ALLEGRO_BITMAP);
		fn al_set_target_backbuffer(display : *mut ALLEGRO_DISPLAY);
		fn al_get_backbuffer(display : *mut ALLEGRO_DISPLAY) -> *mut ALLEGRO_BITMAP;
		fn al_get_target_bitmap() -> *mut ALLEGRO_BITMAP;

		fn al_acknowledge_resize(display : *mut ALLEGRO_DISPLAY) -> c_bool;
		fn al_resize_display(display : *mut ALLEGRO_DISPLAY, width : c_int, height : c_int) -> c_bool;
		fn al_flip_display();
		fn al_update_display_region(x : c_int, y : c_int, width : c_int, height : c_int);
		fn al_is_compatible_bitmap(bitmap : *mut ALLEGRO_BITMAP) -> c_bool;

		fn al_wait_for_vsync() -> c_bool;

		fn al_get_display_event_source(display : *mut ALLEGRO_DISPLAY) -> *mut ALLEGRO_EVENT_SOURCE;

		fn al_set_display_icon(display : *mut ALLEGRO_DISPLAY, icon : *mut ALLEGRO_BITMAP);
		fn al_set_display_icons(display : *mut ALLEGRO_DISPLAY, num_icons : c_int, icons : *mut *mut ALLEGRO_BITMAP);

		fn al_get_new_display_adapter() -> c_int;
		fn al_set_new_display_adapter(adapter : c_int);
		fn al_set_new_window_position(x : c_int, y : c_int);
		fn al_get_new_window_position(x : *mut c_int, y : *mut c_int);
		fn al_set_window_position(display : *mut ALLEGRO_DISPLAY, x : c_int, y : c_int);
		fn al_get_window_position(display : *mut ALLEGRO_DISPLAY, x : *mut c_int, y : *mut c_int);
		fn al_set_window_constraints(display : *mut ALLEGRO_DISPLAY, min_w : c_int, min_h : c_int, max_w : c_int, max_h : c_int) -> c_bool;
		fn al_get_window_constraints(display : *mut ALLEGRO_DISPLAY, min_w : *mut c_int, min_h : *mut c_int, max_w : *mut c_int, max_h : *mut c_int) -> c_bool;

		fn al_set_window_title(display : *mut ALLEGRO_DISPLAY, title : *c_char);

		fn al_set_new_display_option(option : c_int, value : c_int, importance : c_int);
		fn al_get_new_display_option(option : c_int, importance : *mut c_int) -> c_int;
		fn al_reset_new_display_options();
		fn al_set_display_option(display : *mut ALLEGRO_DISPLAY, option : c_int, value : c_int);
		fn al_get_display_option(display : *mut ALLEGRO_DISPLAY, option : c_int) -> c_int;

		fn al_hold_bitmap_drawing(hold : c_bool);
		fn al_is_bitmap_drawing_held() -> c_bool;

		fn al_acknowledge_drawing_halt(display : *mut ALLEGRO_DISPLAY);
		fn al_acknowledge_drawing_resume(display : *mut ALLEGRO_DISPLAY);
	}
}

pub struct ALLEGRO_DISPLAY
{
	Payload : *mut C::ALLEGRO_DISPLAY
}

impl Drop for ALLEGRO_DISPLAY
{
	fn finalize(&self)
	{
		debug!("%s", "Finalizing display.");
		unsafe
		{
			C::al_destroy_display(self.Payload);
		}
	}
}

pub static ALLEGRO_WINDOWED : i32                  = 1 << 0;
pub static ALLEGRO_FULLSCREEN : i32                = 1 << 1;
pub static ALLEGRO_OPENGL : i32                    = 1 << 2;
pub static ALLEGRO_DIRECT3D_INTERNAL : i32         = 1 << 3;
pub static ALLEGRO_RESIZABLE : i32                 = 1 << 4;
pub static ALLEGRO_FRAMELESS : i32                 = 1 << 5;
pub static ALLEGRO_NOFRAME : i32                   = ALLEGRO_FRAMELESS;
pub static ALLEGRO_GENERATE_EXPOSE_EVENTS : i32    = 1 << 6;
pub static ALLEGRO_OPENGL_3_0 : i32                = 1 << 7;
pub static ALLEGRO_OPENGL_FORWARD_COMPATIBLE : i32 = 1 << 8;
pub static ALLEGRO_FULLSCREEN_WINDOW : i32         = 1 << 9;
pub static ALLEGRO_MINIMIZED : i32                 = 1 << 10;
pub static ALLEGRO_PROGRAMMABLE_PIPELINE : i32     = 1 << 11;
pub static ALLEGRO_GTK_TOPLEVEL_INTERNAL : i32     = 1 << 12;

pub static ALLEGRO_RED_SIZE : i32 = 0;
pub static ALLEGRO_GREEN_SIZE : i32 = 1;
pub static ALLEGRO_BLUE_SIZE : i32 = 2;
pub static ALLEGRO_ALPHA_SIZE : i32 = 3;
pub static ALLEGRO_RED_SHIFT : i32 = 4;
pub static ALLEGRO_GREEN_SHIFT : i32 = 5;
pub static ALLEGRO_BLUE_SHIFT : i32 = 6;
pub static ALLEGRO_ALPHA_SHIFT : i32 = 7;
pub static ALLEGRO_ACC_RED_SIZE : i32 = 8;
pub static ALLEGRO_ACC_GREEN_SIZE : i32 = 9;
pub static ALLEGRO_ACC_BLUE_SIZE : i32 = 10;
pub static ALLEGRO_ACC_ALPHA_SIZE : i32 = 11;
pub static ALLEGRO_STEREO : i32 = 12;
pub static ALLEGRO_AUX_BUFFERS : i32 = 13;
pub static ALLEGRO_COLOR_SIZE : i32 = 14;
pub static ALLEGRO_DEPTH_SIZE : i32 = 15;
pub static ALLEGRO_STENCIL_SIZE : i32 = 16;
pub static ALLEGRO_SAMPLE_BUFFERS : i32 = 17;
pub static ALLEGRO_SAMPLES : i32 = 18;
pub static ALLEGRO_RENDER_METHOD : i32 = 19;
pub static ALLEGRO_FLOAT_COLOR : i32 = 20;
pub static ALLEGRO_FLOAT_DEPTH : i32 = 21;
pub static ALLEGRO_SINGLE_BUFFER : i32 = 22;
pub static ALLEGRO_SWAP_METHOD : i32 = 23;
pub static ALLEGRO_COMPATIBLE_DISPLAY : i32 = 24;
pub static ALLEGRO_UPDATE_DISPLAY_REGION : i32 = 25;
pub static ALLEGRO_VSYNC : i32 = 26;
pub static ALLEGRO_MAX_BITMAP_SIZE : i32 = 27;
pub static ALLEGRO_SUPPORT_NPOT_BITMAP : i32 = 28;
pub static ALLEGRO_CAN_DRAW_INTO_BITMAP : i32 = 29;
pub static ALLEGRO_SUPPORT_SEPARATE_ALPHA : i32 = 30;
pub static ALLEGRO_AUTO_CONVERT_BITMAPS : i32 = 31;
pub static ALLEGRO_SUPPORTED_ORIENTATIONS : i32 = 32;
pub static ALLEGRO_DISPLAY_OPTIONS_COUNT : i32 = 33;

pub static ALLEGRO_DONTCARE : i32 = 0;
pub static ALLEGRO_REQUIRE : i32 = 1;
pub static ALLEGRO_SUGGEST : i32 = 2;

pub static ALLEGRO_DISPLAY_ORIENTATION_UNKNOWN : i32 = 0;
pub static ALLEGRO_DISPLAY_ORIENTATION_0_DEGREES : i32 = 1;
pub static ALLEGRO_DISPLAY_ORIENTATION_90_DEGREES : i32 = 2;
pub static ALLEGRO_DISPLAY_ORIENTATION_180_DEGREES : i32 = 4;
pub static ALLEGRO_DISPLAY_ORIENTATION_270_DEGREES : i32 = 8;
pub static ALLEGRO_DISPLAY_ORIENTATION_PORTRAIT : i32 = 5;
pub static ALLEGRO_DISPLAY_ORIENTATION_LANDSCAPE : i32 = 10;
pub static ALLEGRO_DISPLAY_ORIENTATION_ALL : i32 = 15;
pub static ALLEGRO_DISPLAY_ORIENTATION_FACE_UP : i32 = 16;
pub static ALLEGRO_DISPLAY_ORIENTATION_FACE_DOWN : i32 = 32;

pub fn al_set_new_display_refresh_rate(refresh_rate : i32)
{
	unsafe
	{
		C::al_set_new_display_refresh_rate(refresh_rate as c_int);
	}
}

pub fn al_set_new_display_flags(flags : i32)
{
	unsafe
	{
		C::al_set_new_display_flags(flags as c_int);
	}
}

pub fn al_get_new_display_refresh_rate() -> i32
{
	unsafe
	{
		return C::al_get_new_display_refresh_rate() as i32;
	}
}

pub fn al_get_new_display_flags() -> i32
{
	unsafe
	{
		return C::al_get_new_display_flags() as i32;
	}
}

pub fn al_get_display_width(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_width(display.Payload) as i32;
	}
}

pub fn al_get_display_height(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_height(display.Payload) as i32;
	}
}

pub fn al_get_display_format(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_format(display.Payload) as i32;
	}
}

pub fn al_get_display_refresh_rate(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_refresh_rate(display.Payload) as i32;
	}
}

pub fn al_get_display_flags(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_flags(display.Payload) as i32;
	}
}

pub fn al_get_display_orientation(display : &ALLEGRO_DISPLAY) -> i32
{
	unsafe
	{
		return C::al_get_display_orientation(display.Payload) as i32;
	}
}

pub fn al_set_display_flag(display : &ALLEGRO_DISPLAY, flag : i32, onoff : bool) -> bool
{
	unsafe
	{
		return C::al_set_display_flag(display.Payload, flag as c_int, onoff as c_bool) as bool;
	}
}

pub fn al_create_display(w : i32, h : i32) -> Option<ALLEGRO_DISPLAY>
{
	unsafe
	{
		match C::al_create_display(w, h)
		{
			d if ptr::is_null(d) => None,
			d => Some(ALLEGRO_DISPLAY{Payload : d})
		}
	}
}

pub fn al_flip_display()
{
	unsafe
	{
		C::al_flip_display();
	}
}
<|endoftext|>