<commit_before>use std::io::prelude::*;
use std::fs::File;

type Result<T> = std::result::Result<T, String>;

// Setup to make this work. Create two files with some info. Ignore the
// return values because we don't care about them here.
fn setup() {
    File::create("a")
        .and_then(|mut file| file.write_all(b"grape"))
        .unwrap();

    File::create("b")
        .and_then(|mut file| file.write_all(b"fruit"))
        .unwrap();
}

// Get the data from each file with the data stored in a `Result`.
fn get_data(path: &str) -> Result<String> {
    File::open(path)
        .map_err(|err| err.to_string())
        .and_then(|mut file| {
            let mut contents = String::new();

            // Read the data into `contents`.
            file.read_to_string(&mut contents)
                .map_err(|err| err.to_string())
                // Ignore the output `read_to_string` returns and return `contents`.
                .map(|_| contents)
        })
}

// Concat the contents of the two files together into a new `Result`.
fn concat(a: &str, b: &str) -> Result<String> {
    let (data_a, data_b) = (get_data(a), get_data(b));

    data_a.and_then(|a|
        // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return
        // whichever has the first `Err`.
        data_b.and_then(|b| Ok(a + &b))
    )
}

fn main() {
    setup();

    match concat("a", "b") {
        Ok(n)  => println!("{}", n),
        Err(e) => println!("Error: {}", e),
    }
}
<commit_msg>Remove confusing reuse of variables `a` and `b`<commit_after>use std::io::prelude::*;
use std::fs::File;

type Result<T> = std::result::Result<T, String>;

// Setup to make this work. Create two files with some info. Ignore the
// return values because we don't care about them here.
fn setup() {
    File::create("a")
        .and_then(|mut file| file.write_all(b"grape"))
        .unwrap();

    File::create("b")
        .and_then(|mut file| file.write_all(b"fruit"))
        .unwrap();
}

// Get the data from each file with the data stored in a `Result`.
fn get_data(path: &str) -> Result<String> {
    File::open(path)
        .map_err(|err| err.to_string())
        .and_then(|mut file| {
            let mut contents = String::new();

            // Read the data into `contents`.
            file.read_to_string(&mut contents)
                .map_err(|err| err.to_string())
                // Ignore the output `read_to_string` returns and return `contents`.
                .map(|_| contents)
        })
}

// Concat the contents of the two files together into a new `Result`.
fn concat(filename_a: &str, filename_b: &str) -> Result<String> {
    let (data_a, data_b) = (get_data(filename_a), get_data(filename_b));

    data_a.and_then(|a|
        // Return `Ok` when both `a` and `b` are `Ok`. Otherwise return
        // whichever has the first `Err`.
        data_b.and_then(|b| Ok(a + &b))
    )
}

fn main() {
    setup();

    match concat("a", "b") {
        Ok(n)  => println!("{}", n),
        Err(e) => println!("Error: {}", e),
    }
}
<|endoftext|>


<commit_before>use crate::{AssistContext, Assists};
use ide_db::{
    assists::{AssistId, AssistKind},
    syntax_helpers::{
        format_string::is_format_string,
        format_string_exprs::{parse_format_exprs, Arg},
    },
};
use itertools::Itertools;
use syntax::{ast, AstNode, AstToken, NodeOrToken, SyntaxKind::COMMA, TextRange};

// Assist: move_format_string_arg
//
// Move an expression out of a format string.
//
// ```
// macro_rules! format_args {
//     ($lit:literal $(tt:tt)*) => { 0 },
// }
// macro_rules! print {
//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
// }
//
// fn main() {
//     print!("{x + 1}$0");
// }
// ```
// ->
// ```
// macro_rules! format_args {
//     ($lit:literal $(tt:tt)*) => { 0 },
// }
// macro_rules! print {
//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
// }
//
// fn main() {
//     print!("{}"$0, x + 1);
// }
// ```

pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let fmt_string = ctx.find_token_at_offset::<ast::String>()?;
    let tt = fmt_string.syntax().parent().and_then(ast::TokenTree::cast)?;

    let expanded_t = ast::String::cast(
        ctx.sema.descend_into_macros_with_kind_preference(fmt_string.syntax().clone()),
    )?;
    if !is_format_string(&expanded_t) {
        return None;
    }

    let (new_fmt, extracted_args) = parse_format_exprs(fmt_string.text()).ok()?;
    if extracted_args.is_empty() {
        return None;
    }

    acc.add(
        AssistId(
            "move_format_string_arg",
            // if there aren't any expressions, then make the assist a RefactorExtract
            if extracted_args.iter().filter(|f| matches!(f, Arg::Expr(_))).count() == 0 {
                AssistKind::RefactorExtract
            } else {
                AssistKind::QuickFix
            },
        ),
        "Extract format args",
        tt.syntax().text_range(),
        |edit| {
            let fmt_range = fmt_string.syntax().text_range();

            // Replace old format string with new format string whose arguments have been extracted
            edit.replace(fmt_range, new_fmt);

            // Insert cursor at end of format string
            edit.insert(fmt_range.end(), "$0");

            // Extract existing arguments in macro
            let tokens =
                tt.token_trees_and_tokens().filter_map(NodeOrToken::into_token).collect_vec();

            let mut existing_args: Vec<String> = vec![];

            let mut current_arg = String::new();
            if let [_opening_bracket, format_string, _args_start_comma, tokens @ .., end_bracket] =
                tokens.as_slice()
            {
                for t in tokens {
                    if t.kind() == COMMA {
                        existing_args.push(current_arg.trim().into());
                        current_arg.clear();
                    } else {
                        current_arg.push_str(t.text());
                    }
                }
                existing_args.push(current_arg.trim().into());

                // delete everything after the format string till end bracket
                // we're going to insert the new arguments later
                edit.delete(TextRange::new(
                    format_string.text_range().end(),
                    end_bracket.text_range().start(),
                ));
            }

            // Start building the new args
            let mut existing_args = existing_args.into_iter();
            let mut args = String::new();

            let mut placeholder_idx = 1;

            for extracted_args in extracted_args {
                // remove expr from format string
                args.push_str(", ");

                match extracted_args {
                    Arg::Ident(s) | Arg::Expr(s) => {
                        // insert arg
                        args.push_str(&s);
                    }
                    Arg::Placeholder => {
                        // try matching with existing argument
                        match existing_args.next() {
                            Some(ea) => {
                                args.push_str(&ea);
                            }
                            None => {
                                // insert placeholder
                                args.push_str(&format!("${placeholder_idx}"));
                                placeholder_idx += 1;
                            }
                        }
                    }
                }
            }

            // Insert new args
            edit.insert(fmt_range.end(), args);
        },
    );

    Some(())
}

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

    const MACRO_DECL: &'static str = r#"
macro_rules! format_args {
    ($lit:literal $(tt:tt)*) => { 0 },
}
macro_rules! print {
    ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
}
"#;

    fn add_macro_decl(s: &'static str) -> String {
        MACRO_DECL.to_string() + s
    }

    #[test]
    fn multiple_middle_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {}$0", y + 2, 2);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, y + 2, x + 1, 2);
}
"#,
            ),
        );
    }

    #[test]
    fn single_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{obj.value:b}$0",);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{:b}"$0, obj.value);
}
"#,
            ),
        );
    }

    #[test]
    fn multiple_middle_placeholders_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {} {}$0", y + 2, 2);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {} {}"$0, y + 2, x + 1, 2, $1);
}
"#,
            ),
        );
    }

    #[test]
    fn multiple_trailing_args() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
}
"#,
            ),
        );
    }

    #[test]
    fn improper_commas() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1,);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
}
"#,
            ),
        );
    }
}
<commit_msg>Fix move_format_string_arg being tokentree unaware<commit_after>use crate::{AssistContext, Assists};
use ide_db::{
    assists::{AssistId, AssistKind},
    syntax_helpers::{
        format_string::is_format_string,
        format_string_exprs::{parse_format_exprs, Arg},
    },
};
use itertools::Itertools;
use stdx::format_to;
use syntax::{ast, AstNode, AstToken, NodeOrToken, SyntaxKind::COMMA, TextRange};

// Assist: move_format_string_arg
//
// Move an expression out of a format string.
//
// ```
// macro_rules! format_args {
//     ($lit:literal $(tt:tt)*) => { 0 },
// }
// macro_rules! print {
//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
// }
//
// fn main() {
//     print!("{x + 1}$0");
// }
// ```
// ->
// ```
// macro_rules! format_args {
//     ($lit:literal $(tt:tt)*) => { 0 },
// }
// macro_rules! print {
//     ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
// }
//
// fn main() {
//     print!("{}"$0, x + 1);
// }
// ```

pub(crate) fn move_format_string_arg(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
    let fmt_string = ctx.find_token_at_offset::<ast::String>()?;
    let tt = fmt_string.syntax().parent().and_then(ast::TokenTree::cast)?;

    let expanded_t = ast::String::cast(
        ctx.sema.descend_into_macros_with_kind_preference(fmt_string.syntax().clone()),
    )?;
    if !is_format_string(&expanded_t) {
        return None;
    }

    let (new_fmt, extracted_args) = parse_format_exprs(fmt_string.text()).ok()?;
    if extracted_args.is_empty() {
        return None;
    }

    acc.add(
        AssistId(
            "move_format_string_arg",
            // if there aren't any expressions, then make the assist a RefactorExtract
            if extracted_args.iter().filter(|f| matches!(f, Arg::Expr(_))).count() == 0 {
                AssistKind::RefactorExtract
            } else {
                AssistKind::QuickFix
            },
        ),
        "Extract format args",
        tt.syntax().text_range(),
        |edit| {
            let fmt_range = fmt_string.syntax().text_range();

            // Replace old format string with new format string whose arguments have been extracted
            edit.replace(fmt_range, new_fmt);

            // Insert cursor at end of format string
            edit.insert(fmt_range.end(), "$0");

            // Extract existing arguments in macro
            let tokens =
                tt.token_trees_and_tokens().collect_vec();

            let mut existing_args: Vec<String> = vec![];

            let mut current_arg = String::new();
            if let [_opening_bracket, NodeOrToken::Token(format_string), _args_start_comma, tokens @ .., NodeOrToken::Token(end_bracket)] =
                tokens.as_slice()
            {
                for t in tokens {
                    match t {
                        NodeOrToken::Node(n) => {
                            format_to!(current_arg, "{n}");
                        },
                        NodeOrToken::Token(t) if t.kind() == COMMA=> {
                            existing_args.push(current_arg.trim().into());
                            current_arg.clear();
                        },
                        NodeOrToken::Token(t) => {
                            current_arg.push_str(t.text());
                        },
                    }
                }
                existing_args.push(current_arg.trim().into());

                // delete everything after the format string till end bracket
                // we're going to insert the new arguments later
                edit.delete(TextRange::new(
                    format_string.text_range().end(),
                    end_bracket.text_range().start(),
                ));
            }

            // Start building the new args
            let mut existing_args = existing_args.into_iter();
            let mut args = String::new();

            let mut placeholder_idx = 1;

            for extracted_args in extracted_args {
                // remove expr from format string
                args.push_str(", ");

                match extracted_args {
                    Arg::Ident(s) | Arg::Expr(s) => {
                        // insert arg
                        args.push_str(&s);
                    }
                    Arg::Placeholder => {
                        // try matching with existing argument
                        match existing_args.next() {
                            Some(ea) => {
                                args.push_str(&ea);
                            }
                            None => {
                                // insert placeholder
                                args.push_str(&format!("${placeholder_idx}"));
                                placeholder_idx += 1;
                            }
                        }
                    }
                }
            }

            // Insert new args
            edit.insert(fmt_range.end(), args);
        },
    );

    Some(())
}

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

    const MACRO_DECL: &'static str = r#"
