<commit_before><commit_msg>Add dis-abled LLVM backend<commit_after>use std::collections::HashMap;
use std::env;
use std::fmt::Debug;
use std::fs::{File};
use std::io;
use std::io::Write;
use std::process::Command;
use std::path::{Path, PathBuf};

use core;
use cps;
use llvm;
use llvm_sys;

use llvm_sys::prelude::LLVMValueRef;

#[derive(Debug, Clone)]
enum Error {
    UnknownSymbol(String),
}

/// A trait that describes the interface to a particular compiler backend.
trait Backend {
    pub fn create_executable<P: AsRef<Path> + Debug>(module: &cps::Module, output: Option<P>) {
}
// pub trait Backend {
//     fn compile(self)
// }
struct ModuleCx<'cx, 'm> {
    cx: &'cx llvm::Context,
    module: llvm::Module,
    cps_module: &'m cps::Module,
}

impl<'cx, 'm> ModuleCx<'cx, 'm> {
    fn new(cx: &'cx llvm::Context, m: &'m cps::Module) -> ModuleCx<'cx, 'm> {
        panic!()
        // let module = llvm::Module::with_name(m.name.to_string());
        // module.set_target("x86_64-apple-darwin".to_string());
        //
        // ModuleCx {
        //     cx: cx,
        //     module: module,
        //     cps_module: m,
        // }
    }

    pub fn emit_module<P: AsRef<Path> + Debug>(&self, output: P) -> Result<(), Error> {
        // for def in &self.cps_module.defs {
        //     match def {
        //         &cps::Definition::Fn(ref fun) => {
        //             let mut fcx = FunctionCx::new(self, fun);
        //             try!(fcx.emit_function());
        //         }
        //         &cps::Definition::Extern(ref e) => self.emit_extern(&e.0, &e.1),
        //         _ => {}
        //     }
        // }
        //
        // self.module.dump();
        // self.module.print_to_file(output);
        //
        // Ok(())
    }