macro_rules! format_args {
    ($lit:literal $(tt:tt)*) => { 0 },
}
macro_rules! print {
    ($($arg:tt)*) => (std::io::_print(format_args!($($arg)*)));
}
"#;

    fn add_macro_decl(s: &'static str) -> String {
        MACRO_DECL.to_string() + s
    }

    #[test]
    fn multiple_middle_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {}$0", y + 2, 2);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, y + 2, x + 1, 2);
}
"#,
            ),
        );
    }

    #[test]
    fn single_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{obj.value:b}$0",);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{:b}"$0, obj.value);
}
"#,
            ),
        );
    }

    #[test]
    fn multiple_middle_placeholders_arg() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {} {}$0", y + 2, 2);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {} {}"$0, y + 2, x + 1, 2, $1);
}
"#,
            ),
        );
    }

    #[test]
    fn multiple_trailing_args() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
}
"#,
            ),
        );
    }

    #[test]
    fn improper_commas() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {x + 1:b} {Struct(1, 2)}$0", 1,);
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("{} {:b} {}"$0, 1, x + 1, Struct(1, 2));
}
"#,
            ),
        );
    }

    #[test]
    fn nested_tt() {
        check_assist(
            move_format_string_arg,
            &add_macro_decl(
                r#"
fn main() {
    print!("My name is {} {x$0 + x}", stringify!(Paperino))
}
"#,
            ),
            &add_macro_decl(
                r#"
fn main() {
    print!("My name is {} {}"$0, stringify!(Paperino), x + x)
}
"#,
            ),
        );
    }
}
<|endoftext|>


<commit_before>use lyon::path;
use lyon::path_builder::BaseBuilder;
use lyon::path_iterator::PathIterator;
use lyon::tessellation;
use lyon::tessellation::basic_shapes;
use lyon::tessellation::math;
use lyon::tessellation::path_stroke;
use lyon::tessellation::path_fill;
use lyon::tessellation::geometry_builder;

use super::{Point, Vertex};
use GameError;
use GameResult;

pub type Buffer = geometry_builder::VertexBuffers<Vertex>;

const FLATTEN_TOLERANCE: f32 = 0.5;

pub struct VertexConstructor {
    stroke_width: f32,
}

impl geometry_builder::VertexConstructor<tessellation::StrokeVertex, Vertex> for VertexConstructor {
    fn new_vertex(&mut self, input: tessellation::StrokeVertex) -> Vertex {
        let c = input.position + input.normal * self.stroke_width;
        Vertex {
            pos: [c.x, c.y],
            uv: [c.x, c.y],
        }
    }
}

impl geometry_builder::VertexConstructor<tessellation::FillVertex, Vertex> for VertexConstructor {
    fn new_vertex(&mut self, input: tessellation::FillVertex) -> Vertex {
        let p = input.position;
        Vertex {
            pos: [p.x, p.y],
            uv: [p.x, p.y],
        }
    }
}

fn build_path(points: &[Point], closed: bool) -> path::Path {
    let mut path_builder = path::Builder::with_capacity(points.len());
    path_builder.move_to(math::point(points[0].x, points[0].y));

    for p in &points[1..] {
        path_builder.line_to(math::point(p.x, p.y));
    }

    if closed {
        path_builder.close();
    }

    path_builder.build()
}

fn build_geometry<F, V, E>(line_width: f32, f: F) -> GameResult<Buffer>
    where F: for<'a> FnOnce(&mut geometry_builder::BuffersBuilder<'a, Vertex, V, VertexConstructor>)
                            -> Result<geometry_builder::Count, E>,
        VertexConstructor: geometry_builder::VertexConstructor<V, Vertex>,
{
    let mut buffers = geometry_builder::VertexBuffers::new();
    let vertex_ctor = VertexConstructor { stroke_width: line_width };
    {
        let mut builder = geometry_builder::BuffersBuilder::new(&mut buffers, vertex_ctor);
        if let Err(_) = f(&mut builder) {
            return Err(GameError::RenderError(String::from("geometry tessellation failed")));
        }
    }
    Ok(buffers)
}

fn build_stroke(points: &[Point], close: bool, line_width: f32) -> GameResult<Buffer> {
    let path = build_path(points, close);
    let path_iter = path.path_iter().flattened(FLATTEN_TOLERANCE);
    let opts = path_stroke::StrokeOptions::default();
    let mut tessellator = path_stroke::StrokeTessellator::new();
    build_geometry(line_width, |builder| tessellator.tessellate(path_iter, &opts, builder))
}

pub fn build_line(points: &[Point], line_width: f32) -> GameResult<Buffer> {
    build_stroke(points, false, line_width)
}

/// Build a closed polygon.  Identical to build_line but closes the path,
/// which makes sure the two endpoints actually line up.
pub fn build_polygon(points: &[Point], line_width: f32) -> GameResult<Buffer> {
    build_stroke(points, true, line_width)
}

 pub fn build_polygon_fill(points: &[Point]) -> GameResult<Buffer> {
     let path = build_path(points, true);
     let path_iter = path.path_iter().flattened(FLATTEN_TOLERANCE);
     let opts = path_fill::FillOptions::default();
     let mut tessellator = path_fill::FillTessellator::new();
     build_geometry(0.0, |builder| tessellator.tessellate_path(path_iter, &opts, builder))
 }

pub fn build_ellipse_fill(point: Point, r1: f32, r2: f32, segments: u32) -> GameResult<Buffer> {
    let center = math::point(point.x, point.y);
    let radii = math::point(r1, r2);
    build_geometry(0.0, |builder| Ok::<_, ()>(basic_shapes::fill_ellipse(center, radii, segments, builder)))
}
<commit_msg>Split a long line.<commit_after>use lyon::path;
use lyon::path_builder::BaseBuilder;
use lyon::path_iterator::PathIterator;
use lyon::tessellation;
use lyon::tessellation::basic_shapes;
use lyon::tessellation::math;
use lyon::tessellation::path_stroke;
use lyon::tessellation::path_fill;
use lyon::tessellation::geometry_builder;

use super::{Point, Vertex};
use GameError;
use GameResult;

pub type Buffer = geometry_builder::VertexBuffers<Vertex>;

const FLATTEN_TOLERANCE: f32 = 0.5;

pub struct VertexConstructor {
    stroke_width: f32,
}

impl geometry_builder::VertexConstructor<tessellation::StrokeVertex, Vertex> for VertexConstructor {
    fn new_vertex(&mut self, input: tessellation::StrokeVertex) -> Vertex {
        let c = input.position + input.normal * self.stroke_width;
        Vertex {
            pos: [c.x, c.y],
            uv: [c.x, c.y],
        }
    }
}

impl geometry_builder::VertexConstructor<tessellation::FillVertex, Vertex> for VertexConstructor {
    fn new_vertex(&mut self, input: tessellation::FillVertex) -> Vertex {
        let p = input.position;
        Vertex {
            pos: [p.x, p.y],
            uv: [p.x, p.y],
        }
    }
}

fn build_path(points: &[Point], closed: bool) -> path::Path {
    let mut path_builder = path::Builder::with_capacity(points.len());
    path_builder.move_to(math::point(points[0].x, points[0].y));

    for p in &points[1..] {
        path_builder.line_to(math::point(p.x, p.y));
    }

    if closed {
        path_builder.close();
    }

    path_builder.build()
}

fn build_geometry<F, V, E>(line_width: f32, f: F) -> GameResult<Buffer>
    where F: for<'a> FnOnce(&mut geometry_builder::BuffersBuilder<'a, Vertex, V, VertexConstructor>)
                            -> Result<geometry_builder::Count, E>,
        VertexConstructor: geometry_builder::VertexConstructor<V, Vertex>,
{
    let mut buffers = geometry_builder::VertexBuffers::new();
    let vertex_ctor = VertexConstructor { stroke_width: line_width };
    {
        let mut builder = geometry_builder::BuffersBuilder::new(&mut buffers, vertex_ctor);
        if let Err(_) = f(&mut builder) {
            return Err(GameError::RenderError(String::from("geometry tessellation failed")));
        }
    }
    Ok(buffers)
}

fn build_stroke(points: &[Point], close: bool, line_width: f32) -> GameResult<Buffer> {
    let path = build_path(points, close);
    let path_iter = path.path_iter().flattened(FLATTEN_TOLERANCE);
    let opts = path_stroke::StrokeOptions::default();
    let mut tessellator = path_stroke::StrokeTessellator::new();
    build_geometry(line_width, |builder| tessellator.tessellate(path_iter, &opts, builder))
}

pub fn build_line(points: &[Point], line_width: f32) -> GameResult<Buffer> {
    build_stroke(points, false, line_width)
}

/// Build a closed polygon.  Identical to build_line but closes the path,
/// which makes sure the two endpoints actually line up.
pub fn build_polygon(points: &[Point], line_width: f32) -> GameResult<Buffer> {
    build_stroke(points, true, line_width)
}

 pub fn build_polygon_fill(points: &[Point]) -> GameResult<Buffer> {
     let path = build_path(points, true);
     let path_iter = path.path_iter().flattened(FLATTEN_TOLERANCE);
     let opts = path_fill::FillOptions::default();
     let mut tessellator = path_fill::FillTessellator::new();
     build_geometry(0.0, |builder| tessellator.tessellate_path(path_iter, &opts, builder))
 }

pub fn build_ellipse_fill(point: Point, r1: f32, r2: f32, segments: u32) -> GameResult<Buffer> {
    let center = math::point(point.x, point.y);
    let radii = math::point(r1, r2);
    build_geometry(0.0, |builder| {
        let count = basic_shapes::fill_ellipse(center, radii, segments, builder);
        Ok::<_, ()>(count)
    })
}
<|endoftext|>


<commit_before>#![cfg_attr(all(feature="serde_type"), feature(custom_derive, plugin))]
#![cfg_attr(all(feature="serde_type"), plugin(serde_macros))]
extern crate env_logger;
#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
extern crate rustc_serialize;
extern crate handlebars;

#[cfg(feature = "serde_type")]
extern crate serde;
#[cfg(feature = "serde_type")]
extern crate serde_json;

use std::io::{self, Write};
use std::process;
use std::env;

use rustc_serialize::json::Json;

use handlebars::Handlebars;

fn usage() -> ! {
    writeln!(&mut io::stderr(), "{}",
        r#"Usage: ./render-cli template.hbs '{"json": "data"}'"#).ok();
    process::exit(1);
}

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
fn parse_json(text: &str) -> Json {
    match Json::from_str(text) {
        Ok(json) => json,
        Err(_) => usage(),
    }
}
#[cfg(feature = "serde_type")]
fn parse_json(text: &str) -> Value {
    match serde_json::from_str(text) {
        Ok(json) => json,
        Err(_) => usage(),
    }
}

fn main() {
    env_logger::init().unwrap();

    let mut args = env::args();
    args.next(); // skip own filename
    let (filename, json) = match (args.next(), args.next()) {
        (Some(filename), Some(json)) => (filename, json),
        _ => usage(),
    };
    let data = parse_json(&json);

    let mut handlebars = Handlebars::new();

    handlebars.register_template_file(&filename, &filename)
              .ok()
              .unwrap();
    match handlebars.render(&filename, &data) {
        Ok(data) => {
            println!("{}", data);
        }
        Err(e) => {
            println!("Error rendering {}: {}", filename, e);
            process::exit(2);
        }
    }
}
<commit_msg>(fix) fixed template cli<commit_after>#![allow(unused_imports, dead_code)]
extern crate env_logger;
#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
extern crate rustc_serialize;
extern crate handlebars;

use std::io::{self, Write};
use std::process;
use std::env;

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
use rustc_serialize::json::Json;

use handlebars::Handlebars;

fn usage() -> ! {
    writeln!(&mut io::stderr(),
             "{}",
             r#"Usage: ./render-cli template.hbs '{"json": "data"}'"#)
        .ok();
    process::exit(1);
}

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
fn parse_json(text: &str) -> Json {
    match Json::from_str(text) {
        Ok(json) => json,
        Err(_) => usage(),
    }
}

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
fn main() {
    env_logger::init().unwrap();

    let mut args = env::args();
    args.next(); // skip own filename
    let (filename, json) = match (args.next(), args.next()) {
        (Some(filename), Some(json)) => (filename, json),
        _ => usage(),
    };
    let data = parse_json(&json);

    let mut handlebars = Handlebars::new();

    handlebars.register_template_file(&filename, &filename)
              .ok()
              .unwrap();
    match handlebars.render(&filename, &data) {
        Ok(data) => {
            println!("{}", data);
        }
        Err(e) => {
            println!("Error rendering {}: {}", filename, e);
            process::exit(2);
        }
    }
}

#[cfg(feature = "serde_type")]
fn main() {}
<|endoftext|>


<commit_before>extern crate orbital;

use orbital::{BmpFile, Color, EventOption, Window};

use std::fs::File;
use std::io::Read;
use std::process::Command;
use std::thread;

use package::Package;

pub mod package;

fn draw(window: &mut Window, packages: &Vec<Box<Package>>, shutdown: &BmpFile, mouse_x: i32, mouse_y: i32){
    window.set(Color::rgba(0, 0, 0, 128));

    let mut x = 0;
    for package in packages.iter() {
        if package.icon.has_data() {
            let y = window.height() as isize - package.icon.height() as isize;

            if mouse_y >= y as i32 && mouse_x >= x && mouse_x < x + package.icon.width() as i32 {
                window.rect(x as i32, y as i32,
                                  package.icon.width() as u32, package.icon.height() as u32,
                                  Color::rgba(128, 128, 128, 128));

                /*
                window.rect(x as i32, y as i32 - 16,
                    package.name.len() as u32 * 8, 16,
                    Color::rgba(0, 0, 0, 128));

                let mut c_x = x;
                for c in package.name.chars() {
                    window.char(c_x as i32, y as i32 - 16,
                              c,
                              Color::rgb(255, 255, 255),
                              self.font.as_ptr() as usize);
                    c_x += 8;
                }
                */
            }

            window.image(x as i32, y as i32,
                        package.icon.width() as u32,
                        package.icon.height() as u32,
                        &package.icon);
            x = x + package.icon.width() as i32;
        }
    }

    if shutdown.has_data() {
        x = window.width() as i32 - shutdown.width() as i32;
        let y = window.height() as isize - shutdown.height() as isize;

        if mouse_y >= y as i32 && mouse_x >= x &&
           mouse_x < x + shutdown.width() as i32 {
            window.rect(x as i32, y as i32,
                              shutdown.width() as u32, shutdown.height() as u32,
                              Color::rgba(128, 128, 128, 128));
        }

        window.image(x as i32, y as i32,
                        shutdown.width() as u32, shutdown.height() as u32,
                        &shutdown);
        x = x + shutdown.width() as i32;
    }

    window.sync();
}

fn main() {
    let mut packages: Vec<Box<Package>> = Vec::new();

    //TODO: Use a directory walk
    match File::open("file:/apps/") {
        Ok(mut file) => {
            let mut string = String::new();
            if let Ok(_) = file.read_to_string(&mut string) {
                for folder in string.lines() {
                    if folder.ends_with('/') {
                        packages.push(Package::from_path(&("file:/apps/".to_string() + &folder)));
                    }
                }
            }
        }
        Err(err) => println!("Failed to open apps: {}", err),
    }
    /*
        for package in packages.iter() {
            let mut accepted = false;
            for accept in package.accepts.iter() {
                if (accept.starts_with('*') &&
                    path.ends_with(&accept.get_slice(Some(1), None))) ||
                   (accept.ends_with('*') &&
                    path.starts_with(&accept.get_slice(None, Some(accept.len() - 1)))) {
                    accepted = true;
                    break;
                }
            }
            if accepted {
                if Command::new(&package.binary).arg(&path).spawn_scheme().is_none() {
                    println!("{}: Failed to launch", package.binary);
                }
                break;
            }
        }
    */

    let shutdown = BmpFile::from_path("file:/ui/actions/system-shutdown.bmp");
    if ! shutdown.has_data() {
        println!("Failed to read shutdown icon");
    }

    let mut window = Window::new(0, 568, 800, 32, "Launcher").unwrap();

    draw(&mut window, &packages, &shutdown, -1, -1);
    'running: loop {
        for event in window.events() {
            println!("{:?}", event.to_option());
            match event.to_option() {
                EventOption::Mouse(mouse_event) => {
                    draw(&mut window, &packages, &shutdown, mouse_event.x, mouse_event.y);

                    if mouse_event.left_button {
                        let mut x = 0;
                        for package in packages.iter() {
                            if package.icon.has_data() {
                                if mouse_event.x >= x && mouse_event.x < x + package.icon.width() as i32 {
                                    if let Err(err) = Command::new(&package.binary).spawn() {
                                        println!("{}: Failed to launch: {}", package.binary, err);
                                    }
                                }
                                x = x + package.icon.width() as i32;
                            }
                        }

                        if shutdown.has_data() {
                            x = window.width() as i32 - shutdown.width() as i32;
                            let y = window.height() as i32 - shutdown.height() as i32;
                            if mouse_event.y >= y && mouse_event.x >= x &&
                               mouse_event.x < x + shutdown.width() as i32 {
                                   File::create("acpi:off");
                            }
                        }
                    }
                },
                EventOption::Quit(_) => break 'running,
                _ => ()
            }
        }

        thread::yield_now();
    }
}
<commit_msg>Do not log events in launcher<commit_after>extern crate orbital;

use orbital::{BmpFile, Color, EventOption, Window};

use std::fs::File;
use std::io::Read;
use std::process::Command;
use std::thread;

use package::Package;

pub mod package;

fn draw(window: &mut Window, packages: &Vec<Box<Package>>, shutdown: &BmpFile, mouse_x: i32, mouse_y: i32){
    window.set(Color::rgba(0, 0, 0, 128));

    let mut x = 0;
    for package in packages.iter() {
        if package.icon.has_data() {
            let y = window.height() as isize - package.icon.height() as isize;

            if mouse_y >= y as i32 && mouse_x >= x && mouse_x < x + package.icon.width() as i32 {
                window.rect(x as i32, y as i32,
                                  package.icon.width() as u32, package.icon.height() as u32,
                                  Color::rgba(128, 128, 128, 128));

                /*
                window.rect(x as i32, y as i32 - 16,
                    package.name.len() as u32 * 8, 16,
                    Color::rgba(0, 0, 0, 128));

                let mut c_x = x;
                for c in package.name.chars() {
                    window.char(c_x as i32, y as i32 - 16,
                              c,
                              Color::rgb(255, 255, 255),
                              self.font.as_ptr() as usize);
                    c_x += 8;
                }
                */
            }

            window.image(x as i32, y as i32,
                        package.icon.width() as u32,
                        package.icon.height() as u32,
                        &package.icon);
            x = x + package.icon.width() as i32;
        }
    }

    if shutdown.has_data() {
        x = window.width() as i32 - shutdown.width() as i32;
        let y = window.height() as isize - shutdown.height() as isize;

        if mouse_y >= y as i32 && mouse_x >= x &&
           mouse_x < x + shutdown.width() as i32 {
            window.rect(x as i32, y as i32,
                              shutdown.width() as u32, shutdown.height() as u32,
                              Color::rgba(128, 128, 128, 128));
        }

        window.image(x as i32, y as i32,
                        shutdown.width() as u32, shutdown.height() as u32,
                        &shutdown);
        x = x + shutdown.width() as i32;
    }

    window.sync();
}

fn main() {
    let mut packages: Vec<Box<Package>> = Vec::new();

    //TODO: Use a directory walk
    match File::open("file:/apps/") {
        Ok(mut file) => {
            let mut string = String::new();
            if let Ok(_) = file.read_to_string(&mut string) {
                for folder in string.lines() {
                    if folder.ends_with('/') {
                        packages.push(Package::from_path(&("file:/apps/".to_string() + &folder)));
                    }
                }
            }
        }
        Err(err) => println!("Failed to open apps: {}", err),
    }
    /*
        for package in packages.iter() {
            let mut accepted = false;
            for accept in package.accepts.iter() {
                if (accept.starts_with('*') &&
                    path.ends_with(&accept.get_slice(Some(1), None))) ||
                   (accept.ends_with('*') &&
                    path.starts_with(&accept.get_slice(None, Some(accept.len() - 1)))) {
                    accepted = true;
                    break;
                }
            }
            if accepted {
                if Command::new(&package.binary).arg(&path).spawn_scheme().is_none() {
                    println!("{}: Failed to launch", package.binary);
                }
                break;
            }
        }
    */

    let shutdown = BmpFile::from_path("file:/ui/actions/system-shutdown.bmp");
    if ! shutdown.has_data() {
        println!("Failed to read shutdown icon");
    }

    let mut window = Window::new(0, 568, 800, 32, "Launcher").unwrap();

    draw(&mut window, &packages, &shutdown, -1, -1);
    'running: loop {
        for event in window.events() {
            match event.to_option() {
                EventOption::Mouse(mouse_event) => {
                    draw(&mut window, &packages, &shutdown, mouse_event.x, mouse_event.y);

                    if mouse_event.left_button {
                        let mut x = 0;
                        for package in packages.iter() {
                            if package.icon.has_data() {
                                if mouse_event.x >= x && mouse_event.x < x + package.icon.width() as i32 {
                                    if let Err(err) = Command::new(&package.binary).spawn() {
                                        println!("{}: Failed to launch: {}", package.binary, err);
                                    }
                                }
                                x = x + package.icon.width() as i32;
                            }
                        }

                        if shutdown.has_data() {
                            x = window.width() as i32 - shutdown.width() as i32;
                            let y = window.height() as i32 - shutdown.height() as i32;
                            if mouse_event.y >= y && mouse_event.x >= x &&
                               mouse_event.x < x + shutdown.width() as i32 {
                                   File::create("acpi:off");
                            }
                        }
                    }
                },
                EventOption::Quit(_) => break 'running,
                _ => ()
            }
        }

        thread::yield_now();
    }
}
<|endoftext|>