    pub fn emit_extern(&self, name: &core::Name, ty: &core::Term) {
        // let i64_ty = self.cx.i64_type();
        // let fn_ty = llvm::FunctionType::new(i64_ty, vec![i64_ty]);
        //
        // let efunction = llvm::Function::in_module(
        //     &self.module,
        //     name.clone(),
        //     fn_ty);
        //
        // efunction.set_linkage(llvm_sys::LLVMLinkage::LLVMExternalLinkage);
    }
}

// struct FunctionCx<'cx, 'm:'cx, 'f> {
//     mcx: &'cx ModuleCx<'cx, 'm>,
//     func: &'f cps::Function,
//     builder: llvm::Builder,
//     vars: HashMap<String, LLVMValueRef>,
// }
//
// impl<'cx, 'm, 'f> FunctionCx<'cx, 'm, 'f> {
//     fn new(module: &'cx ModuleCx<'cx, 'm>, func: &'f cps::Function) -> FunctionCx<'cx, 'm, 'f> {
//         FunctionCx {
//             mcx: module,
//             func: func,
//             builder: llvm::Builder::in_context(module.cx),
//             vars: HashMap::new(),
//         }
//     }
//
//     pub fn emit_function(&mut self) -> Result<(), Error> {
//         let arg_tys = self.func.args.iter().map(|_| {
//             self.mcx.cx.i64_type()
//         }).collect();
//
//         let fn_ty = llvm::FunctionType::new(self.mcx.cx.i64_type(), arg_tys);
//
//         let fname = if self.func.name == "main" {
//             "_hubris_main".to_string()
//         } else {
//             self.func.name.clone()
//         };
//
//         let mut function = llvm::Function::in_module(
//             &self.mcx.module,
//             fname,
//             fn_ty.clone());
//
//         let bb = function.create_entry_block(&self.mcx.cx);
//         self.builder.postition_at_end(bb);
//
//         debug!("emit_fucntion: emitting body");
//         let return_value = try!(self.emit_term(&self.func.body));
//
//         debug!("emit_function: emitting return");
//         self.builder.emit_ret(return_value);
//
//         Ok(())
//     }
//
//     pub fn emit_term(&mut self, term: &cps::Term) -> Result<LLVMValueRef, Error> {
//         use cps::Term::*;
//
//         debug!("emit_term: term={:?}", term);
//
//         match term {
//             &Value(ref v) => self.emit_value(v),
//             &App(ref callee, ref arg) => {
//                 debug!("emitting callee");
//                 let callee = try!(self.emit_value(callee));
//                 let arg = try!(self.emit_value(arg));
//
//                 Ok(unsafe {
//                     llvm_sys::core::LLVMBuildCall(
//                         self.builder.as_ptr(), callee,
//                         [arg].as_mut_ptr(), 1 as u32,
//                         b"call_tmp\0".as_ptr() as *const _)
//                 })
//             }
//             &Fix(ref bindings, ref body) => {
//                 debug!("emitting args");
//                 for &(ref n, ref args, ref term) in bindings {
//                     if args.len() == 0 {
//                         let i64_ty = self.mcx.cx.i64_type();
//                         debug!("before alloc");
//                         let alloca = self.builder.emit_alloca(i64_ty, n.clone());
//                         debug!("before value");
//                         let value = try!(self.emit_term(term));
//                         // let value = unsafe { llvm_sys::core::LLVMBuildPtrToInt(
//                         //     self.builder.as_ptr(),
//                         //     value, i64_ty, b"a\0".as_ptr() as *const _) };
//                         debug!("before store");
//                         debug!("{:?} {:?}", value, alloca);
//                         let sto = unsafe {
//                             llvm_sys::core::LLVMBuildStore(
//                                 self.builder.as_ptr(),
//                                 value,
//                                 alloca)
//                         };
//                         self.vars.insert(n.clone(), alloca);
//                     } else {
//                         panic!("can't code gen local closures")
//                     }
//                 }
//
//                 debug!("emitting body");
//                 self.emit_term(body)
//             }
//         }
//     }
//
//     pub fn emit_value(&self, value: &cps::Value) -> Result<LLVMValueRef, Error> {
//         use cps::Value::*;
//
//         debug!("emit_value: value={:?}", value);
//
//         match value {
//             &Literal(ref l) => self.emit_literal(l),
//             &Var(ref name) => match self.vars.get(name) {
//                 None => match self.mcx.module.get_function(name.clone()) {
//                     Some(function) => Ok(unsafe { function.as_ptr() }),
//                     None => Err(Error::UnknownSymbol(name.clone())),
//                 },
//                 Some(v) => {
//                     Ok(unsafe {
//                         llvm_sys::core::LLVMBuildLoad(
//                             self.builder.as_ptr(),
//                             *v,
//                             name.as_ptr() as *const _)
//                     })
//                 }
//             }
//         }
//     }
//
//     pub fn emit_literal(&self, lit: &core::Literal) -> Result<LLVMValueRef, Error> {
//         use core::Literal;
//
//         match lit {
//             &Literal::Unit => unsafe {
//                 let i64_ty = self.mcx.cx.i64_type();
//                 Ok(llvm_sys::core::LLVMConstInt(i64_ty, 1, 0))
//             },
//             lit => panic!("can't compile {:?}", lit),
//         }
//     }
//
// }

pub fn in_build_path<P: AsRef<Path>, F, R>(build_path: P, f: F) -> R
    where F: Fn(&Path) -> R {

    let current_dir = env::current_dir().unwrap();
    env::set_current_dir(build_path.as_ref());
    let result = f(build_path.as_ref());
    env::set_current_dir(current_dir);
    result
}

pub fn ensure_success(cmd: &mut Command) -> io::Result<()> {
    let output = try!(cmd.output());
    if !output.status.success() {
        panic!("command {:?} failed with: {:?}", cmd, output.stdout);
    } else {
        Ok(())
    }
}

pub fn create_executable<P: AsRef<Path> + Debug>(module: &cps::Module, output: Option<P>) {
    let current_dir = env::current_dir().unwrap();
    let output = output.as_ref().map(|x| x.as_ref()).unwrap_or(current_dir.as_ref());
    let tmp = PathBuf::from("/tmp");

    ensure_success(
        Command::new("mkdir")
           .arg("-p")
           .arg("/tmp/hubris"));

    let exe = in_build_path(tmp.join("hubris"), |build_path| {
        let file_name = module.file_name();

        let mut context = llvm::Context::new();
        let mcx = ModuleCx::new(&context, module);

        mcx.emit_module(
            build_path.join(file_name.with_extension("ll")));

        llvm::tools::llc(
            build_path.join(file_name.with_extension("ll")));

        ensure_success(
            Command::new("as")
               .arg(file_name.with_extension("s"))
               .arg("-o")
               .arg(file_name.with_extension("o")));

        let rt = include_str!("../../../rt.c");

        let mut rtc = File::create(build_path.join("rt.c")).unwrap();
        rtc.write_all(rt.as_bytes()).unwrap();

        ensure_success(
            Command::new("gcc")
                .arg("rt.c")
                .arg(file_name.with_extension("o"))
                .arg("-o")
                .arg("prog"));

        build_path.join("prog")
    });

    debug!("create_executable: copy executable {:?} to {:?}",
        exe, output);

    ensure_success(
        Command::new("cp")
           .arg(exe)
           .arg(output));
}
//
// use core;
// use core::Name;
//
// use std::path::PathBuf;
//
// #[derive(Debug)]
// pub struct Module {
//     pub name: Name,
//     pub defs: Vec<Definition>,
// }
//
// impl Module {
//     pub fn file_name(&self) -> PathBuf {
//         PathBuf::from(&self.name[..])
//     }
// }
//
// #[derive(Debug, Clone, PartialEq)]
// pub enum Value {
//     Var(Name),
//     Literal(core::Literal),
// }
//
// #[derive(Debug, Clone, PartialEq)]
// pub enum Definition {
//     Data(core::Data),
//     Fn(Function),
//     Extern(core::Extern),
// }
//
// #[derive(Debug, Clone, PartialEq)]
// pub struct Function {
//     pub name: Name,
//     pub args: Vec<Name>,
//     pub body: Term,
// }
//
// #[derive(Debug, Clone, PartialEq)]
// pub enum Term {
//     Value(Value),
//     App(Value, Value),
//     Fix(Vec<(Name, Vec<Name>, Box<Term>)>, Box<Term>),
// }
//
// pub fn from_core_module(core_module: core::Module) -> Module {
//     let mut module = Module {
//         name: core_module.name,
//         defs: vec![],
//     };
//
//     for def in core_module.defs {
//         match def {
//             core::Definition::Data(data) =>
//                 module.defs.push(Definition::Data(data)),
//             core::Definition::Fn(fun) =>
//                 module.defs.push(Definition::Fn(from_core_fn(fun))),
//             core::Definition::Extern(ext) =>
//                 module.defs.push(Definition::Extern(ext)),
//         }
//     }
//
//     return module;
// }
//
// fn from_core_fn(core_fn: core::Function) -> Function {
//     Function {
//         name: core_fn.name,
//         args: core_fn.args.into_iter().map(|x| x.0).collect(),
//         body: from_core_term(core_fn.body),
//     }
// }
//
// fn from_core_term(core_term: core::Term) -> Term {
//     match core_term {
//         core::Term::Var(n) => Term::Value(Value::Var(n)),
//         core::Term::Literal(l) => Term::Value(Value::Literal(l)),
//         core::Term::App(f, g) => {
//             bind_terms(vec![*f, *g], |values| {
//                 Term::App(values[0].clone(), values[1].clone())
//             })
//         }
//
//         f => panic!("unsupported form: {:?}", f)
//     }
// }
//
// fn bind_terms<F: FnOnce(Vec<Value>) -> Term>(ts: Vec<core::Term>, body: F) -> Term {
//     let mut values = vec![];
//     let mut bindings = vec![];
//
//     for (i, t) in ts.into_iter().enumerate() {
//         let name     = format!("arg{}", i);
//         let cps_term = from_core_term(t);
//
//         match cps_term {
//             Term::Value(v) => values.push(v),
//             t => {
//                 bindings.push((format!("arg{}", i), vec![], Box::new(t)));
//                 values.push(Value::Var(name));
//             }
//         }
//     }
//
//     Term::Fix(bindings, Box::new(body(values)))
// }
<|endoftext|>


<commit_before><commit_msg>Minor renaming.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix offset sign issue<commit_after><|endoftext|>


<commit_before><commit_msg>Day 12 Part 2<commit_after><|endoftext|>


<commit_before><commit_msg>Default CharacterAttributes::image<commit_after><|endoftext|>


<commit_before><commit_msg>Using global buffer in Raknet Session<commit_after><|endoftext|>


<commit_before><commit_msg>use classgrid for saved games<commit_after><|endoftext|>


<commit_before><commit_msg>Implement list-dead subcommand<commit_after><|endoftext|>


<commit_before><commit_msg>Missing file.<commit_after>// Copyright 2014 Johannes Köster.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

//! Mathematical and statistical tools.

use std::cmp;

/// Calculate the number of combinations when choosing
/// k elements from n elements without replacement.
/// This is also known as n over k, or the binomial coefficient.
pub fn comb(n: u64, k: u64) -> u64 {
    if k > n {
        0
    }
    else {
        let mut comb = 1;
        for j in 0..cmp::min(k, n-k) {
            comb = (comb * (n - j)) / (j + 1)
        }
        comb
    }
}

/// Calculate the number of combinations when choosing
/// k elements from n elements with replacement.
pub fn comb_with_repl(n: u64, k: u64) -> u64 {
    comb(n + k - 1, k)
}

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