<commit_before>use super::{super::monitor, backend, device, proxy::Proxy, runner, window};
use crate::dpi::{PhysicalSize, Size};
use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent};
use crate::event_loop::ControlFlow;
use crate::window::{Theme, WindowId};
use std::clone::Clone;
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};

pub struct WindowTarget<T: 'static> {
    pub(crate) runner: runner::Shared<T>,
}

impl<T> Clone for WindowTarget<T> {
    fn clone(&self) -> Self {
        WindowTarget {
            runner: self.runner.clone(),
        }
    }
}

impl<T> WindowTarget<T> {
    pub fn new() -> Self {
        WindowTarget {
            runner: runner::Shared::new(),
        }
    }

    pub fn proxy(&self) -> Proxy<T> {
        Proxy::new(self.runner.clone())
    }

    pub fn run(&self, event_handler: Box<dyn FnMut(Event<'static, T>, &mut ControlFlow)>) {
        self.runner.set_listener(event_handler);
    }

    pub fn generate_id(&self) -> window::Id {
        window::Id(self.runner.generate_id())
    }

    pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) {
        let runner = self.runner.clone();
        canvas.set_attribute("data-raw-handle", &id.0.to_string());

        canvas.on_blur(move || {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Focused(false),
            });
        });

        let runner = self.runner.clone();
        canvas.on_focus(move || {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Focused(true),
            });
        });

        let runner = self.runner.clone();
        canvas.on_keyboard_press(move |scancode, virtual_keycode, modifiers| {
            #[allow(deprecated)]
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::KeyboardInput {
                    device_id: DeviceId(unsafe { device::Id::dummy() }),
                    input: KeyboardInput {
                        scancode,
                        state: ElementState::Pressed,
                        virtual_keycode,
                        modifiers,
                    },
                    is_synthetic: false,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_keyboard_release(move |scancode, virtual_keycode, modifiers| {
            #[allow(deprecated)]
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::KeyboardInput {
                    device_id: DeviceId(unsafe { device::Id::dummy() }),
                    input: KeyboardInput {
                        scancode,
                        state: ElementState::Released,
                        virtual_keycode,
                        modifiers,
                    },
                    is_synthetic: false,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_received_character(move |char_code| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::ReceivedCharacter(char_code),
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_leave(move |pointer_id| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorLeft {
                    device_id: DeviceId(device::Id(pointer_id)),
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_enter(move |pointer_id| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorEntered {
                    device_id: DeviceId(device::Id(pointer_id)),
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_move(move |pointer_id, position, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorMoved {
                    device_id: DeviceId(device::Id(pointer_id)),
                    position,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_mouse_press(move |pointer_id, position, button, modifiers| {
            // A mouse down event may come in without any prior CursorMoved events,
            // therefore we should send a CursorMoved event to make sure that the
            // user code has the correct cursor position.
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorMoved {
                    device_id: DeviceId(device::Id(pointer_id)),
                    position,
                    modifiers,
                },
            });
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::MouseInput {
                    device_id: DeviceId(device::Id(pointer_id)),
                    state: ElementState::Pressed,
                    button,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_mouse_release(move |pointer_id, button, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::MouseInput {
                    device_id: DeviceId(device::Id(pointer_id)),
                    state: ElementState::Released,
                    button,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_mouse_wheel(move |pointer_id, delta, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::MouseWheel {
                    device_id: DeviceId(device::Id(pointer_id)),
                    delta,
                    phase: TouchPhase::Moved,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        let raw = canvas.raw().clone();

        // The size to restore to after exiting fullscreen.
        let mut intended_size = PhysicalSize {
            width: raw.width() as u32,
            height: raw.height() as u32,
        };
        canvas.on_fullscreen_change(move || {
            // If the canvas is marked as fullscreen, it is moving *into* fullscreen
            // If it is not, it is moving *out of* fullscreen
            let new_size = if backend::is_fullscreen(&raw) {
                intended_size = PhysicalSize {
                    width: raw.width() as u32,
                    height: raw.height() as u32,
                };

                backend::window_size().to_physical(backend::scale_factor())
            } else {
                intended_size
            };

            backend::set_canvas_size(&raw, Size::Physical(new_size));
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Resized(new_size),
            });
            runner.request_redraw(WindowId(id));
        });

        let runner = self.runner.clone();
        canvas.on_dark_mode(move |is_dark_mode| {
            let theme = if is_dark_mode {
                Theme::Dark
            } else {
                Theme::Light
            };
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::ThemeChanged(theme),
            });
        });
    }

    pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> {
        VecDeque::new().into_iter()
    }

    pub fn primary_monitor(&self) -> monitor::Handle {
        monitor::Handle
    }
}
<commit_msg>Use send_events instead of send_event in web backend (#1681)<commit_after>use super::{super::monitor, backend, device, proxy::Proxy, runner, window};
use crate::dpi::{PhysicalSize, Size};
use crate::event::{DeviceId, ElementState, Event, KeyboardInput, TouchPhase, WindowEvent};
use crate::event_loop::ControlFlow;
use crate::window::{Theme, WindowId};
use std::clone::Clone;
use std::collections::{vec_deque::IntoIter as VecDequeIter, VecDeque};

pub struct WindowTarget<T: 'static> {
    pub(crate) runner: runner::Shared<T>,
}

impl<T> Clone for WindowTarget<T> {
    fn clone(&self) -> Self {
        WindowTarget {
            runner: self.runner.clone(),
        }
    }
}

impl<T> WindowTarget<T> {
    pub fn new() -> Self {
        WindowTarget {
            runner: runner::Shared::new(),
        }
    }

    pub fn proxy(&self) -> Proxy<T> {
        Proxy::new(self.runner.clone())
    }

    pub fn run(&self, event_handler: Box<dyn FnMut(Event<'static, T>, &mut ControlFlow)>) {
        self.runner.set_listener(event_handler);
    }

    pub fn generate_id(&self) -> window::Id {
        window::Id(self.runner.generate_id())
    }

    pub fn register(&self, canvas: &mut backend::Canvas, id: window::Id) {
        let runner = self.runner.clone();
        canvas.set_attribute("data-raw-handle", &id.0.to_string());

        canvas.on_blur(move || {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Focused(false),
            });
        });

        let runner = self.runner.clone();
        canvas.on_focus(move || {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Focused(true),
            });
        });

        let runner = self.runner.clone();
        canvas.on_keyboard_press(move |scancode, virtual_keycode, modifiers| {
            #[allow(deprecated)]
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::KeyboardInput {
                    device_id: DeviceId(unsafe { device::Id::dummy() }),
                    input: KeyboardInput {
                        scancode,
                        state: ElementState::Pressed,
                        virtual_keycode,
                        modifiers,
                    },
                    is_synthetic: false,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_keyboard_release(move |scancode, virtual_keycode, modifiers| {
            #[allow(deprecated)]
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::KeyboardInput {
                    device_id: DeviceId(unsafe { device::Id::dummy() }),
                    input: KeyboardInput {
                        scancode,
                        state: ElementState::Released,
                        virtual_keycode,
                        modifiers,
                    },
                    is_synthetic: false,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_received_character(move |char_code| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::ReceivedCharacter(char_code),
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_leave(move |pointer_id| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorLeft {
                    device_id: DeviceId(device::Id(pointer_id)),
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_enter(move |pointer_id| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorEntered {
                    device_id: DeviceId(device::Id(pointer_id)),
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_cursor_move(move |pointer_id, position, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::CursorMoved {
                    device_id: DeviceId(device::Id(pointer_id)),
                    position,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_mouse_press(move |pointer_id, position, button, modifiers| {
            // A mouse down event may come in without any prior CursorMoved events,
            // therefore we should send a CursorMoved event to make sure that the
            // user code has the correct cursor position.
            runner.send_events(
                std::iter::once(Event::WindowEvent {
                    window_id: WindowId(id),
                    event: WindowEvent::CursorMoved {
                        device_id: DeviceId(device::Id(pointer_id)),
                        position,
                        modifiers,
                    },
                })
                .chain(std::iter::once(Event::WindowEvent {
                    window_id: WindowId(id),
                    event: WindowEvent::MouseInput {
                        device_id: DeviceId(device::Id(pointer_id)),
                        state: ElementState::Pressed,
                        button,
                        modifiers,
                    },
                })),
            );
        });

        let runner = self.runner.clone();
        canvas.on_mouse_release(move |pointer_id, button, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::MouseInput {
                    device_id: DeviceId(device::Id(pointer_id)),
                    state: ElementState::Released,
                    button,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        canvas.on_mouse_wheel(move |pointer_id, delta, modifiers| {
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::MouseWheel {
                    device_id: DeviceId(device::Id(pointer_id)),
                    delta,
                    phase: TouchPhase::Moved,
                    modifiers,
                },
            });
        });

        let runner = self.runner.clone();
        let raw = canvas.raw().clone();

        // The size to restore to after exiting fullscreen.
        let mut intended_size = PhysicalSize {
            width: raw.width() as u32,
            height: raw.height() as u32,
        };
        canvas.on_fullscreen_change(move || {
            // If the canvas is marked as fullscreen, it is moving *into* fullscreen
            // If it is not, it is moving *out of* fullscreen
            let new_size = if backend::is_fullscreen(&raw) {
                intended_size = PhysicalSize {
                    width: raw.width() as u32,
                    height: raw.height() as u32,
                };

                backend::window_size().to_physical(backend::scale_factor())
            } else {
                intended_size
            };

            backend::set_canvas_size(&raw, Size::Physical(new_size));
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::Resized(new_size),
            });
            runner.request_redraw(WindowId(id));
        });

        let runner = self.runner.clone();
        canvas.on_dark_mode(move |is_dark_mode| {
            let theme = if is_dark_mode {
                Theme::Dark
            } else {
                Theme::Light
            };
            runner.send_event(Event::WindowEvent {
                window_id: WindowId(id),
                event: WindowEvent::ThemeChanged(theme),
            });
        });
    }

    pub fn available_monitors(&self) -> VecDequeIter<monitor::Handle> {
        VecDeque::new().into_iter()
    }

    pub fn primary_monitor(&self) -> monitor::Handle {
        monitor::Handle
    }
}
<|endoftext|>


<commit_before>use nn::{Module, ModuleStruct, ModDelegate, ModIntf, Parameter};
use autograd::Variable;
use std::marker::PhantomData;

#[builder(pattern="owned")]
#[derive(Builder)]
pub struct LinearArgs<T: Default> {
    in_features: u32,
    out_features: u32,
    #[builder(default="true")]
    bias: bool,
    #[builder(default="PhantomData")]
    phantom: PhantomData<T>,
}
impl<T: Default> LinearArgsBuilder<T> {
    pub fn done(self) -> Linear<T> {
        let args = self.build().unwrap();
        Linear::new(args)
    }
}

#[derive(ModParse)]
pub struct Linear<T> {
    delegate: Module<T>,
    #[ignore]
    in_features: u32,
    #[ignore]
    out_features: u32,
    weight: Parameter<T>,
    bias: Option<Parameter<T>>,
}

impl<T: Default> Linear<T> {
    pub fn build(in_features: u32, out_features: u32) -> LinearArgsBuilder<T> {
        LinearArgsBuilder::default()
            .in_features(in_features)
            .out_features(out_features)
    }
    pub fn new(args: LinearArgs<T>) -> Linear<T> {
        let mut t = Linear {
            delegate: Module::new(),
            in_features: args.in_features,
            out_features: args.out_features,
            weight: Parameter::default(),
            bias: None,
        };
        t.init_module();
        t
    }
}
impl_mod_delegate!(Linear);

impl<T: Default> ModIntf<T> for Linear<T> {
    fn forward(&mut self, input: &mut Variable<T>) -> Variable<T> {
        panic!("implement");
        input.clone()
    }
}
<commit_msg>call functional linear instead of no-op<commit_after>use nn::{Module, ModuleStruct, ModDelegate, ModIntf, Parameter};
use nn::functional as F;
use autograd::Variable;
use std::marker::PhantomData;

#[builder(pattern="owned")]
#[derive(Builder)]
pub struct LinearArgs<T: Default> {
    in_features: u32,
    out_features: u32,
    #[builder(default="true")]
    bias: bool,
    #[builder(default="PhantomData")]
    phantom: PhantomData<T>,
}
impl<T: Default> LinearArgsBuilder<T> {
    pub fn done(self) -> Linear<T> {
        let args = self.build().unwrap();
        Linear::new(args)
    }
}

#[derive(ModParse)]
pub struct Linear<T> {
    delegate: Module<T>,
    #[ignore]
    in_features: u32,
    #[ignore]
    out_features: u32,
    weight: Parameter<T>,
    bias: Option<Parameter<T>>,
}

impl<T: Default> Linear<T> {
    pub fn build(in_features: u32, out_features: u32) -> LinearArgsBuilder<T> {
        LinearArgsBuilder::default()
            .in_features(in_features)
            .out_features(out_features)
    }
    pub fn new(args: LinearArgs<T>) -> Linear<T> {
        let mut t = Linear {
            delegate: Module::new(),
            in_features: args.in_features,
            out_features: args.out_features,
            weight: Parameter::default(),
            bias: None,
        };
        t.init_module();
        t
    }
}
impl_mod_delegate!(Linear);

impl<T: Default> ModIntf<T> for Linear<T> {
    fn forward(&mut self, input: &mut Variable<T>) -> Variable<T> {
        if let Some(ref mut bias) = self.bias {
            F::linear(&input, &mut self.weight.v, Some(&mut bias.v))
        } else {
            F::linear(&input, &mut self.weight.v, None)
        }
    }
}
<|endoftext|>


<commit_before>use std::collections::{HashMap, hash_map};
use tensor::Tensor;
use autograd::Variable;
use std::vec::IntoIter;
use nn;

// placeholder
struct TorchBackend {}

pub trait ModuleStruct {
    fn init_module(self) -> Self;
}

pub struct Module<T: Copy> {
    pub _name: String,
    pub training: bool,
    _backend: TorchBackend,

    _buffers: HashMap<String, Tensor<T>>,
    //	_backward_hooks:
    //	_forward_hooks:
    _params: HashMap<String, *mut nn::Parameter<T>>,
    _modules: HashMap<String, *mut Module<T>>,
}
pub struct PtrIterMut<'a, T: 'a> {
    //mod_iter: linked_hash_map::IterMut<'a, &'a str, *mut T>,
    mod_iter: hash_map::IterMut<'a, String, *mut T>,
}
pub struct PtrIter<'a, T: 'a> {
    //mod_iter: linked_hash_map::IterMut<'a, &'a str, *mut T>,
    mod_iter: hash_map::Iter<'a, String, *mut T>,
}

impl<'a, T> Iterator for PtrIter<'a, T> {
    type Item = (&'a str, &'a T);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((name, t)) = self.mod_iter.next() {
            Some((name, unsafe { &**t as &T }))
        } else {
            None
        }
    }
}

impl<'a, T> Iterator for PtrIterMut<'a, T> {
    type Item = (&'a String, &'a mut T);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((name, t)) = self.mod_iter.next() {
            Some((name, unsafe { &mut **t as &mut T }))
        } else {
            None
        }
    }
}

pub struct ParamIter<'a, T: 'a + Copy> {
    pub modules: Vec<*mut Module<T>>,
    pub mod_iter: IntoIter<*mut Module<T>>,
    pub iter: PtrIterMut<'a, nn::Parameter<T>>,
}
fn mod_accum<T: Copy>(module: &mut Module<T>, arg: &mut Vec<*mut Module<T>>) {
    arg.push((module));
}
impl<'a, T: 'a + Copy> ParamIter<'a, T> {
    pub fn new(root: &'a mut Module<T>) -> Self {
        let mut mods = Vec::new();
        root.apply_arg(&mut mods, mod_accum);
        ParamIter {
            modules: mods.clone(),
            mod_iter: mods.into_iter(),
            iter: root.params_iter_mut(),
        }
    }
}

impl<'a, T: Copy> Iterator for ParamIter<'a, T> {
    type Item = &'a mut nn::Parameter<T>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((_, t)) = self.iter.next() {
            Some(t)
        } else if let Some(modulep) = self.mod_iter.next() {
            let mut module = unsafe { &mut *modulep as &mut Module<T> };
            self.iter = module.params_iter_mut();
            self.next()
        } else {
            None
        }
    }
}

impl<'a, T: Copy> Clone for ParamIter<'a, T> {
    fn clone(&self) -> Self {
        let mut new_mod_list = self.modules.clone();
        let param_iter = unsafe { &mut *new_mod_list[0] }.params_iter_mut();
        ParamIter {
            modules: new_mod_list,
            mod_iter: self.modules.clone().into_iter(),
            iter: param_iter,
        }
    }
}

impl<T: Copy> Module<T> {
    pub fn new() -> Module<T> {
        Module {
            _name: String::from(""),
            _backend: TorchBackend {},
            _buffers: HashMap::new(),
            _params: HashMap::new(),
            _modules: HashMap::new(),
            training: true,
        }
    }
    #[inline]
    fn as_mut_ptr(&mut self) -> *mut Module<T> {
        self as *mut Module<T>
    }
    pub fn add_module(&mut self, module: &mut ModIntf<T>) {
        let m = module.delegate();
        self._modules.insert(m._name.clone(), m.as_mut_ptr());

    }
    pub fn add_param(&mut self, name: &str, param: &mut nn::Parameter<T>) {
        let s = String::from(name);
        self._params.insert(s, param.as_mut_ptr());

    }
    pub fn modules_iter_mut(&mut self) -> PtrIterMut<Module<T>> {
        PtrIterMut { mod_iter: self._modules.iter_mut() }
    }
    pub fn modules_iter(&mut self) -> PtrIter<Module<T>> {
        PtrIter { mod_iter: self._modules.iter() }
    }
    pub fn params_iter_mut(&mut self) -> PtrIterMut<nn::Parameter<T>> {
        PtrIterMut { mod_iter: self._params.iter_mut() }
    }
    pub fn register_buffer(&mut self, name: &str, tensor: &mut Tensor<T>) {
        self._buffers.insert(String::from(name), tensor.clone());
    }
    pub fn parameters(&mut self) -> ParamIter<T> {
        ParamIter::new(self)
    }
    fn _apply(&mut self, callback: fn(&mut Tensor<T>)) {
        for (_, module) in self.modules_iter_mut() {
            module._apply(callback)
        }
        for (_, param) in self.params_iter_mut() {
            param.apply(callback)
            /*
			if let Some(g) = p._grad {
					callback(g.data)
			}
			*/
            /* see also _buffers */
        }
    }
    pub fn apply(&mut self, callback: fn(&mut Self)) {
        for (_, module) in self.modules_iter_mut() {
            module.apply(callback)
        }
        callback(self)
    }
    fn apply_arg<Ta>(&mut self, arg: &mut Ta, callback: fn(&mut Self, &mut Ta)) {
        for (_, module) in self.modules_iter_mut() {
            module.apply_arg(arg, callback)
        }
        callback(self, arg)
    }
    pub fn repr(&mut self) -> String {
        let mut tmpstr = format!("{} (\n", self._name);
        for (key, module) in self.modules_iter_mut() {
            let modstr = module.repr();
            let modstr = format!("  {}", modstr);
            tmpstr = format!("{} ({}): {}\n", tmpstr, key, modstr);
        }
        tmpstr = format!("{})", tmpstr);
        tmpstr
    }
    pub fn eval(&mut self) {
        self.train(false)
    }
    fn train(&mut self, mode: bool) {
        self.training = mode;
        for (_, module) in self.modules_iter_mut() {
            module.train(mode)
        }

    }
}

pub trait ModDelegate<T: Copy> {
    fn delegate(&mut self) -> &mut Module<T>;
}

pub trait ModIntf<T: Copy>: ModDelegate<T> {
    fn forward(&mut self, input: &mut Variable<T>) -> Variable<T>;
    fn f(&mut self, input: &mut Variable<T>) -> Variable<T> {
        {
            let mut m = self.delegate();
            // do pre-forward hooks
        }
        let output = self.forward(input);
        {
            let mut m = self.delegate();
            // do post-forward hooks
        }
        output
    }
    fn train(&mut self) {
        self.delegate().train(true)
    }
    fn eval(&mut self) {
        self.delegate().train(false)
    }
}

pub trait ModIntfV<T: Copy>: ModDelegate<T> {
    fn forwardv(&mut self, input: &mut Vec<Variable<T>>) -> Vec<Variable<T>>;
    fn fv(&mut self, input: &mut Vec<Variable<T>>) -> Vec<Variable<T>> {
        {
            let mut m = self.delegate();
            // do pre-forward hooks
        }
        let output = self.forwardv(input);
        {
            let mut m = self.delegate();
            // do post-forward hooks
        }
        output
    }
}
<commit_msg>go through serious contortions to avoid life time resolution conflicts when holding persistent references to the module graph<commit_after>use std::collections::{HashMap, hash_map};
use tensor::Tensor;
use autograd::Variable;
use std::vec::IntoIter;
use std::ops::{Deref, DerefMut};
use std::marker::PhantomData;
use nn;

pub trait ModuleStruct {
    fn init_module(self) -> Self;
}
pub struct ModRefMut<'a, T: 'a + ?Sized> {
    value: *mut T,
    phantom: PhantomData<&'a T>,
}

impl<'a, T> ModRefMut<'a, T> {
    pub fn new(value: *mut T) -> Self {
        ModRefMut {
            value: value,
            phantom: PhantomData,
        }
    }
}

impl<'a, T> From<&'a mut T> for ModRefMut<'a, T> {
    fn from(value: &mut T) -> Self {
        ModRefMut::new(value as *mut T)
    }
}
impl<'a, T> From<*mut T> for ModRefMut<'a, T> {
    fn from(value: *mut T) -> Self {
        ModRefMut::new(value)
    }
}

impl<'a, T> Deref for ModRefMut<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { &*self.value as &T }
    }
}
impl<'a, T> DerefMut for ModRefMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.value as &mut T }
    }
}

pub struct Module<T: Copy> {
    pub _name: String,
    pub training: bool,
    //_backend: TorchBackend,
    //	_backward_hooks:
    //	_forward_hooks:
    _buffers: HashMap<String, Tensor<T>>,
    _params: HashMap<String, *mut nn::Parameter<T>>,
    _modules: HashMap<String, *mut Module<T>>,
}
pub struct PtrIterMut<'a, T: 'a> {
    //mod_iter: linked_hash_map::IterMut<'a, &'a str, *mut T>,
    mod_iter: hash_map::IterMut<'a, String, *mut T>,
}
pub struct PtrIter<'a, T: 'a> {
    //mod_iter: linked_hash_map::IterMut<'a, &'a str, *mut T>,
    mod_iter: hash_map::Iter<'a, String, *mut T>,
}

impl<'a, T> Iterator for PtrIter<'a, T> {
    type Item = (&'a str, &'a T);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((name, t)) = self.mod_iter.next() {
            Some((name, unsafe { &**t as &T }))
        } else {
            None
        }
    }
}

impl<'a, T> Iterator for PtrIterMut<'a, T> {
    type Item = (&'a String, &'a mut T);
    fn next(&mut self) -> Option<Self::Item> {
        if let Some((name, t)) = self.mod_iter.next() {
            Some((name, unsafe { &mut **t as &mut T }))
        } else {
            None
        }
    }
}

pub struct ParamIter<T: Copy> {
    pub modules: Vec<*mut Module<T>>,
    pub mod_iter: IntoIter<*mut Module<T>>,
    pub iter: Box<Iterator<Item = *mut nn::Parameter<T>>>,
}
fn mod_accum<T: Copy>(module: &mut Module<T>, arg: &mut Vec<*mut Module<T>>) {
    arg.push((module));
}
impl<'a, T: 'static + Copy> ParamIter<T> {
    pub fn new(root: &'a mut Module<T>) -> Self {
        let mut mods = Vec::new();
        root.apply_arg(&mut mods, mod_accum);
        let mut module = unsafe { &mut *mods[0] as &mut Module<T> };
        ParamIter {
            modules: mods.clone(),
            mod_iter: mods.into_iter(),
            iter: Box::new(module._params.iter_mut().map(|(s, d)| *d)),
        }
    }
}

impl<T: Copy + 'static> Iterator for ParamIter<T> {
    type Item = ModRefMut<'static, nn::Parameter<T>>;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(t) = self.iter.next() {
            Some(ModRefMut::new(t))
        } else if let Some(modulep) = self.mod_iter.next() {
            let mut module = unsafe { &mut *modulep as &mut Module<T> };
            self.iter = Box::new(module._params.iter_mut().map(|(s, d)| *d));
            self.next()
        } else {
            None
        }
    }
}

impl<T: Copy + 'static> Clone for Box<ParamIter<T>> {
    fn clone(&self) -> Self {
        let mut new_mod_list = self.modules.clone();
        let param_iter = Box::new(unsafe { &mut *new_mod_list[0] }
                                      ._params
                                      .iter_mut()
                                      .map(|(s, d)| *d));
        Box::new(ParamIter {
                     modules: new_mod_list,
                     mod_iter: self.modules.clone().into_iter(),
                     iter: param_iter,
                 })
    }
}

impl<T: Copy> Module<T> {
    pub fn new() -> Module<T> {
        Module {
            _name: String::from(""),
            _buffers: HashMap::new(),
            _params: HashMap::new(),
            _modules: HashMap::new(),
            training: true,
        }
    }
    #[inline]
    fn as_mut_ptr(&mut self) -> *mut Module<T> {
        self as *mut Module<T>
    }
    pub fn add_module(&mut self, module: &mut ModIntf<T>) {
        let m = module.delegate();
        self._modules.insert(m._name.clone(), m.as_mut_ptr());

    }
    pub fn add_param(&mut self, name: &str, param: &mut nn::Parameter<T>) {
        let s = String::from(name);
        self._params.insert(s, param.as_mut_ptr());

    }
    pub fn modules_iter_mut(&mut self) -> PtrIterMut<Module<T>> {
        PtrIterMut { mod_iter: self._modules.iter_mut() }
    }
    pub fn modules_iter(&mut self) -> PtrIter<Module<T>> {
        PtrIter { mod_iter: self._modules.iter() }
    }
    pub fn params_iter_mut(&mut self) -> PtrIterMut<nn::Parameter<T>> {
        PtrIterMut { mod_iter: self._params.iter_mut() }
    }
    pub fn register_buffer(&mut self, name: &str, tensor: &mut Tensor<T>) {
        self._buffers.insert(String::from(name), tensor.clone());
    }
    pub fn parameters(&mut self) -> Box<Iterator<Item = ModRefMut<'static, nn::Parameter<T>>>> {
        Box::new(ParamIter::new(self))
    }
    pub fn as_ref_mut(&mut self) -> ModRefMut<'static, Module<T>> {
        ModRefMut::new(self as *mut Module<T>)
    }
    fn _apply(&mut self, callback: fn(&mut Tensor<T>)) {
        for (_, module) in self.modules_iter_mut() {
            module._apply(callback)
        }
        for (_, param) in self.params_iter_mut() {
            param.apply(callback)
            /*
			if let Some(g) = p._grad {
					callback(g.data)
			}
			*/
            /* see also _buffers */
        }
    }
    pub fn apply(&mut self, callback: fn(&mut Self)) {
        for (_, module) in self.modules_iter_mut() {
            module.apply(callback)
        }
        callback(self)
    }
    fn apply_arg<Ta>(&mut self, arg: &mut Ta, callback: fn(&mut Self, &mut Ta)) {
        for (_, module) in self.modules_iter_mut() {
            module.apply_arg(arg, callback)
        }
        callback(self, arg)
    }
    pub fn repr(&mut self) -> String {
        let mut tmpstr = format!("{} (\n", self._name);
        for (key, module) in self.modules_iter_mut() {
            let modstr = module.repr();
            let modstr = format!("  {}", modstr);
            tmpstr = format!("{} ({}): {}\n", tmpstr, key, modstr);
        }
        tmpstr = format!("{})", tmpstr);
        tmpstr
    }
    pub fn eval(&mut self) {
        self.train(false)
    }
    fn train(&mut self, mode: bool) {
        self.training = mode;
        for (_, module) in self.modules_iter_mut() {
            module.train(mode)
        }

    }
}

pub trait ModDelegate<T: Copy> {
    fn delegate(&mut self) -> &mut Module<T>;
}

pub trait ModIntf<T: Copy>: ModDelegate<T> {
    fn forward(&mut self, input: &mut Variable<T>) -> Variable<T>;
    fn f(&mut self, input: &mut Variable<T>) -> Variable<T> {
        {
            let mut m = self.delegate();
            // do pre-forward hooks
        }
        let output = self.forward(input);
        {
            let mut m = self.delegate();
            // do post-forward hooks
        }
        output
    }
    fn train(&mut self) {
        self.delegate().train(true)
    }
    fn eval(&mut self) {
        self.delegate().train(false)
    }
    fn parameters(&mut self) -> Box<Iterator<Item = ModRefMut<'static, nn::Parameter<T>>>> {
        self.delegate().parameters()
    }
}

pub trait ModIntfV<T: Copy>: ModDelegate<T> {
    fn forwardv(&mut self, input: &mut Vec<Variable<T>>) -> Vec<Variable<T>>;
    fn fv(&mut self, input: &mut Vec<Variable<T>>) -> Vec<Variable<T>> {
        {
            let mut m = self.delegate();
            // do pre-forward hooks
        }
        let output = self.forwardv(input);
        {
            let mut m = self.delegate();
            // do post-forward hooks
        }
        output
    }
}
<|endoftext|>


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

use std::fmt;

use ra_ap_hir::{self as hir, HasVisibility};
use ra_ap_ide_db::RootDatabase;

#[derive(Clone, PartialEq, Debug)]
pub enum NodeVisibility {
    Crate,
    Module(String),
    Private,
    Public,
    Super,
}

impl<'a> NodeVisibility {
    pub fn new(hir: hir::ModuleDef, db: &RootDatabase) -> Self {
        let visibility = hir.visibility(db);

        let parent_module = match hir.module(db) {
            Some(module) => module,
            None => return Self::Public,
        };

        let grandparent_module = parent_module.parent(db);
        let krate_module = parent_module.krate().root_module(db);

        match visibility {
            hir::Visibility::Module(visibility_module_id) => {
                let visibility_module = hir::Module::from(visibility_module_id);
                if visibility_module == krate_module {
                    Self::Crate
                } else if Some(visibility_module) == grandparent_module {
                    // For some reason we actually have to match against the grandparent.
                    Self::Super
                } else if visibility_module == parent_module {
                    // For some reason we actually have to match against the parent.
                    Self::Private
                } else {
                    let visibility_module_def = hir::ModuleDef::Module(visibility_module);
                    let path = visibility_module_def.canonical_path(db).unwrap();
                    Self::Module(path)
                }
            }
            hir::Visibility::Public => Self::Public,
        }
    }
}

impl fmt::Display for NodeVisibility {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NodeVisibility::Crate => write!(f, "pub(crate)"),
            NodeVisibility::Module(path) => write!(f, "pub(in crate::{})", path),
            NodeVisibility::Private => write!(f, "pub(self)"),
            NodeVisibility::Public => write!(f, "pub"),
            NodeVisibility::Super => write!(f, "pub(super)"),
        }
    }
}
<commit_msg>Fix clippy warning<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use std::fmt;

use ra_ap_hir::{self as hir, HasVisibility};
use ra_ap_ide_db::RootDatabase;

#[derive(Clone, PartialEq, Debug)]
pub enum NodeVisibility {
    Crate,
    Module(String),
    Private,
    Public,
    Super,
}

impl NodeVisibility {
    pub fn new(hir: hir::ModuleDef, db: &RootDatabase) -> Self {
        let visibility = hir.visibility(db);

        let parent_module = match hir.module(db) {
            Some(module) => module,
            None => return Self::Public,
        };

        let grandparent_module = parent_module.parent(db);
        let krate_module = parent_module.krate().root_module(db);

        match visibility {
            hir::Visibility::Module(visibility_module_id) => {
                let visibility_module = hir::Module::from(visibility_module_id);
                if visibility_module == krate_module {
                    Self::Crate
                } else if Some(visibility_module) == grandparent_module {
                    // For some reason we actually have to match against the grandparent.
                    Self::Super
                } else if visibility_module == parent_module {
                    // For some reason we actually have to match against the parent.
                    Self::Private
                } else {
                    let visibility_module_def = hir::ModuleDef::Module(visibility_module);
                    let path = visibility_module_def.canonical_path(db).unwrap();
                    Self::Module(path)
                }
            }
            hir::Visibility::Public => Self::Public,
        }
    }
}