    #[test]
    fn test_comb() {
        assert_eq!(comb(10, 3), 120);
        assert_eq!(comb_with_repl(10, 3), 220);
    }
}
<|endoftext|>


<commit_before>use collections::BTreeMap;

use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::{Read, Seek, SeekFrom};
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileType {
    description: String,
    icon: BMPFile,
}

impl FileType {
    pub fn new(desc: &str, icon: &str) -> FileType {
        FileType { description: desc.to_string(), icon: load_icon(icon) }
    }

}

pub struct FileManager {
    file_types: BTreeMap<String, FileType>,
    /*
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    */
    files: Vec<String>,
    file_sizes: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            file_types: {
                let mut file_types = BTreeMap::<String, FileType>::new();
                file_types.insert("/".to_string(),
                                  FileType::new("Folder", "inode-directory"));
                file_types.insert("wav".to_string(),
                                  FileType::new("WAV audio", "audio-x-wav"));
                file_types.insert("bin".to_string(),
                                  FileType::new("Executable", "application-x-executable"));
                file_types.insert("bmp".to_string(),
                                  FileType::new("Bitmap Image", "image-x-generic"));
                file_types.insert("rs".to_string(),
                                  FileType::new("Rust source code", "image-x-makefile"));
                file_types.insert("crate".to_string(),
                                  FileType::new("Rust crate", "image-x-makefile"));
                file_types.insert("asm".to_string(),
                                  FileType::new("Assembly source", "image-x-makefile"));
                file_types.insert("list".to_string(),
                                  FileType::new("Disassembly source", "image-x-makefile"));
                file_types.insert("c".to_string(),
                                  FileType::new("C source code", "image-x-makefile"));
                file_types.insert("cpp".to_string(),
                                  FileType::new("C++ source code", "image-x-makefile"));
                file_types.insert("sh".to_string(),
                                  FileType::new("Shell script", "image-x-script"));
                file_types.insert("lua".to_string(),
                                  FileType::new("Lua script", "image-x-script"));
                file_types.insert("txt".to_string(),
                                  FileType::new("plain text document", "text-x-generic"));
                file_types.insert("md".to_string(),
                                  FileType::new("Markdown", "text-x-generic"));
                file_types.insert(String::new(),
                                  FileType::new("Unknown file", "unknown"));
                file_types
            },
            files: Vec::new(),
            file_sizes: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn load_icon_with(&self, file_name: &str, row: isize, window: &mut Window) {
        if let Some(pos) = file_name.find('.') {
            match self.file_types.get(&file_name[(pos + 1)..]) {
                Some(file_type) => {
                    window.image(0,
                                 32 * row,
                                 file_type.icon.width(),
                                 file_type.icon.height(),
                                 file_type.icon.as_slice());
                }
                None => {
                    window.image(0,
                                 32 * row,
                                 self.file_types[""].icon.width(),
                                 self.file_types[""].icon.height(),
                                 self.file_types[""].icon.as_slice());
                }
            }
        }
        else if file_name.ends_with("/") {
            window.image(0,
                         32 * row as isize,
                         self.file_types["/"].icon.width(),
                         self.file_types["/"].icon.height(),
                         self.file_types["/"].icon.as_slice());
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        let column1 = {
            let mut tmp = 0;
            for string in self.files.iter() {
                if tmp < string.len() {
                    tmp = string.len();
                }
            }
            tmp + 1
        };
        for (file_name, file_size) in self.files.iter().zip(self.file_sizes.iter()) {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            self.load_icon_with(&file_name, row as isize, window);

            let mut col = 0;
            for c in file_name.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column1;

            for c in file_size.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                self.files.push(entry.to_string());
                self.file_sizes.push(
                    match File::open(&(path.to_string() + entry)) {
                        Some(mut file) => {
                            // When the entry is a folder
                            if entry.ends_with('/') {
                                let mut string = String::new();
                                file.read_to_string(&mut string);

                                let count = string.split('\n').count();
                                if count == 1 {
                                    "1 entry".to_string()
                                } else {
                                    format!("{} entries", count)
                                }
                            } else {
                                match file.seek(SeekFrom::End(0)) {
                                    Some(size) => {
                                        if size >= 1_000_000_000 {
                                            format!("{:.1} GB", (size as f64)/1_000_000_000.0)
                                        } else if size >= 1_000_000 {
                                            format!("{:.1} MB", (size as f64)/1_000_000.0)
                                        } else if size >= 1_000 {
                                            format!("{:.1} KB", (size as f64)/1_000.0)
                                        } else {
                                            format!("{:.1} bytes", size)
                                        }
                                    }
                                    None => "Failed to seek".to_string()
                                }
                            }
                        },
                        None => "Failed to open".to_string(),
                    }
                );
                // Unwrapping the last file size will not panic since it has
                // been at least pushed once in the vector
                let current_width = (40 + (entry.len() + 1) * 8) +
                                    (8 + (self.file_sizes.last().unwrap().len() + 1) * 8);
                if width < current_width {
                    width = current_width;
                }
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<commit_msg>Add file description column in file manager<commit_after>use collections::BTreeMap;

use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::{Read, Seek, SeekFrom};
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileType {
    description: String,
    icon: BMPFile,
}

impl FileType {
    pub fn new(desc: &str, icon: &str) -> FileType {
        FileType { description: desc.to_string(), icon: load_icon(icon) }
    }

}

pub struct FileManager {
    file_types: BTreeMap<String, FileType>,
    /*
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    */
    files: Vec<String>,
    file_sizes: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            file_types: {
                let mut file_types = BTreeMap::<String, FileType>::new();
                file_types.insert("/".to_string(),
                                  FileType::new("Folder", "inode-directory"));
                file_types.insert("wav".to_string(),
                                  FileType::new("WAV audio", "audio-x-wav"));
                file_types.insert("bin".to_string(),
                                  FileType::new("Executable", "application-x-executable"));
                file_types.insert("bmp".to_string(),
                                  FileType::new("Bitmap Image", "image-x-generic"));
                file_types.insert("rs".to_string(),
                                  FileType::new("Rust source code", "image-x-makefile"));
                file_types.insert("crate".to_string(),
                                  FileType::new("Rust crate", "image-x-makefile"));
                file_types.insert("asm".to_string(),
                                  FileType::new("Assembly source", "image-x-makefile"));
                file_types.insert("list".to_string(),
                                  FileType::new("Disassembly source", "image-x-makefile"));
                file_types.insert("c".to_string(),
                                  FileType::new("C source code", "image-x-makefile"));
                file_types.insert("cpp".to_string(),
                                  FileType::new("C++ source code", "image-x-makefile"));
                file_types.insert("sh".to_string(),
                                  FileType::new("Shell script", "image-x-script"));
                file_types.insert("lua".to_string(),
                                  FileType::new("Lua script", "image-x-script"));
                file_types.insert("txt".to_string(),
                                  FileType::new("plain text document", "text-x-generic"));
                file_types.insert("md".to_string(),
                                  FileType::new("Markdown", "text-x-generic"));
                file_types.insert(String::new(),
                                  FileType::new("Unknown file", "unknown"));
                file_types
            },
            files: Vec::new(),
            file_sizes: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn load_icon_with(&self, file_name: &str, row: isize, window: &mut Window) {
        if let Some(pos) = file_name.find('.') {
            match self.file_types.get(&file_name[(pos + 1)..]) {
                Some(file_type) => {
                    window.image(0,
                                 32 * row,
                                 file_type.icon.width(),
                                 file_type.icon.height(),
                                 file_type.icon.as_slice());
                }
                None => {
                    window.image(0,
                                 32 * row,
                                 self.file_types[""].icon.width(),
                                 self.file_types[""].icon.height(),
                                 self.file_types[""].icon.as_slice());
                }
            }
        }
        else if file_name.ends_with("/") {
            window.image(0,
                         32 * row as isize,
                         self.file_types["/"].icon.width(),
                         self.file_types["/"].icon.height(),
                         self.file_types["/"].icon.as_slice());
        }
    }

    fn get_description(&self, file_name: &str) -> String {
        if let Some(pos) = file_name.find('.') {
            match self.file_types.get(&file_name[(pos + 1)..]) {
                Some(file_type) => file_type.description.clone(),
                None => self.file_types[""].description.clone(),
            }
        }
        else { self.file_types["/"].description.clone() }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        let (column1, column2) = {
            let mut tmp1 = 0;
            for string in self.files.iter() {
                if tmp1 < string.len() {
                    tmp1 = string.len();
                }
            }

            let mut tmp2 = 0;
            for file_size in self.file_sizes.iter() {
                if tmp2 < file_size.len() {
                    tmp2 = file_size.len();
                }
            }
            (tmp1 + 1, tmp1 + 1 + tmp2 + 1)
        };
        for (file_name, file_size) in self.files.iter().zip(self.file_sizes.iter()) {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            self.load_icon_with(&file_name, row as isize, window);

            let mut col = 0;
            for c in file_name.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column1;

            for c in file_size.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column2;

            for c in self.get_description(file_name).chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                self.files.push(entry.to_string());
                self.file_sizes.push(
                    match File::open(&(path.to_string() + entry)) {
                        Some(mut file) => {
                            // When the entry is a folder
                            if entry.ends_with('/') {
                                let mut string = String::new();
                                file.read_to_string(&mut string);

                                let count = string.split('\n').count();
                                if count == 1 {
                                    "1 entry".to_string()
                                } else {
                                    format!("{} entries", count)
                                }
                            } else {
                                match file.seek(SeekFrom::End(0)) {
                                    Some(size) => {
                                        if size >= 1_000_000_000 {
                                            format!("{:.1} GB", (size as f64)/1_000_000_000.0)
                                        } else if size >= 1_000_000 {
                                            format!("{:.1} MB", (size as f64)/1_000_000.0)
                                        } else if size >= 1_000 {
                                            format!("{:.1} KB", (size as f64)/1_000.0)
                                        } else {
                                            format!("{:.1} bytes", size)
                                        }
                                    }
                                    None => "Failed to seek".to_string()
                                }
                            }
                        },
                        None => "Failed to open".to_string(),
                    }
                );
                // Unwrapping the last file size will not panic since it has
                // been at least pushed once in the vector
                let tmp_width = (40 + (entry.len() + 1) * 8) +
                                (8 + (self.file_sizes.last().unwrap().len() + 1) * 8) +
                                (8 + (self.get_description(entry).len() + 1) * 8);
                if width < tmp_width {
                    width = tmp_width;
                }
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<|endoftext|>


<commit_before><commit_msg>The gstreamer plugin should resize when it's presented with frames to fill, not when caps are set<commit_after><|endoftext|>


<commit_before><commit_msg>chore: holy implementation of std::ops::Add<commit_after><|endoftext|>


<commit_before><commit_msg>Added test for deref projection.<commit_after>// run-pass

// Issue #62007: assigning over a deref projection of a box (in this
// case, `*list = n;`) should be able to kill all borrows of `*list`,
// so that `*list` can be borrowed on the next iteration through the
// loop.

#![allow(dead_code)]

struct List<T> {
    value: T,
    next: Option<Box<List<T>>>,
}

fn to_refs<T>(mut list: Box<&mut List<T>>) -> Vec<&mut T> {
    let mut result = vec![];
    loop {
        result.push(&mut list.value);
        if let Some(n) = list.next.as_mut() {
            *list = n;
        } else {
            return result;
        }
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #70131 - Aaron1011:fix/issue-55099-test, r=nikomatsakis<commit_after>// check-pass
// Regression test for issue #55099
// Tests that we don't incorrectly consider a lifetime to part
// of the concrete type

#![feature(type_alias_impl_trait)]

trait Future {
}

struct AndThen<F>(F);

impl<F> Future for AndThen<F> {
}

struct Foo<'a> {
    x: &'a mut (),
}

type F = impl Future;

impl<'a> Foo<'a> {
    fn reply(&mut self) -> F {
        AndThen(|| ())
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add a test that tests typestate checking inside of fn exprs.<commit_after>// error-pattern:Unsatisfied precondition
// xfail-stage0

fn main() {
    // Typestate should work even in a lambda. we should reject this program.
    auto f = fn () -> int {
        let int i;
        ret i;
    };
    log_err f();
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue-48010<commit_after>// check-pass

#![crate_type = "lib"]

pub struct Foo;

pub struct Path<T: Bar> {
    _inner: T::Slice,
}

pub trait Bar: Sized {
    type Slice: ?Sized;

    fn open(_: &Path<Self>);
}

impl Bar for Foo {
    type Slice = [u8];

    fn open(_: &Path<Self>) {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before>use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::Read;
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        for string in self.files.iter() {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if string.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if string.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if string.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if string.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if string.ends_with(".rs") || string.ends_with(".asm") || string.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if string.ends_with(".sh") || string.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if string.ends_with(".md") || string.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in string.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }
            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                if width < 40 + (entry.len() + 1) * 8 {
                    width = 40 + (entry.len() + 1) * 8;
                }
                self.files.push(entry.to_string());
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<commit_msg>Implement file size and entry count for the file manager<commit_after>use redox::{self, env, BMPFile};
use redox::event::{self, EventOption, MouseEvent};
use redox::fs::file::File;
use redox::io::{Read, Seek, SeekFrom};
use redox::orbital::Window;
use redox::time::{self, Duration};
use redox::vec::Vec;
use redox::string::{String, ToString};

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    file_sizes: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut vec: Vec<u8> = Vec::new();
    if let Some(mut file) = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp")) {
        file.read_to_end(&mut vec);
    }
    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            file_sizes: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            },
            click_time: Duration::new(0, 0),
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        let column1 = {
            let mut tmp = 0;
            for string in self.files.iter() {
                if tmp < string.len() {
                    tmp = string.len();
                }
            }
            tmp + 1
        };
        for (file_name, file_size) in self.files.iter().zip(self.file_sizes.iter()) {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if file_name.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if file_name.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if file_name.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if file_name.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if file_name.ends_with(".rs") || file_name.ends_with(".asm") || file_name.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if file_name.ends_with(".sh") || file_name.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if file_name.ends_with(".md") || file_name.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in file_name.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            col = column1;

            for c in file_size.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }

            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        if let Some(mut file) = File::open(path) {
            let mut list = String::new();
            file.read_to_string(&mut list);

            for entry in list.split('\n') {
                self.files.push(entry.to_string());
                self.file_sizes.push(
                    match File::open(&(path.to_string() + entry)) {
                        Some(mut file) => {
                            // When the entry is a folder
                            if entry.ends_with('/') {
                                let mut string = String::new();
                                file.read_to_string(&mut string);

                                let count = string.split('\n').count();
                                if count == 1 {
                                    "1 entry".to_string()
                                } else {
                                    format!("{} entries", count)
                                }
                            } else {
                                match file.seek(SeekFrom::End(0)) {
                                    Some(size) => {
                                        if size >= 1_000 {
                                            format!("{:.1} KB", (size as f64)/1_000.0)
                                        } else if size >= 1_000_000 {
                                            format!("{:.1} MB", (size as f64)/1_000_000.0)
                                        } else if size >= 1_000_000_000 {
                                            format!("{:.1} GB", (size as f64)/1_000_000_000.0)
                                        } else {
                                            format!("{:.1} bytes", size)
                                        }
                                    }
                                    None => "Failed to seek".to_string()
                                }
                            }
                        },
                        None => "Failed to open".to_string(),
                    }
                );
                // Unwrapping the last file size will not panic since it has
                // been at least pushed once in the vector
                let current_width = (40 + (entry.len() + 1) * 8) +
                                    (8 + (self.file_sizes.last().unwrap().len() + 1) * 8);
                if width < current_width {
                    width = current_width;
                }
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((redox::rand() % 400 + 50) as isize,
                                     (redox::rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path).unwrap();

        self.draw_content(&mut window);

        while let Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            event::K_ESC => break,
                            event::K_HOME => self.selected = 0,
                            event::K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            event::K_END => self.selected = self.files.len() as isize - 1,
                            event::K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Some(file) => {
                                                File::exec(&(path.to_string() + &file));
                                            },
                                            None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }

                    //Check for double click
                    if mouse_event.left_button {
                        let click_time = Duration::realtime();

                        if click_time - self.click_time < Duration::new(0, 500 * time::NANOS_PER_MILLI)
                            && self.last_mouse_event.x == mouse_event.x
                            && self.last_mouse_event.y == mouse_event.y {
                            if self.selected >= 0 && self.selected < self.files.len() as isize {
                                match self.files.get(self.selected as usize) {
                                    Some(file) => {
                                        File::exec(&(path.to_string() + &file));
                                    },
                                    None => (),
                                }
                            }
                            self.click_time = Duration::new(0, 0);
                        } else {
                            self.click_time = click_time;
                        }
                    }
                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match env::args().get(1) {
        Some(arg) => FileManager::new().main(arg),
        None => FileManager::new().main("file:///"),
    }
}
<|endoftext|>


<commit_before><commit_msg>Refactor calc_neighbors<commit_after><|endoftext|>


<commit_before><commit_msg>Add HeapSizeOf impl for ParseError<commit_after><|endoftext|>


<commit_before><commit_msg>Add some commented debug code for dumping the main thread's ID on Windows<commit_after><|endoftext|>


<commit_before><commit_msg>Avoid locking in the signal handler<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #65<commit_after>use std::bigint::{ BigUint };

use core::util::{ swap };

use common::problem::{ Problem };

pub static problem: Problem<'static> = Problem {
    id: 65,
    answer: "272",
    solver: solve
};

fn napier_seq(i: uint) -> uint {
    match i {
        0 => 2,
        i if i % 3 == 2 => 2 * (i + 1) / 3,
        _ => 1
    }
}

fn fold_cont_frac(ns: &[uint]) -> (BigUint, BigUint) {
    let mut numer = BigUint::from_uint(1);
    let mut denom = BigUint::from_uint(0);

    for ns.each_reverse |&n| {
        swap(&mut numer, &mut denom);
        numer = numer + BigUint::from_uint(n) * denom;
    }

    return (numer, denom);
}

fn solve() -> ~str {
    let len = 100;

    let napier = vec::from_fn(len, napier_seq);

    let (n, _d) = fold_cont_frac(napier);
    let mut sum = 0;
    for str::each_char(n.to_str()) |c| {
        sum += char::to_digit(c, 10).get();
    }
    return sum.to_str();
}

<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten
// ignore-android

// Test that the simd floating-point math intrinsics produce correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fsqrt<T>(x: T) -> T;
    fn simd_fabs<T>(x: T) -> T;
    fn simd_fsin<T>(x: T) -> T;
    fn simd_fcos<T>(x: T) -> T;
    fn simd_ceil<T>(x: T) -> T;
    fn simd_fexp<T>(x: T) -> T;
    fn simd_fexp2<T>(x: T) -> T;
    fn simd_floor<T>(x: T) -> T;
    fn simd_fma<T>(x: T, y: T, z: T) -> T;
    fn simd_flog<T>(x: T) -> T;
    fn simd_flog10<T>(x: T) -> T;
    fn simd_flog2<T>(x: T) -> T;
    fn simd_fpow<T>(x: T, y: T) -> T;
    fn simd_fpowi<T>(x: T, y: i32) -> T;
}

fn main() {
    let x = f32x4(1.0, 1.0, 1.0, 1.0);
    let y = f32x4(-1.0, -1.0, -1.0, -1.0);
    let z = f32x4(0.0, 0.0, 0.0, 0.0);

    let h = f32x4(0.5, 0.5, 0.5, 0.5);

    unsafe {
        let r = simd_fabs(y);
        assert_eq!(x, r);

        let r = simd_fcos(z);
        assert_eq!(x, r);

        let r = simd_ceil(h);
        assert_eq!(x, r);

        let r = simd_fexp(z);
        assert_eq!(x, r);

        let r = simd_fexp2(z);
        assert_eq!(x, r);

        let r = simd_floor(h);
        assert_eq!(z, r);

        let r = simd_fma(x, h, h);
        assert_eq!(x, r);

        let r = simd_fsqrt(x);
        assert_eq!(x, r);

        let r = simd_flog(x);
        assert_eq!(z, r);

        let r = simd_flog2(x);
        assert_eq!(z, r);

        let r = simd_flog10(x);
        assert_eq!(z, r);

        let r = simd_fpow(h, x);
        assert_eq!(h, r);

        let r = simd_fpowi(h, 1);
        assert_eq!(h, r);

        let r = simd_fsin(z);
        assert_eq!(z, r);
    }
}
<commit_msg>add comment explaining ignore android<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten
// ignore-android

// FIXME: this test fails on arm-android because the NDK version 14 is too old.
// It needs at least version 18. We disable it on all android build bots because
// there is no way in compile-test to disable it for an (arch,os) pair.

// Test that the simd floating-point math intrinsics produce correct results.

#![feature(repr_simd, platform_intrinsics)]
#![allow(non_camel_case_types)]

#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
struct f32x4(pub f32, pub f32, pub f32, pub f32);

extern "platform-intrinsic" {
    fn simd_fsqrt<T>(x: T) -> T;
    fn simd_fabs<T>(x: T) -> T;
    fn simd_fsin<T>(x: T) -> T;
    fn simd_fcos<T>(x: T) -> T;
    fn simd_ceil<T>(x: T) -> T;
    fn simd_fexp<T>(x: T) -> T;
    fn simd_fexp2<T>(x: T) -> T;
    fn simd_floor<T>(x: T) -> T;
    fn simd_fma<T>(x: T, y: T, z: T) -> T;
    fn simd_flog<T>(x: T) -> T;
    fn simd_flog10<T>(x: T) -> T;
    fn simd_flog2<T>(x: T) -> T;
    fn simd_fpow<T>(x: T, y: T) -> T;
    fn simd_fpowi<T>(x: T, y: i32) -> T;
}

fn main() {
    let x = f32x4(1.0, 1.0, 1.0, 1.0);
    let y = f32x4(-1.0, -1.0, -1.0, -1.0);
    let z = f32x4(0.0, 0.0, 0.0, 0.0);

    let h = f32x4(0.5, 0.5, 0.5, 0.5);

    unsafe {
        let r = simd_fabs(y);
        assert_eq!(x, r);

        let r = simd_fcos(z);
        assert_eq!(x, r);

        let r = simd_ceil(h);
        assert_eq!(x, r);

        let r = simd_fexp(z);
        assert_eq!(x, r);

        let r = simd_fexp2(z);
        assert_eq!(x, r);

        let r = simd_floor(h);
        assert_eq!(z, r);

        let r = simd_fma(x, h, h);
        assert_eq!(x, r);

        let r = simd_fsqrt(x);
        assert_eq!(x, r);

        let r = simd_flog(x);
        assert_eq!(z, r);

        let r = simd_flog2(x);
        assert_eq!(z, r);

        let r = simd_flog10(x);
        assert_eq!(z, r);

        let r = simd_fpow(h, x);
        assert_eq!(h, r);

        let r = simd_fpowi(h, 1);
        assert_eq!(h, r);

        let r = simd_fsin(z);
        assert_eq!(z, r);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #25180<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

const x: &'static Fn() = &|| println!("ICE here");

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test to show issue with ScalarPair parameters<commit_after>// only-cdb
// compile-flags: -g

// cdb-command: g

// cdb-command: dx r1
// cdb-check:r1               : (0xa..0xc) [Type: core::ops::range::Range<u32>]
// cdb-command: dx r2
// cdb-check:r2               : 0x14 [Type: core::ops::range::Range<u64> *]

// cdb-command: g

// cdb-command: dx r1
// cdb-check:r1               : (0x9..0x64) [Type: core::ops::range::Range<u32>]
// cdb-command: dx r2
// cdb-check:r2               : 0xc [Type: core::ops::range::Range<u64> *]

// cdb-command: g

// cdb-command: dx o1
// cdb-check:o1               : Some [Type: enum$<core::option::Option<u32> >]
// cdb-check:    [variant]        : Some
// cdb-check:    [+0x004] __0              : 0x4d2 [Type: [...]]
// cdb-command: dx o2
// cdb-check:o2               : 0x1 [Type: enum$<core::option::Option<u64> > *]
// cdb-check:    [variant]

// cdb-command: g

// cdb-command: dx t1
// cdb-check:t1               : (0xa, 0x14) [Type: tuple$<u32,u32>]
// cdb-check:    [0]              : 0xa [Type: unsigned int]
// cdb-check:    [1]              : 0x14 [Type: unsigned int]
// cdb-command: dx t2
// cdb-check:t2               : 0x1e [Type: tuple$<u64,u64> *]
// cdb-check:    [0]              : Unable to read memory at Address 0x1e
// cdb-check:    [1]              : Unable to read memory at Address 0x26

// cdb-command: g

// cdb-command: dx s
// cdb-check:s                : "this is a static str" [Type: str]
// cdb-check:    [len]            : 0x14 [Type: unsigned __int64]
// cdb-check:    [chars]

// cdb-command: g

// cdb-command: dx s
// cdb-check:s                : { len=0x5 } [Type: slice$<u8>]
// cdb-check:    [len]            : 0x5 [Type: unsigned __int64]
// cdb-check:    [0]              : 0x1 [Type: unsigned char]
// cdb-check:    [1]              : 0x2 [Type: unsigned char]
// cdb-check:    [2]              : 0x3 [Type: unsigned char]
// cdb-check:    [3]              : 0x4 [Type: unsigned char]
// cdb-check:    [4]              : 0x5 [Type: unsigned char]

use std::ops::Range;

fn range(r1: Range<u32>, r2: Range<u64>) {
    zzz(); // #break
}

fn range_mut(mut r1: Range<u32>, mut r2: Range<u64>) {
    if r1.start == 9 {
        r1.end = 100;
    }

    if r2.start == 12 {
        r2.end = 90;
    }

    zzz(); // #break
}

fn option(o1: Option<u32>, o2: Option<u64>) {
    zzz(); // #break
}

fn tuple(t1: (u32, u32), t2: (u64, u64)) {
    zzz(); // #break
}

fn str(s: &str) {
    zzz(); // #break
}

fn slice(s: &[u8]) {
    zzz(); // #break
}

fn zzz() { }

fn main() {
    range(10..12, 20..30);
    range_mut(9..20, 12..80);
    option(Some(1234), Some(5678));
    tuple((10, 20), (30, 40));
    str("this is a static str");
    slice(&[1, 2, 3, 4, 5]);
}
<|endoftext|>


<commit_before><commit_msg>Rename DFn to DepFn<commit_after><|endoftext|>


<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct yes0<'self> {
  x: &uint, //~ ERROR Illegal anonymous lifetime: anonymous lifetimes are not permitted here
}

struct yes1<'self> {
  x: &'self uint,
}

struct yes2<'self> {
  x: &'foo uint, //~ ERROR Illegal lifetime 'foo: this lifetime must be declared
}

fn main() {}
<commit_msg>test: Fix botched error message in compile-fail test<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

struct yes0<'self> {
  x: &uint, //~ ERROR Illegal anonymous lifetime: anonymous lifetimes are not permitted here
}

struct yes1<'self> {
  x: &'self uint,
}

struct yes2<'self> {
  x: &'foo uint, //~ ERROR Illegal lifetime 'foo: only 'self is allowed
}

fn main() {}
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate semver;
extern crate clap;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagref;
extern crate libimagerror;
extern crate libimagentrylist;
extern crate libimaginteraction;

mod ui;
use ui::build_ui;

use std::path::PathBuf;

use libimagref::reference::Ref;
use libimagref::flags::RefFlags;
use libimagerror::trace::trace_error;
use libimagrt::setup::generate_runtime_setup;
use libimagrt::runtime::Runtime;

fn main() {
    let rt = generate_runtime_setup("imag-ref",
                                    &version!()[..],
                                    "Reference files outside of the store",
                                    build_ui);
    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "add"    => add(&rt),
                "remove" => remove(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn add(rt: &Runtime) {
    let cmd  = rt.cli().subcommand_matches("add").unwrap();
    let path = cmd.value_of("path").map(PathBuf::from).unwrap(); // saved by clap

    let flags = RefFlags::default()
        .with_content_hashing(cmd.is_present("track-content"))
        .with_permission_tracking(cmd.is_present("track-permissions"));

    match Ref::create(rt.store(), path, flags) {
        Ok(r) => {
            debug!("Reference created: {:?}", r);
            info!("Ok");
        },
        Err(e) => {
            trace_error(&e);
            warn!("Failed to create reference");
        },
    }
}

fn remove(rt: &Runtime) {
    use libimaginteraction::ask::ask_bool;

    let cmd  = rt.cli().subcommand_matches("remove").unwrap();
    let hash = cmd.value_of("hash").map(String::from).unwrap(); // saved by clap
    let yes  = cmd.is_present("yes");

    if yes || ask_bool(&format!("Delete Ref with hash '{}'", hash)[..], None) {
        match Ref::delete_by_hash(rt.store(), hash) {
            Err(e) => trace_error(&e),
            Ok(_) => info!("Ok"),
        }
    } else {
        info!("Aborted");
    }

}

fn list(rt: &Runtime) {
    use std::process::exit;

    use libimagentrylist::lister::Lister;
    use libimagref::lister::RefLister;

    let cmd                      = rt.cli().subcommand_matches("list").unwrap();
    let do_check_dead            = cmd.is_present("check-dead");
    let do_check_changed         = cmd.is_present("check-changed");
    let do_check_changed_content = cmd.is_present("check-changed-content");
    let do_check_changed_permiss = cmd.is_present("check-changed-permissions");

    let iter = match rt.store().retrieve_for_module("ref") {
        Ok(iter) => iter.filter_map(|id| {
            match Ref::get(rt.store(), id) {
                Ok(r) => Some(r),
                Err(e) => {
                    trace_error(&e);
                    None
                },
            }
        }),
        Err(e) => {
            trace_error(&e);
            exit(1);
        }
    };

    RefLister::new()
        .check_dead(do_check_dead)
        .check_changed(do_check_changed)
        .check_changed_content(do_check_changed_content)
        .check_changed_permiss(do_check_changed_permiss)
        .list(iter.map(|e| e.into()))
        .ok();
}

<commit_msg>Deny warnings<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

#![deny(
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

#[macro_use] extern crate log;
#[macro_use] extern crate version;
extern crate semver;
extern crate clap;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagref;
extern crate libimagerror;
extern crate libimagentrylist;
extern crate libimaginteraction;

mod ui;
use ui::build_ui;

use std::path::PathBuf;

use libimagref::reference::Ref;
use libimagref::flags::RefFlags;
use libimagerror::trace::trace_error;
use libimagrt::setup::generate_runtime_setup;
use libimagrt::runtime::Runtime;

fn main() {
    let rt = generate_runtime_setup("imag-ref",
                                    &version!()[..],
                                    "Reference files outside of the store",
                                    build_ui);
    rt.cli()
        .subcommand_name()
        .map(|name| {
            debug!("Call: {}", name);
            match name {
                "add"    => add(&rt),
                "remove" => remove(&rt),
                "list"   => list(&rt),
                _        => {
                    debug!("Unknown command"); // More error handling
                },
            };
        });
}

fn add(rt: &Runtime) {
    let cmd  = rt.cli().subcommand_matches("add").unwrap();
    let path = cmd.value_of("path").map(PathBuf::from).unwrap(); // saved by clap

    let flags = RefFlags::default()
        .with_content_hashing(cmd.is_present("track-content"))
        .with_permission_tracking(cmd.is_present("track-permissions"));

    match Ref::create(rt.store(), path, flags) {
        Ok(r) => {
            debug!("Reference created: {:?}", r);
            info!("Ok");
        },
        Err(e) => {
            trace_error(&e);
            warn!("Failed to create reference");
        },
    }
}

fn remove(rt: &Runtime) {
    use libimaginteraction::ask::ask_bool;

    let cmd  = rt.cli().subcommand_matches("remove").unwrap();
    let hash = cmd.value_of("hash").map(String::from).unwrap(); // saved by clap
    let yes  = cmd.is_present("yes");

    if yes || ask_bool(&format!("Delete Ref with hash '{}'", hash)[..], None) {
        match Ref::delete_by_hash(rt.store(), hash) {
            Err(e) => trace_error(&e),
            Ok(_) => info!("Ok"),
        }
    } else {
        info!("Aborted");
    }

}

fn list(rt: &Runtime) {
    use std::process::exit;

    use libimagentrylist::lister::Lister;
    use libimagref::lister::RefLister;

    let cmd                      = rt.cli().subcommand_matches("list").unwrap();
    let do_check_dead            = cmd.is_present("check-dead");
    let do_check_changed         = cmd.is_present("check-changed");
    let do_check_changed_content = cmd.is_present("check-changed-content");
    let do_check_changed_permiss = cmd.is_present("check-changed-permissions");

    let iter = match rt.store().retrieve_for_module("ref") {
        Ok(iter) => iter.filter_map(|id| {
            match Ref::get(rt.store(), id) {
                Ok(r) => Some(r),
                Err(e) => {
                    trace_error(&e);
                    None
                },
            }
        }),
        Err(e) => {
            trace_error(&e);
            exit(1);
        }
    };

    RefLister::new()
        .check_dead(do_check_dead)
        .check_changed(do_check_changed)
        .check_changed_content(do_check_changed_content)
        .check_changed_permiss(do_check_changed_permiss)
        .list(iter.map(|e| e.into()))
        .ok();
}

<|endoftext|>


<commit_before><commit_msg>Added SDL graphics<commit_after>extern crate sdl;

struct Screen {
    surface sdl::video::Surface,
    on_color : sdl::video::Color,
    off_color :sdl::video::Color,
    x_max :uint,
    y_max :uint

}

impl Screen {

    fn new(width :uint, height :uint, x_max :uint, y_max :uint) -> Screen {
        sdl::init([sdl::InitVideo]);
        sdl::wm::set_caption("CHIP-8 Emulator");

        let surface =
            match sdl::video::set_video_mode(width, height, 32,
            [sdl::video::HWSurface], [sdl::video::DoubleBuf]) {

                Ok(screen) => screen,
                Err(err) => fail!("failed to set video mode: {}", err)
            };

        Screen { surface:surface,
                 on_color:sdl::video::Color  { r:0, g:255, b:0},
                 off_color:sdl::video::Color { r:0, g:0,   b:0},
                 x_max:x_max,
                 y_max:y_max
               }
        }
   }

    fn draw_pix(&mut self, x_pos :uint, y_pos :uint, set:bool) {
        let x_unit = screen.ll.w/screen.x_max;
        let y_uint = screen.ll.h/screen.y_max;

        self.screen.fill_rect(Some(sdl:Rect {
            x: x_pos * x_unit,
            y: y_pos * y_unit,
            w: x_unit,
            h: y_unit,
        }), match set { true => self.on_color, false => self.off_color });
    }

    pub fn clear_screen(&mut self) {
        self.screen.fill_rect(Some(sdl:Rect {
            x: 0,
            y: 0,
            w: self.ll.w,
            h: self.ll.h,
        }), self.off_color);
    }

}

/*
  // Note: You'll want to put this and the flip call inside the main loop
  // but we don't as to not startle epileptics
  for i in range(0, 10) {
      for j in range(0, 10) {
          screen.fill_rect(Some(sdl::Rect {
              x: (i as i16) * 800 / 10,
              y: (j as i16) * 600 / 10,
              w: 800 / 10,
              h: 600 / 10
          }), rng.gen::<sdl::video::Color>());
      }
  }

  screen.flip();

  'main : loop {
      'event : loop {
          match sdl::event::poll_event() {
              sdl::event::QuitEvent => break 'main,
              sdl::event::NoEvent => break 'event,
              sdl::event::KeyEvent(k, _, _, _)
                  if k == sdl::event::EscapeKey
                      => break 'main,
              _ => {}
          }
      }
  }

  sdl::quit();
}
*/
<|endoftext|>


<commit_before><commit_msg>removed some comments<commit_after><|endoftext|>


<commit_before><commit_msg>Commenting style fixes<commit_after><|endoftext|>


<commit_before><commit_msg>Add layout transitions to ensure that the renderpass can specify COLOR_ATTACHMENT_OPTIMAL for the colour attachment<commit_after><|endoftext|>


<commit_before><commit_msg>Use separate image-available and render-finished synchronisation per swapchain image<commit_after><|endoftext|>


<commit_before><commit_msg>Fix gid error because it was set after uid<commit_after><|endoftext|>


<commit_before><commit_msg>Added a simple example of reading non-utf8 files into a Rope.<commit_after>//! Example of decoding from another text encoding on-the-fly while reading.
//! In this case, we're decoding from ISO/IEC 8859-1, which conveniently
//! happens to map 1-to-1 to the first 256 unicode scalar values.

extern crate ropey;

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

use ropey::RopeBuilder;

fn main() {
    // Get filepath from commandline
    let filepath = if std::env::args().count() > 1 {
        std::env::args().nth(1).unwrap()
    } else {
        println!(
            "You must pass a filepath!  Only recieved {} arguments.",
            std::env::args().count()
        );
        panic!()
    };

    // Get everything set up to begin reading and decoding.
    let mut buf = vec![0u8; 1 << 14]; // Buffer for raw bytes.
    let mut buf_str = String::with_capacity(1 << 14); // Buffer for decoded utf8.
    let mut builder = RopeBuilder::new();
    let mut file = io::BufReader::new(File::open(&filepath).unwrap());

    // Read the data in chunks, decoding and appending to the rope builder
    // as we go.
    // (Note: in real code you should handle errors from the reader!)
    while let Ok(n) = file.read(&mut buf) {
        if n == 0 {
            break;
        }

        // Decode and append the chunk to the rope builder.
        buf_str.clear();
        for &byte in &buf[..n] {
            buf_str.push(byte as char);
        }
        builder.append(&buf_str);
    }

    // Build rope.
    let _rope = builder.finish();
}
<|endoftext|>