impl fmt::Display for NodeVisibility {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            NodeVisibility::Crate => write!(f, "pub(crate)"),
            NodeVisibility::Module(path) => write!(f, "pub(in crate::{})", path),
            NodeVisibility::Private => write!(f, "pub(self)"),
            NodeVisibility::Public => write!(f, "pub"),
            NodeVisibility::Super => write!(f, "pub(super)"),
        }
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]

//! A 3dsMax / Blender style camera that orbits about a target position

use vecmath::{ Vector3, vec3_add, vec3_scale };
use vecmath::traits::Float;

use quaternion;
use quaternion::Quaternion;

use input;
use input::{ GenericEvent, Key, MouseButton };
use input::Button::{ Keyboard, Mouse };

use Camera;

bitflags!(
    pub flags Keys: u8 {
        const ZOOM  = 0b00000001,
        const PAN   = 0b00000010,
        const ORBIT = 0b00000100,
    }
);

/// Specifies key bindings and speed modifiers for OrbitZoomCamera
pub struct OrbitZoomCameraSettings<T=f32> {

    /// Which button to press to orbit with mouse
    pub orbit_button: input::Button,

    /// Which button to press to zoom with mouse
    pub zoom_button: input::Button,

    /// Which button to press to pan with mouse
    pub pan_button: input::Button,

    /// Modifier for orbiting speed (arbitrary unit)
    pub orbit_speed: T,

    /// Modifier for pitch speed relative to orbiting speed (arbitrary unit).
    /// To reverse pitch direction, set this to -1.
    pub pitch_speed: T,

    /// Modifier for panning speed (arbitrary unit)
    pub pan_speed: T,

    /// Modifier for zoom speed (arbitrary unit)
    pub zoom_speed: T,
}

impl<T: Float> OrbitZoomCameraSettings<T> {

    /// Clicking and dragging OR two-finger scrolling will orbit camera,
    /// with LShift as pan modifer and LCtrl as zoom modifier
    pub fn default() -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_button : Mouse(MouseButton::Left),
            zoom_button : Keyboard(Key::LCtrl),
            pan_button : Keyboard(Key::LShift),
            orbit_speed: T::from_f32(0.05),
            pitch_speed: T::from_f32(0.1),
            pan_speed: T::from_f32(0.1),
            zoom_speed: T::from_f32(0.1),
        }
    }

    /// Set the button for orbiting
    pub fn orbit_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_button: button,
            .. self
        }
    }

    /// Set the button for zooming
    pub fn zoom_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            zoom_button: button,
            .. self
        }
    }

    /// Set the button for panning
    pub fn pan_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pan_button: button,
            .. self
        }
    }

    /// Set the orbit speed modifier
    pub fn orbit_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_speed: s,
            .. self
        }
    }

    /// Set the pitch speed modifier
    pub fn pitch_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pitch_speed: s,
            .. self
        }
    }

    /// Set the pan speed modifier
    pub fn pan_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pan_speed: s,
            .. self
        }
    }

    /// Set the zoom speed modifier
    pub fn zoom_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            zoom_speed: s,
            .. self
        }
    }
}

/// A 3dsMax / Blender-style camera that orbits around a target point
pub struct OrbitZoomCamera<T=f32> {

    /// origin of camera rotation
    pub target: Vector3<T>,

    /// Rotation of camera
    pub rotation: Quaternion<T>,

    /// Pitch up/down from target
    pub pitch: T,

    /// Yaw left/right from target
    pub yaw: T,

    /// camera distance from target
    pub distance: T,

    /// Settings for the camera
    pub settings: OrbitZoomCameraSettings<T>,

    /// Current keys that are pressed
    keys: Keys,
}

impl<T: Float>
OrbitZoomCamera<T> {

    /// Create a new OrbitZoomCamera targeting the given coordinates
    pub fn new(target: [T; 3], settings: OrbitZoomCameraSettings<T>) -> OrbitZoomCamera<T> {
        OrbitZoomCamera {
            target: target,
            rotation: quaternion::id(),
            distance: T::from_f32(10.0),
            pitch: T::zero(),
            yaw: T::zero(),
            keys: Keys::empty(),
            settings: settings
        }
    }

    /// Return a Camera for the current OrbitZoomCamera configuration
    pub fn camera(&self, _dt: f64) -> Camera<T> {
        let target_to_camera = quaternion::rotate_vector(
            self.rotation,
            [T::zero(), T::zero(), self.distance]
        );
        let mut camera = Camera::new(vec3_add(self.target, target_to_camera));
        camera.set_rotation(self.rotation);
        camera
    }

    /// Initialize the camera configuration, such that next call to camera() gives the correct
    /// camera configuration
    pub fn init(&mut self) {
        self.control_camera(T::zero(), T::zero());
    }

    /// Orbit the camera using the given horizontal and vertical params,
    /// or zoom or pan if the appropriate modifier keys are pressed
    fn control_camera(&mut self, dx: T, dy: T) {

        let _1 = T::one();
        let _0 = T::zero();

        if self.keys.contains(PAN) {

            // Pan target position along plane normal to camera direction
            let dx = dx * self.settings.pan_speed;
            let dy = dy * self.settings.pan_speed;

            let right = quaternion::rotate_vector(self.rotation, [_1, _0, _0]);
            let up = quaternion::rotate_vector(self.rotation, [_0, _1, _0]);
            self.target = vec3_add(
                vec3_add(self.target, vec3_scale(up, dy)),
                vec3_scale(right,dx)
            );

        } else if self.keys.contains(ZOOM) {

            // Zoom to / from target
            self.distance = self.distance + dy * self.settings.zoom_speed;

        } else {

            // Orbit around target
            let dx = dx * self.settings.orbit_speed;
            let dy = dy * self.settings.orbit_speed;

            self.yaw = self.yaw + dx;
            self.pitch = self.pitch + dy*self.settings.pitch_speed;
            self.rotation = quaternion::mul(
                quaternion::axis_angle([_0, _1, _0], self.yaw),
                quaternion::axis_angle([_1, _0, _0], self.pitch)
            );

        }
    }

    /// Respond to scroll and key press/release events
    pub fn event<E: GenericEvent>(&mut self, e: &E) {
        e.mouse_scroll(|dx, dy| {
            let dx = T::from_f64(dx);
            let dy = T::from_f64(dy);
            self.control_camera(dx, dy);
        });

        e.mouse_relative(|dx, dy| {
            let dx = T::from_f64(dx);
            let dy = T::from_f64(dy);
            if self.keys.contains(ORBIT){
                self.control_camera(-dx, dy);
            }
        });

        e.press(|button| {
            match button {
                x if x == self.settings.orbit_button => self.keys.insert(ORBIT),
                x if x == self.settings.pan_button => self.keys.insert(PAN),
                x if x == self.settings.zoom_button => self.keys.insert(ZOOM),
                _ => {}
            }
        });

        e.release(|button| {
            match button {
                x if x == self.settings.orbit_button => self.keys.remove(ORBIT),
                x if x == self.settings.pan_button => self.keys.remove(PAN),
                x if x == self.settings.zoom_button => self.keys.remove(ZOOM),
                _ => {}
            }
        });
    }
}
<commit_msg>added limiting to how much one can zoom in or out Made panning and zooming scaled by distance from target. This allows the user to pan larger distances when scales are large.<commit_after>#![allow(dead_code)]

//! A 3dsMax / Blender style camera that orbits about a target position

use vecmath::{ Vector3, vec3_add, vec3_scale };
use vecmath::traits::Float;

use quaternion;
use quaternion::Quaternion;

use input;
use input::{ GenericEvent, Key, MouseButton };
use input::Button::{ Keyboard, Mouse };

use Camera;

bitflags!(
    pub flags Keys: u8 {
        const ZOOM  = 0b00000001,
        const PAN   = 0b00000010,
        const ORBIT = 0b00000100,
    }
);

/// Specifies key bindings and speed modifiers for OrbitZoomCamera
pub struct OrbitZoomCameraSettings<T=f32> {

    /// Which button to press to orbit with mouse
    pub orbit_button: input::Button,

    /// Which button to press to zoom with mouse
    pub zoom_button: input::Button,

    /// Which button to press to pan with mouse
    pub pan_button: input::Button,

    /// Modifier for orbiting speed (arbitrary unit)
    pub orbit_speed: T,

    /// Modifier for pitch speed relative to orbiting speed (arbitrary unit).
    /// To reverse pitch direction, set this to -1.
    pub pitch_speed: T,

    /// Modifier for panning speed (arbitrary unit)
    pub pan_speed: T,

    /// Modifier for zoom speed (arbitrary unit)
    pub zoom_speed: T,
}

impl<T: Float> OrbitZoomCameraSettings<T> {

    /// Clicking and dragging OR two-finger scrolling will orbit camera,
    /// with LShift as pan modifer and LCtrl as zoom modifier
    pub fn default() -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_button : Mouse(MouseButton::Left),
            zoom_button : Keyboard(Key::LCtrl),
            pan_button : Keyboard(Key::LShift),
            orbit_speed: T::from_f32(0.05),
            pitch_speed: T::from_f32(0.1),
            pan_speed: T::from_f32(0.1),
            zoom_speed: T::from_f32(0.1),
        }
    }

    /// Set the button for orbiting
    pub fn orbit_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_button: button,
            .. self
        }
    }

    /// Set the button for zooming
    pub fn zoom_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            zoom_button: button,
            .. self
        }
    }

    /// Set the button for panning
    pub fn pan_button(self, button: input::Button) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pan_button: button,
            .. self
        }
    }

    /// Set the orbit speed modifier
    pub fn orbit_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            orbit_speed: s,
            .. self
        }
    }

    /// Set the pitch speed modifier
    pub fn pitch_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pitch_speed: s,
            .. self
        }
    }

    /// Set the pan speed modifier
    pub fn pan_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            pan_speed: s,
            .. self
        }
    }

    /// Set the zoom speed modifier
    pub fn zoom_speed(self, s: T) -> OrbitZoomCameraSettings<T> {
        OrbitZoomCameraSettings {
            zoom_speed: s,
            .. self
        }
    }
}

/// A 3dsMax / Blender-style camera that orbits around a target point
pub struct OrbitZoomCamera<T=f32> {

    /// origin of camera rotation
    pub target: Vector3<T>,

    /// Rotation of camera
    pub rotation: Quaternion<T>,

    /// Pitch up/down from target
    pub pitch: T,

    /// Yaw left/right from target
    pub yaw: T,

    /// Camera distance from target
    pub distance: T,

    /// Lower distance limit
    /// Set this to near clipping distance
    pub distance_near_limit: T,

    /// Upper distance limit
    /// Set this to far clipping distance
    pub distance_far_limit: T,

    /// Settings for the camera
    pub settings: OrbitZoomCameraSettings<T>,

    /// Current keys that are pressed
    keys: Keys,
}

impl<T: Float>
OrbitZoomCamera<T> {
    /// Create a new OrbitZoomCamera targeting the given coordinates
    pub fn new(target: [T; 3], settings: OrbitZoomCameraSettings<T>) -> OrbitZoomCamera<T> {
        OrbitZoomCamera {
            target: target,
            rotation: quaternion::id(),
            distance: T::from_f32(10.0),
            distance_near_limit: T::from_f32(0.1),
            distance_far_limit: T::from_f32(1000.0),
            pitch: T::zero(),
            yaw: T::zero(),
            keys: Keys::empty(),
            settings: settings
        }
    }

    /// Return a Camera for the current OrbitZoomCamera configuration
    pub fn camera(&self, _dt: f64) -> Camera<T> {
        let target_to_camera = quaternion::rotate_vector(
            self.rotation,
            [T::zero(), T::zero(), self.distance]
        );
        let mut camera = Camera::new(vec3_add(self.target, target_to_camera));
        camera.set_rotation(self.rotation);
        camera
    }

    /// Initialize the camera configuration, such that next call to camera() gives the correct
    /// camera rotation
    pub fn init(&mut self) {
        self.control_camera(T::zero(), T::zero());
    }

    /// Orbit the camera using the given horizontal and vertical params,
    /// or zoom or pan if the appropriate modifier keys are pressed
    fn control_camera(&mut self, dx: T, dy: T) {

        let _1 = T::one();
        let _0 = T::zero();

        if self.keys.contains(PAN) {

            // Pan target position along plane normal to camera direction
            let dx = dx * self.settings.pan_speed*self.distance;
            let dy = dy * self.settings.pan_speed*self.distance;

            let right = quaternion::rotate_vector(self.rotation, [_1, _0, _0]);
            let up = quaternion::rotate_vector(self.rotation, [_0, _1, _0]);
            self.target = vec3_add(
                vec3_add(self.target, vec3_scale(up, dy)),
                vec3_scale(right,dx)
            );

        } else if self.keys.contains(ZOOM) {

            // Zoom to / from target
            let new_dist = self.distance + dy * self.settings.zoom_speed*self.distance;
            self.distance =
                if new_dist > self.distance_far_limit {
                    self.distance_far_limit
                } else if new_dist < self.distance_near_limit {
                    self.distance_near_limit
                } else {
                    new_dist
                }

        } else {

            // Orbit around target
            let dx = dx * self.settings.orbit_speed;
            let dy = dy * self.settings.orbit_speed;

            self.yaw = self.yaw + dx;
            self.pitch = self.pitch + dy*self.settings.pitch_speed;
            self.rotation = quaternion::mul(
                quaternion::axis_angle([_0, _1, _0], self.yaw),
                quaternion::axis_angle([_1, _0, _0], self.pitch)
            );

        }
    }

    /// Respond to scroll and key press/release events
    pub fn event<E: GenericEvent>(&mut self, e: &E) {
        e.mouse_scroll(|dx, dy| {
            let dx = T::from_f64(dx);
            let dy = T::from_f64(dy);
            self.control_camera(dx, dy);
        });

        e.mouse_relative(|dx, dy| {
            let dx = T::from_f64(dx);
            let dy = T::from_f64(dy);
            if self.keys.contains(ORBIT){
                self.control_camera(-dx, dy);
            }
        });

        e.press(|button| {
            match button {
                x if x == self.settings.orbit_button => self.keys.insert(ORBIT),
                x if x == self.settings.pan_button => self.keys.insert(PAN),
                x if x == self.settings.zoom_button => self.keys.insert(ZOOM),
                _ => {}
            }
        });

        e.release(|button| {
            match button {
                x if x == self.settings.orbit_button => self.keys.remove(ORBIT),
                x if x == self.settings.pan_button => self.keys.remove(PAN),
                x if x == self.settings.zoom_button => self.keys.remove(ZOOM),
                _ => {}
            }
        });
    }
}
<|endoftext|>


<commit_before>#[cfg(any(target_os = "macos", target_os = "linux"))]
mod common;

#[cfg(any(target_os = "macos", target_os = "linux"))]
mod tests {
    const TEST_PLATFORM: &str = "wasm32";

    use super::common::check_request_received_using;
    use std::fs;
    use std::path::PathBuf;

    // to run this test, run it as:
    // cargo test --test test_wasm32 -- --ignored
    //
    #[ignore]
    #[actix_rt::test]
    async fn test_wasm32() {
        let uri = &format!("/{}", TEST_PLATFORM);
        let ipv4 = "127.0.0.1";
        check_request_received_using(uri.into(), &ipv4, |url| {
            // modify html to use the correct url
            let mut app_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
            app_dir.push("tests/test-wasm-app");
            let mut src_html = PathBuf::from(&app_dir);
            src_html.push("test.html");
            let mut dst_html = PathBuf::from(&app_dir);
            dst_html.push("pkg/test.html");
            let old_html = fs::read_to_string(&src_html).expect("failed to read test.html");
            let new_html = old_html.replace("DYNAMIC_URL_TBD", &url);
            fs::write(&dst_html, &new_html).expect("failed to update dst test.html");

            // open browser
            let html_url = url.replace(uri, "/static/wasm/test.html");
            //println!("URL: {}", html_url);
            let status = webbrowser::open(&html_url);

            // check for browser run status
            status.expect("browser open failed");
        })
        .await;
    }
}
<commit_msg>fix linter error for wasm test<commit_after>#[cfg(any(target_os = "macos", target_os = "linux"))]
mod common;

#[cfg(any(target_os = "macos", target_os = "linux"))]
mod tests {
    const TEST_PLATFORM: &str = "wasm32";

    use super::common::check_request_received_using;
    use std::fs;
    use std::path::PathBuf;

    // to run this test, run it as:
    // cargo test --test test_wasm32 -- --ignored
    //
    #[ignore]
    #[actix_rt::test]
    async fn test_wasm32() {
        let uri = &format!("/{}", TEST_PLATFORM);
        let ipv4 = "127.0.0.1";
        check_request_received_using(uri.into(), ipv4, |url| {
            // modify html to use the correct url
            let mut app_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
            app_dir.push("tests/test-wasm-app");
            let mut src_html = PathBuf::from(&app_dir);
            src_html.push("test.html");
            let mut dst_html = PathBuf::from(&app_dir);
            dst_html.push("pkg/test.html");
            let old_html = fs::read_to_string(&src_html).expect("failed to read test.html");
            let new_html = old_html.replace("DYNAMIC_URL_TBD", url);
            fs::write(&dst_html, &new_html).expect("failed to update dst test.html");

            // open browser
            let html_url = url.replace(uri, "/static/wasm/test.html");
            //println!("URL: {}", html_url);
            let status = webbrowser::open(&html_url);

            // check for browser run status
            status.expect("browser open failed");
        })
        .await;
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 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.

fn main() {
    let x: Option<&[u8]> = Some("foo").map(std::mem::transmute);
    //~^ ERROR: mismatched types
}
<commit_msg>Fix compile fail tests<commit_after>// Copyright 2014 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.

fn main() {
    let x: Option<&[u8]> = Some("foo").map(std::mem::transmute);
    //~^ ERROR: is not implemented for the type
}
<|endoftext|>