<commit_before>/*
 * Copyright (C) 2017  Sebastian Wiesner <swiesner@lunaryorn.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#![deny(warnings)]

#[macro_use]
extern crate clap;
extern crate atty;
extern crate rand;
extern crate ansi_term;
extern crate xkpwgen;

use ansi_term::Colour;
use ansi_term::Style;
use clap::{App, AppSettings, Arg};
use xkpwgen::generate_password;
use xkpwgen::wordlist::builtin_words;

macro_rules! license {
    () => {
    "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."
    }
}

arg_enum! {
    enum YesNoAuto {
        Yes,
        No,
        Auto
    }
}

fn alternating_styles(colour_setting: YesNoAuto) -> (Style, Style) {
    let enable_colours = match colour_setting {
        YesNoAuto::Auto => atty::is(atty::Stream::Stdout),
        YesNoAuto::Yes => true,
        YesNoAuto::No => false,
    };
    if enable_colours {
        (Style::new().fg(Colour::Cyan), Style::new().fg(Colour::Purple))
    } else {
        (Style::new(), Style::new())
    }
}

fn app() -> App<'static, 'static> {
    app_from_crate!()
        .after_help(concat!("Copyright (C) 2017 Sebastian Wiesner <swiesner@lunaryorn.com>\n\n",
                            license!()))
        .version_message("Print version information")
        .help_message("Print this message")
        .arg(Arg::with_name("colour")
                 .alias("color")
                 .long("colour")
                 .possible_values(&["yes", "no", "auto"])
                 .default_value("auto")
                 .help("Whether to enable or disable coloured output."))
        .arg(Arg::with_name("number")
                 .short("n")
                 .long("number")
                 .default_value("5")
                 .help("The number of passwords to generate at once"))
        .arg(Arg::with_name("length")
                 .short("l")
                 .long("length")
                 .default_value("4")
                 .help("The number of words in each password"))
        .arg(Arg::with_name("words").long("words").help("Print the internal wordlist and exit"))
        .settings(&[AppSettings::ColoredHelp,
                    AppSettings::DontCollapseArgsInUsage,
                    // Don't put flags and options in separate --help groups
                    AppSettings::UnifiedHelpMessage])
}

fn main() {
    let parse_result = app().get_matches_safe();

    match parse_result {
        Ok(matches) => {
            if matches.is_present("words") {
                for word in builtin_words() {
                    println!("{}", word);
                }
            } else {
                let words = builtin_words();
                let password_length = value_t_or_exit!(matches.value_of("length"), usize);
                let number_of_passwords = value_t_or_exit!(matches.value_of("number"), usize);
                let (even, odd) =
                    alternating_styles(value_t_or_exit!(matches, "colour", YesNoAuto));
                for lineno in 0..number_of_passwords {
                    let style = if lineno % 2 == 0 { even } else { odd };
                    let password =
                        generate_password(&mut rand::thread_rng(), &words, password_length, " ");
                    println!("{}", style.paint(password));
                }
            }
        }
        Err(error @ clap::Error { kind: clap::ErrorKind::VersionDisplayed, .. }) => {
            let mut words = builtin_words();
            words.sort_by_key(|w| w.chars().count());
            print!("\n
EFF long wordlist July 2017: {} words (min length {}, max length {})

{}",
                   words.len(),
                   words[0].chars().count(),
                   words.last()
                       .unwrap()
                       .chars()
                       .count(),
                   license!());
            error.exit();
        }
        Err(error) => error.exit(),
    }
}
<commit_msg>Pass by reference to fix clippy warning<commit_after>/*
 * Copyright (C) 2017  Sebastian Wiesner <swiesner@lunaryorn.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#![deny(warnings)]

#[macro_use]
extern crate clap;
extern crate atty;
extern crate rand;
extern crate ansi_term;
extern crate xkpwgen;

use ansi_term::Colour;
use ansi_term::Style;
use clap::{App, AppSettings, Arg};
use xkpwgen::generate_password;
use xkpwgen::wordlist::builtin_words;

macro_rules! license {
    () => {
    "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."
    }
}

arg_enum! {
    enum YesNoAuto {
        Yes,
        No,
        Auto
    }
}

fn alternating_styles(colour_setting: &YesNoAuto) -> (Style, Style) {
    let enable_colours = match *colour_setting {
        YesNoAuto::Auto => atty::is(atty::Stream::Stdout),
        YesNoAuto::Yes => true,
        YesNoAuto::No => false,
    };
    if enable_colours {
        (Style::new().fg(Colour::Cyan), Style::new().fg(Colour::Purple))
    } else {
        (Style::new(), Style::new())
    }
}

fn app() -> App<'static, 'static> {
    app_from_crate!()
        .after_help(concat!("Copyright (C) 2017 Sebastian Wiesner <swiesner@lunaryorn.com>\n\n",
                            license!()))
        .version_message("Print version information")
        .help_message("Print this message")
        .arg(Arg::with_name("colour")
                 .alias("color")
                 .long("colour")
                 .possible_values(&["yes", "no", "auto"])
                 .default_value("auto")
                 .help("Whether to enable or disable coloured output."))
        .arg(Arg::with_name("number")
                 .short("n")
                 .long("number")
                 .default_value("5")
                 .help("The number of passwords to generate at once"))
        .arg(Arg::with_name("length")
                 .short("l")
                 .long("length")
                 .default_value("4")
                 .help("The number of words in each password"))
        .arg(Arg::with_name("words").long("words").help("Print the internal wordlist and exit"))
        .settings(&[AppSettings::ColoredHelp,
                    AppSettings::DontCollapseArgsInUsage,
                    // Don't put flags and options in separate --help groups
                    AppSettings::UnifiedHelpMessage])
}

fn main() {
    let parse_result = app().get_matches_safe();

    match parse_result {
        Ok(matches) => {
            if matches.is_present("words") {
                for word in builtin_words() {
                    println!("{}", word);
                }
            } else {
                let words = builtin_words();
                let password_length = value_t_or_exit!(matches.value_of("length"), usize);
                let number_of_passwords = value_t_or_exit!(matches.value_of("number"), usize);
                let (even, odd) =
                    alternating_styles(&value_t_or_exit!(matches, "colour", YesNoAuto));
                for lineno in 0..number_of_passwords {
                    let style = if lineno % 2 == 0 { even } else { odd };
                    let password =
                        generate_password(&mut rand::thread_rng(), &words, password_length, " ");
                    println!("{}", style.paint(password));
                }
            }
        }
        Err(error @ clap::Error { kind: clap::ErrorKind::VersionDisplayed, .. }) => {
            let mut words = builtin_words();
            words.sort_by_key(|w| w.chars().count());
            print!("\n
EFF long wordlist July 2017: {} words (min length {}, max length {})

{}",
                   words.len(),
                   words[0].chars().count(),
                   words.last()
                       .unwrap()
                       .chars()
                       .count(),
                   license!());
            error.exit();
        }
        Err(error) => error.exit(),
    }
}
<|endoftext|>


<commit_before>#![feature(globs)]
extern crate rgtk;

use rgtk::*;
use std::collections::HashSet;
use std::ptr;

mod projects;
mod utils;

fn main() {
    gtk::init();

    // constants

    let width = 1242;
    let height = 768;
    let editor_height = ((height as f32) * 0.8) as i32;

    // window

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("SolidOak");
    window.set_window_position(gtk::window_position::Center);
    window.set_default_size(width, height);

    window.connect(gtk::signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // project pane

    let new_project_button = gtk::Button::new_with_label("New Project").unwrap();
    let import_button = gtk::Button::new_with_label("Import").unwrap();
    let rename_button = gtk::Button::new_with_label("Rename").unwrap();
    let remove_button = gtk::Button::new_with_label("Remove").unwrap();

    let mut project_buttons = gtk::Box::new(gtk::orientation::Horizontal, 0).unwrap();
    project_buttons.set_size_request(-1, -1);
    project_buttons.add(&new_project_button);
    project_buttons.add(&import_button);
    project_buttons.add(&rename_button);
    project_buttons.add(&remove_button);

    let mut project_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let store = gtk::TreeStore::new(column_types).unwrap();
    let model = store.get_model().unwrap();
    project_tree.set_model(&model);
    project_tree.set_headers_visible(false);

    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    project_tree.append_column(&column);

    let mut project_pane = gtk::Box::new(gtk::orientation::Vertical, 0).unwrap();
    project_pane.set_size_request(-1, -1);
    project_pane.pack_start(&project_buttons, false, true, 0);
    project_pane.pack_start(&project_tree, true, true, 0);

    // editor pane

    let editor_pane = gtk::TextView::new().unwrap();
    editor_pane.set_size_request(-1, editor_height);

    // build pane

    let build_pane = gtk::TextView::new().unwrap();

    // content

    let mut content = gtk::Box::new(gtk::orientation::Vertical, 0).unwrap();
    content.pack_start(&editor_pane, false, true, 0);
    content.pack_start(&build_pane, true, true, 0);

    // hbox

    let mut hbox = gtk::Box::new(gtk::orientation::Horizontal, 0).unwrap();
    hbox.pack_start(&project_pane, false, true, 0);
    hbox.pack_start(&content, true, true, 0);
    window.add(&hbox);

    // state

    let mut state = ::utils::State{
        projects: HashSet::new(),
        expansions: HashSet::new(),
        selection: None,
        tree_store: &store
    };

    // populate tree

    let mut iter = gtk::ffi::C_GtkTreeIter;
    state.tree_store.append(&mut iter, ptr::null_mut());
    state.tree_store.set_string(&mut iter, 0, "Hello, world!");

    let mut child = gtk::ffi::C_GtkTreeIter;
    state.tree_store.append(&mut child, &mut iter);
    state.tree_store.set_string(&mut child, 0, "Bye, world!");

    // connections

    new_project_button.connect(gtk::signals::Clicked::new(|| {::projects::new_project(&mut state)}));
    import_button.connect(gtk::signals::Clicked::new(|| {::projects::import_project(&mut state)}));
    rename_button.connect(gtk::signals::Clicked::new(|| {::projects::rename_project(&mut state)}));
    remove_button.connect(gtk::signals::Clicked::new(|| {::projects::remove_project(&mut state)}));

    // show window

    window.show_all();
    gtk::main();
}
<commit_msg>Use TreeIter instead of C_GtkTreeIter<commit_after>#![feature(globs)]
extern crate rgtk;

use rgtk::*;
use std::collections::HashSet;

mod projects;
mod utils;

fn main() {
    gtk::init();

    // constants

    let width = 1242;
    let height = 768;
    let editor_height = ((height as f32) * 0.8) as i32;

    // window

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("SolidOak");
    window.set_window_position(gtk::window_position::Center);
    window.set_default_size(width, height);

    window.connect(gtk::signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // project pane

    let new_project_button = gtk::Button::new_with_label("New Project").unwrap();
    let import_button = gtk::Button::new_with_label("Import").unwrap();
    let rename_button = gtk::Button::new_with_label("Rename").unwrap();
    let remove_button = gtk::Button::new_with_label("Remove").unwrap();

    let mut project_buttons = gtk::Box::new(gtk::orientation::Horizontal, 0).unwrap();
    project_buttons.set_size_request(-1, -1);
    project_buttons.add(&new_project_button);
    project_buttons.add(&import_button);
    project_buttons.add(&rename_button);
    project_buttons.add(&remove_button);

    let mut project_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let store = gtk::TreeStore::new(column_types).unwrap();
    let model = store.get_model().unwrap();
    project_tree.set_model(&model);
    project_tree.set_headers_visible(false);

    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    project_tree.append_column(&column);

    let mut project_pane = gtk::Box::new(gtk::orientation::Vertical, 0).unwrap();
    project_pane.set_size_request(-1, -1);
    project_pane.pack_start(&project_buttons, false, true, 0);
    project_pane.pack_start(&project_tree, true, true, 0);

    // editor pane

    let editor_pane = gtk::TextView::new().unwrap();
    editor_pane.set_size_request(-1, editor_height);

    // build pane

    let build_pane = gtk::TextView::new().unwrap();

    // content

    let mut content = gtk::Box::new(gtk::orientation::Vertical, 0).unwrap();
    content.pack_start(&editor_pane, false, true, 0);
    content.pack_start(&build_pane, true, true, 0);

    // hbox

    let mut hbox = gtk::Box::new(gtk::orientation::Horizontal, 0).unwrap();
    hbox.pack_start(&project_pane, false, true, 0);
    hbox.pack_start(&content, true, true, 0);
    window.add(&hbox);

    // state

    let mut state = ::utils::State{
        projects: HashSet::new(),
        expansions: HashSet::new(),
        selection: None,
        tree_store: &store
    };

    // populate tree

    let mut iter_raw = gtk::ffi::C_GtkTreeIter;
    let iter = gtk::TreeIter::wrap_pointer(&mut iter_raw);
    state.tree_store.append(&iter, None);
    state.tree_store.set_string(&iter, 0, "Hello, world!");

    let mut child_raw = gtk::ffi::C_GtkTreeIter;
    let child = gtk::TreeIter::wrap_pointer(&mut child_raw);
    state.tree_store.append(&child, Some(&iter));
    state.tree_store.set_string(&child, 0, "Bye, world!");

    // connections

    new_project_button.connect(gtk::signals::Clicked::new(|| {::projects::new_project(&mut state)}));
    import_button.connect(gtk::signals::Clicked::new(|| {::projects::import_project(&mut state)}));
    rename_button.connect(gtk::signals::Clicked::new(|| {::projects::rename_project(&mut state)}));
    remove_button.connect(gtk::signals::Clicked::new(|| {::projects::remove_project(&mut state)}));

    // show window

    window.show_all();
    gtk::main();
}
<|endoftext|>


<commit_before>#![feature(box_syntax)]

extern crate open;

// FIXME: is it possible to move all of that in platform/macos?
// FIXME: here it's because macro can only be used if included in main.rs
// FIXME: here it's because we want to access cocoa from platform/macos/delegate.rs
#[cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[cfg(target_os = "macos")]
extern crate cocoa;
#[cfg(target_os = "macos")]
extern crate objc_foundation;
#[cfg(target_os = "macos")]
extern crate libc;

#[macro_use]
extern crate bitflags;

mod window;
mod widgets;
mod servo;
mod platform;

use std::env::args;
use servo::{FollowLinkPolicy, Servo, ServoEvent, ServoCursor};
use window::{GlutinWindow, WindowEvent, WindowMouseButton, WindowMouseCursor};
use window::{WindowMouseScrollDelta, WindowElementState, WindowVirtualKeyCode};

#[derive(Copy, Clone)]
pub struct DrawableGeometry {
    inner_size: (u32, u32),
    position: (i32, i32),
    hidpi_factor: f32,
}

bitflags! {
    flags KeyModifiers: u8 {
        const LEFT_CONTROL = 1,
        const RIGHT_CONTROL = 2,
        const LEFT_SHIFT = 4,
        const RIGHT_SHIFT = 8,
        const LEFT_ALT = 16,
        const RIGHT_ALT = 32,
        const LEFT_SUPER = 64,
        const RIGHT_SUPER = 128,
    }
}

fn main() {

    widgets::Widgets::setup_app();

    let url = args().nth(1).unwrap_or("http://servo.org".to_owned());
    let window = GlutinWindow::new();
    let widgets = widgets::Widgets::new(&window);

    // FIXME: set policy via command line arg
    let servo = Servo::new(window.get_geometry(),
                           window.create_event_loop_riser(),
                           &url,
                           FollowLinkPolicy::FollowOriginalDomain);

    let mut mouse_pos = (0, 0);
    let mut mouse_down_button: Option<WindowMouseButton> = None;
    let mut mouse_down_point = (0, 0);
    let mut first_load = true;
    let mut key_modifiers = KeyModifiers::empty();

    loop {
        let mut winit_events = window.get_events();
        let mut widget_events = widgets.get_events();
        let mut browser_events = servo.get_events();

        for event in widget_events.drain(..) {
            match event {
                widgets::WidgetEvent::BackClicked => {
                    servo.go_back();
                }
                widgets::WidgetEvent::FwdClicked => {
                    servo.go_fwd();
                }
                widgets::WidgetEvent::ReloadClicked => {
                    servo.reload();
                }
            }
        }

        for event in browser_events.drain(..) {
            match event {
                ServoEvent::CursorChanged(servo_cursor) => {
                    let winit_cursor = match servo_cursor {
                        ServoCursor::None => WindowMouseCursor::NoneCursor,
                        ServoCursor::Default => WindowMouseCursor::Default,
                        ServoCursor::Pointer => WindowMouseCursor::Hand,
                        ServoCursor::ContextMenu => WindowMouseCursor::ContextMenu,
                        ServoCursor::Help => WindowMouseCursor::Help,
                        ServoCursor::Progress => WindowMouseCursor::Progress,
                        ServoCursor::Wait => WindowMouseCursor::Wait,
                        ServoCursor::Cell => WindowMouseCursor::Cell,
                        ServoCursor::Crosshair => WindowMouseCursor::Crosshair,
                        ServoCursor::Text => WindowMouseCursor::Text,
                        ServoCursor::VerticalText => WindowMouseCursor::VerticalText,
                        ServoCursor::Alias => WindowMouseCursor::Alias,
                        ServoCursor::Copy => WindowMouseCursor::Copy,
                        ServoCursor::Move => WindowMouseCursor::Move,
                        ServoCursor::NoDrop => WindowMouseCursor::NoDrop,
                        ServoCursor::NotAllowed => WindowMouseCursor::NotAllowed,
                        ServoCursor::Grab => WindowMouseCursor::Grab,
                        ServoCursor::Grabbing => WindowMouseCursor::Grabbing,
                        ServoCursor::EResize => WindowMouseCursor::EResize,
                        ServoCursor::NResize => WindowMouseCursor::NResize,
                        ServoCursor::NeResize => WindowMouseCursor::NeResize,
                        ServoCursor::NwResize => WindowMouseCursor::NwResize,
                        ServoCursor::SResize => WindowMouseCursor::SResize,
                        ServoCursor::SeResize => WindowMouseCursor::SeResize,
                        ServoCursor::SwResize => WindowMouseCursor::SwResize,
                        ServoCursor::WResize => WindowMouseCursor::WResize,
                        ServoCursor::EwResize => WindowMouseCursor::EwResize,
                        ServoCursor::NsResize => WindowMouseCursor::NsResize,
                        ServoCursor::NeswResize => WindowMouseCursor::NeswResize,
                        ServoCursor::NwseResize => WindowMouseCursor::NwseResize,
                        ServoCursor::ColResize => WindowMouseCursor::ColResize,
                        ServoCursor::RowResize => WindowMouseCursor::RowResize,
                        ServoCursor::AllScroll => WindowMouseCursor::AllScroll,
                        ServoCursor::ZoomIn => WindowMouseCursor::ZoomIn,
                        ServoCursor::ZoomOut => WindowMouseCursor::ZoomOut,
                    };
                    window.get_winit_window().set_cursor(winit_cursor);
                }
                ServoEvent::Present => {
                    window.swap_buffers();
                }
                ServoEvent::HeadParsed(url) => {
                    widgets.set_urlbar_text(url.as_str());
                    if !first_load {
                        // FIXME: this is hacky, but until we get better history state
                        // events, that'll do it.
                        widgets.set_back_button_enabled(true);
                    }
                    first_load = false;
                }
                ServoEvent::LoadStart(can_go_back, can_go_forward) => {
                    widgets.set_back_button_enabled(can_go_back);
                    widgets.set_fwd_button_enabled(can_go_forward);
                    widgets.set_indicator_active(true);
                }
                ServoEvent::LoadEnd(can_go_back, can_go_forward, root) => {
                    // FIXME: why root?
                    if root {
                        widgets.set_back_button_enabled(can_go_back);
                        widgets.set_fwd_button_enabled(can_go_forward);
                    }
                    widgets.set_indicator_active(false);
                }
                ServoEvent::StatusChanged(status) => {
                    match status {
                        None => widgets.set_bottombar_text(""),
                        Some(text) => widgets.set_bottombar_text(text.as_str()),
                    }
                }
                ServoEvent::TitleChanged(title) => {
                    window.get_winit_window().set_title(&title.unwrap_or("No Title".to_owned()));
                }
                ServoEvent::UnhandledURL(url) => {
                    open::that(url.as_str()).ok();
                }
                e => {
                    println!("Unhandled Servo event: {:?}", e);
                }
            }
        }

        for event in winit_events.drain(..) {
            match event {
                WindowEvent::MouseMoved(x, y) => {
                    let y = y - 76; /* FIXME: magic value */
                    mouse_pos = (x, y);
                    servo.update_mouse_coordinates(x, y);
                }
                WindowEvent::MouseWheel(delta, phase) => {
                    let (mut dx, mut dy) = match delta {
                        // FIXME: magic value
                        WindowMouseScrollDelta::LineDelta(dx, dy) => (dx, dy * 38.),
                        WindowMouseScrollDelta::PixelDelta(dx, dy) => (dx, dy),
                    };
                    if dy.abs() >= dx.abs() {
                        dx = 0.0;
                    } else {
                        dy = 0.0;
                    }
                    let (x, y) = mouse_pos;
                    servo.scroll(x, y, dx, dy, phase);
                }
                WindowEvent::ReceivedCharacter(ch) => {
                    println!("ReceivedCharacter: {:?}", ch);
                }
                WindowEvent::KeyboardInput(element_state, _scan_code, Some(virtual_key_code)) => {
                    match virtual_key_code {
                        WindowVirtualKeyCode::LControl => key_modifiers.toggle(LEFT_CONTROL),
                        WindowVirtualKeyCode::RControl => key_modifiers.toggle(RIGHT_CONTROL),
                        WindowVirtualKeyCode::LShift => key_modifiers.toggle(LEFT_SHIFT),
                        WindowVirtualKeyCode::RShift => key_modifiers.toggle(RIGHT_SHIFT),
                        WindowVirtualKeyCode::LAlt => key_modifiers.toggle(LEFT_ALT),
                        WindowVirtualKeyCode::RAlt => key_modifiers.toggle(RIGHT_ALT),
                        WindowVirtualKeyCode::LWin => key_modifiers.toggle(LEFT_SUPER),
                        WindowVirtualKeyCode::RWin => key_modifiers.toggle(RIGHT_SUPER),
                        _ => {}
                    }

                    let is_cmd = key_modifiers.intersects(LEFT_SUPER | RIGHT_SUPER);
                    match (element_state, virtual_key_code, is_cmd) {
                        (WindowElementState::Pressed, WindowVirtualKeyCode::Left, true) => {
                            servo.go_back();
                        }
                        (WindowElementState::Pressed, WindowVirtualKeyCode::Right, true) => {
                            servo.go_fwd();
                        }
                        _ => {
                            // FIXME
                        }
                    }
                }
                WindowEvent::MouseInput(element_state, mouse_button) => {
                    if mouse_button == WindowMouseButton::Left ||
                       mouse_button == WindowMouseButton::Right {
                        if element_state == WindowElementState::Pressed {
                            mouse_down_point = mouse_pos;
                            mouse_down_button = Some(mouse_button);
                        }
                        let (x, y) = mouse_pos;
                        let (org_x, org_y) = mouse_down_point;
                        servo.click(x,
                                    y,
                                    org_x,
                                    org_y,
                                    element_state,
                                    mouse_button,
                                    mouse_down_button);
                    }
                }
                WindowEvent::Awakened |
                WindowEvent::TouchpadPressure(..) => {
                    // Skip printing. Too many.
                }
                e => {
                    println!("Unhandled Window event: {:?}", e);
                }
            }
        }

        // sync is necessary even if there's no event.
        // The main thread is awaken by Servo (see CompositorProxy trick).
        // servo.handle_event() is then expected to be called.
        servo.sync();
    }
}
<commit_msg>remove useless println<commit_after>#![feature(box_syntax)]

extern crate open;

// FIXME: is it possible to move all of that in platform/macos?
// FIXME: here it's because macro can only be used if included in main.rs
// FIXME: here it's because we want to access cocoa from platform/macos/delegate.rs
#[cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
#[cfg(target_os = "macos")]
extern crate cocoa;
#[cfg(target_os = "macos")]
extern crate objc_foundation;
#[cfg(target_os = "macos")]
extern crate libc;

#[macro_use]
extern crate bitflags;

mod window;
mod widgets;
mod servo;
mod platform;

use std::env::args;
use servo::{FollowLinkPolicy, Servo, ServoEvent, ServoCursor};
use window::{GlutinWindow, WindowEvent, WindowMouseButton, WindowMouseCursor};
use window::{WindowMouseScrollDelta, WindowElementState, WindowVirtualKeyCode};

#[derive(Copy, Clone)]
pub struct DrawableGeometry {
    inner_size: (u32, u32),
    position: (i32, i32),
    hidpi_factor: f32,
}

bitflags! {
    flags KeyModifiers: u8 {
        const LEFT_CONTROL = 1,
        const RIGHT_CONTROL = 2,
        const LEFT_SHIFT = 4,
        const RIGHT_SHIFT = 8,
        const LEFT_ALT = 16,
        const RIGHT_ALT = 32,
        const LEFT_SUPER = 64,
        const RIGHT_SUPER = 128,
    }
}

fn main() {

    widgets::Widgets::setup_app();

    let url = args().nth(1).unwrap_or("http://servo.org".to_owned());
    let window = GlutinWindow::new();
    let widgets = widgets::Widgets::new(&window);

    // FIXME: set policy via command line arg
    let servo = Servo::new(window.get_geometry(),
                           window.create_event_loop_riser(),
                           &url,
                           FollowLinkPolicy::FollowOriginalDomain);

    let mut mouse_pos = (0, 0);
    let mut mouse_down_button: Option<WindowMouseButton> = None;
    let mut mouse_down_point = (0, 0);
    let mut first_load = true;
    let mut key_modifiers = KeyModifiers::empty();

    loop {
        let mut winit_events = window.get_events();
        let mut widget_events = widgets.get_events();
        let mut browser_events = servo.get_events();

        for event in widget_events.drain(..) {
            match event {
                widgets::WidgetEvent::BackClicked => {
                    servo.go_back();
                }
                widgets::WidgetEvent::FwdClicked => {
                    servo.go_fwd();
                }
                widgets::WidgetEvent::ReloadClicked => {
                    servo.reload();
                }
            }
        }

        for event in browser_events.drain(..) {
            match event {
                ServoEvent::CursorChanged(servo_cursor) => {
                    let winit_cursor = match servo_cursor {
                        ServoCursor::None => WindowMouseCursor::NoneCursor,
                        ServoCursor::Default => WindowMouseCursor::Default,
                        ServoCursor::Pointer => WindowMouseCursor::Hand,
                        ServoCursor::ContextMenu => WindowMouseCursor::ContextMenu,
                        ServoCursor::Help => WindowMouseCursor::Help,
                        ServoCursor::Progress => WindowMouseCursor::Progress,
                        ServoCursor::Wait => WindowMouseCursor::Wait,
                        ServoCursor::Cell => WindowMouseCursor::Cell,
                        ServoCursor::Crosshair => WindowMouseCursor::Crosshair,
                        ServoCursor::Text => WindowMouseCursor::Text,
                        ServoCursor::VerticalText => WindowMouseCursor::VerticalText,
                        ServoCursor::Alias => WindowMouseCursor::Alias,
                        ServoCursor::Copy => WindowMouseCursor::Copy,
                        ServoCursor::Move => WindowMouseCursor::Move,
                        ServoCursor::NoDrop => WindowMouseCursor::NoDrop,
                        ServoCursor::NotAllowed => WindowMouseCursor::NotAllowed,
                        ServoCursor::Grab => WindowMouseCursor::Grab,
                        ServoCursor::Grabbing => WindowMouseCursor::Grabbing,
                        ServoCursor::EResize => WindowMouseCursor::EResize,
                        ServoCursor::NResize => WindowMouseCursor::NResize,
                        ServoCursor::NeResize => WindowMouseCursor::NeResize,
                        ServoCursor::NwResize => WindowMouseCursor::NwResize,
                        ServoCursor::SResize => WindowMouseCursor::SResize,
                        ServoCursor::SeResize => WindowMouseCursor::SeResize,
                        ServoCursor::SwResize => WindowMouseCursor::SwResize,
                        ServoCursor::WResize => WindowMouseCursor::WResize,
                        ServoCursor::EwResize => WindowMouseCursor::EwResize,
                        ServoCursor::NsResize => WindowMouseCursor::NsResize,
                        ServoCursor::NeswResize => WindowMouseCursor::NeswResize,
                        ServoCursor::NwseResize => WindowMouseCursor::NwseResize,
                        ServoCursor::ColResize => WindowMouseCursor::ColResize,
                        ServoCursor::RowResize => WindowMouseCursor::RowResize,
                        ServoCursor::AllScroll => WindowMouseCursor::AllScroll,
                        ServoCursor::ZoomIn => WindowMouseCursor::ZoomIn,
                        ServoCursor::ZoomOut => WindowMouseCursor::ZoomOut,
                    };
                    window.get_winit_window().set_cursor(winit_cursor);
                }
                ServoEvent::Present => {
                    window.swap_buffers();
                }
                ServoEvent::HeadParsed(url) => {
                    widgets.set_urlbar_text(url.as_str());
                    if !first_load {
                        // FIXME: this is hacky, but until we get better history state
                        // events, that'll do it.
                        widgets.set_back_button_enabled(true);
                    }
                    first_load = false;
                }
                ServoEvent::LoadStart(can_go_back, can_go_forward) => {
                    widgets.set_back_button_enabled(can_go_back);
                    widgets.set_fwd_button_enabled(can_go_forward);
                    widgets.set_indicator_active(true);
                }
                ServoEvent::LoadEnd(can_go_back, can_go_forward, root) => {
                    // FIXME: why root?
                    if root {
                        widgets.set_back_button_enabled(can_go_back);
                        widgets.set_fwd_button_enabled(can_go_forward);
                    }
                    widgets.set_indicator_active(false);
                }
                ServoEvent::StatusChanged(status) => {
                    match status {
                        None => widgets.set_bottombar_text(""),
                        Some(text) => widgets.set_bottombar_text(text.as_str()),
                    }
                }
                ServoEvent::TitleChanged(title) => {
                    window.get_winit_window().set_title(&title.unwrap_or("No Title".to_owned()));
                }
                ServoEvent::UnhandledURL(url) => {
                    open::that(url.as_str()).ok();
                }
                e => {
                    println!("Unhandled Servo event: {:?}", e);
                }
            }
        }

        for event in winit_events.drain(..) {
            match event {
                WindowEvent::MouseMoved(x, y) => {
                    let y = y - 76; /* FIXME: magic value */
                    mouse_pos = (x, y);
                    servo.update_mouse_coordinates(x, y);
                }
                WindowEvent::MouseWheel(delta, phase) => {
                    let (mut dx, mut dy) = match delta {
                        // FIXME: magic value
                        WindowMouseScrollDelta::LineDelta(dx, dy) => (dx, dy * 38.),
                        WindowMouseScrollDelta::PixelDelta(dx, dy) => (dx, dy),
                    };
                    if dy.abs() >= dx.abs() {
                        dx = 0.0;
                    } else {
                        dy = 0.0;
                    }
                    let (x, y) = mouse_pos;
                    servo.scroll(x, y, dx, dy, phase);
                }
                WindowEvent::KeyboardInput(element_state, _scan_code, Some(virtual_key_code)) => {
                    match virtual_key_code {
                        WindowVirtualKeyCode::LControl => key_modifiers.toggle(LEFT_CONTROL),
                        WindowVirtualKeyCode::RControl => key_modifiers.toggle(RIGHT_CONTROL),
                        WindowVirtualKeyCode::LShift => key_modifiers.toggle(LEFT_SHIFT),
                        WindowVirtualKeyCode::RShift => key_modifiers.toggle(RIGHT_SHIFT),
                        WindowVirtualKeyCode::LAlt => key_modifiers.toggle(LEFT_ALT),
                        WindowVirtualKeyCode::RAlt => key_modifiers.toggle(RIGHT_ALT),
                        WindowVirtualKeyCode::LWin => key_modifiers.toggle(LEFT_SUPER),
                        WindowVirtualKeyCode::RWin => key_modifiers.toggle(RIGHT_SUPER),
                        _ => {}
                    }

                    let is_cmd = key_modifiers.intersects(LEFT_SUPER | RIGHT_SUPER);
                    match (element_state, virtual_key_code, is_cmd) {
                        (WindowElementState::Pressed, WindowVirtualKeyCode::Left, true) => {
                            servo.go_back();
                        }
                        (WindowElementState::Pressed, WindowVirtualKeyCode::Right, true) => {
                            servo.go_fwd();
                        }
                        _ => {
                            // FIXME
                        }
                    }
                }
                WindowEvent::MouseInput(element_state, mouse_button) => {
                    if mouse_button == WindowMouseButton::Left ||
                       mouse_button == WindowMouseButton::Right {
                        if element_state == WindowElementState::Pressed {
                            mouse_down_point = mouse_pos;
                            mouse_down_button = Some(mouse_button);
                        }
                        let (x, y) = mouse_pos;
                        let (org_x, org_y) = mouse_down_point;
                        servo.click(x,
                                    y,
                                    org_x,
                                    org_y,
                                    element_state,
                                    mouse_button,
                                    mouse_down_button);
                    }
                }
                WindowEvent::Awakened |
                WindowEvent::TouchpadPressure(..) => {
                    // Skip printing. Too many.
                }
                e => {
                    println!("Unhandled Window event: {:?}", e);
                }
            }
        }

        // sync is necessary even if there's no event.
        // The main thread is awaken by Servo (see CompositorProxy trick).
        // servo.handle_event() is then expected to be called.
        servo.sync();
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code, unused_variables)]

extern crate crossbeam;
extern crate docopt;
extern crate env_logger;
extern crate grep;
#[macro_use]
extern crate log;
extern crate memchr;
extern crate memmap;
extern crate num_cpus;
extern crate parking_lot;
extern crate regex;
extern crate regex_syntax as syntax;
extern crate rustc_serialize;
extern crate thread_local;
extern crate walkdir;

use std::cmp;
use std::error::Error;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::result;
use std::sync::Arc;
use std::thread;

use crossbeam::sync::SegQueue;
use docopt::Docopt;
use grep::{Grep, GrepBuilder};
use parking_lot::Mutex;
use walkdir::WalkDir;

use ignore::Ignore;
use printer::Printer;
use search::{InputBuffer, Searcher};

macro_rules! errored {
    ($($tt:tt)*) => {
        return Err(From::from(format!($($tt)*)));
    }
}

macro_rules! eprintln {
    ($($tt:tt)*) => {{
        use std::io::Write;
        let _ = writeln!(&mut ::std::io::stderr(), $($tt)*);
    }}
}

mod gitignore;
mod glob;
mod ignore;
mod printer;
mod search;
mod walk;

const USAGE: &'static str = "
Usage: xrep [options] <pattern> [<path> ...]
       xrep --files [<path> ...]

xrep is like the silver searcher and grep, but faster than both.

WARNING: Searching stdin isn't yet supported.

Options:
    -c, --count                Suppress normal output and show count of line
                               matches.
    -A, --after-context NUM    Show NUM lines after each match.
    -B, --before-context NUM   Show NUM lines before each match.
    -C, --context NUM          Show NUM lines before and after each match.
    --debug                    Show debug messages.
    --files                    Print each file that would be searched
                               (but don't search).
    --hidden                   Search hidden directories and files.
    -i, --ignore-case          Case insensitive search.
    -L, --follow               Follow symlinks.
    -n, --line-number          Show line numbers (1-based).
    -t, --threads ARG          The number of threads to use. Defaults to the
                               number of logical CPUs. [default: 0]
    -v, --invert-match         Invert matching.
";

#[derive(RustcDecodable)]
struct Args {
    arg_pattern: String,
    arg_path: Vec<String>,
    flag_after_context: usize,
    flag_before_context: usize,
    flag_context: usize,
    flag_count: bool,
    flag_debug: bool,
    flag_files: bool,
    flag_follow: bool,
    flag_hidden: bool,
    flag_ignore_case: bool,
    flag_invert_match: bool,
    flag_line_number: bool,
    flag_threads: usize,
}

pub type Result<T> = result::Result<T, Box<Error + Send + Sync>>;

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode())
                                       .unwrap_or_else(|e| e.exit());
    match run(args) {
        Ok(_) => process::exit(0),
        Err(err) => {
            let _ = writeln!(&mut io::stderr(), "{}", err);
            process::exit(1);
        }
    }
}

fn run(mut args: Args) -> Result<()> {
    let mut logb = env_logger::LogBuilder::new();
    if args.flag_debug {
        logb.filter(None, log::LogLevelFilter::Debug);
    } else {
        logb.filter(None, log::LogLevelFilter::Warn);
    }
    if let Err(err) = logb.init() {
        errored!("failed to initialize logger: {}", err);
    }

    if args.arg_path.is_empty() {
        args.arg_path.push("./".to_string());
    }
    if args.arg_path.iter().any(|p| p == "-") {
        errored!("searching <stdin> isn't yet supported");
    }
    if args.flag_files {
        return run_files(args);
    }
    let args = Arc::new(args);
    let mut workers = vec![];
    let stdout = Arc::new(Mutex::new(io::BufWriter::new(io::stdout())));

    let chan_work_send = {
        let chan_work = Arc::new(SegQueue::new());
        for _ in 0..args.num_workers() {
            let grepb =
                GrepBuilder::new(&args.arg_pattern)
                .case_insensitive(args.flag_ignore_case);
            let worker = Worker {
                args: args.clone(),
                stdout: stdout.clone(),
                chan_work: chan_work.clone(),
                inpbuf: InputBuffer::new(),
                outbuf: Some(vec![]),
                grep: try!(grepb.build()),
            };
            workers.push(thread::spawn(move || worker.run()));
        }
        chan_work
    };

    for p in &args.arg_path {
        for path in args.walker(p) {
            chan_work_send.push(Message::Some(path));
        }
    }
    for _ in 0..workers.len() {
        chan_work_send.push(Message::Quit);
    }
    for worker in workers {
        worker.join().unwrap();
    }
    Ok(())
}

fn run_files(args: Args) -> Result<()> {
    let mut printer = Printer::new(io::BufWriter::new(io::stdout()));
    for p in &args.arg_path {
        for path in args.walker(p) {
            printer.path(path);
        }
    }
    Ok(())
}

impl Args {
    fn printer<W: io::Write>(&self, wtr: W) -> Printer<W> {
        Printer::new(wtr)
    }

    fn num_workers(&self) -> usize {
        let mut num = self.flag_threads;
        if num == 0 {
            num = cmp::min(8, num_cpus::get());
        }
        num
    }

    fn walker<P: AsRef<Path>>(&self, path: P) -> walk::Iter {
        let wd = WalkDir::new(path).follow_links(self.flag_follow);
        let mut ig = Ignore::new();
        ig.ignore_hidden(!self.flag_hidden);
        walk::Iter::new(ig, wd)
    }
}

enum Message<T> {
    Some(T),
    Quit,
}

struct Worker {
    args: Arc<Args>,
    stdout: Arc<Mutex<io::BufWriter<io::Stdout>>>,
    chan_work: Arc<SegQueue<Message<PathBuf>>>,
    inpbuf: InputBuffer,
    outbuf: Option<Vec<u8>>,
    grep: Grep,
}

impl Worker {
    fn run(mut self) {
        loop {
            let path = match self.chan_work.try_pop() {
                None => continue,
                Some(Message::Quit) => break,
                Some(Message::Some(path)) => path,
            };
            let file = match File::open(&path) {
                Ok(file) => file,
                Err(err) => {
                    eprintln!("{}: {}", path.display(), err);
                    continue;
                }
            };
            let mut outbuf = self.outbuf.take().unwrap();
            outbuf.clear();
            let mut printer = self.args.printer(outbuf);
            {
                let mut searcher = Searcher::new(
                    &mut self.inpbuf,
                    &mut printer,
                    &self.grep,
                    &path,
                    file,
                );
                searcher = searcher.count(self.args.flag_count);
                searcher = searcher.line_number(self.args.flag_line_number);
                searcher = searcher.invert_match(self.args.flag_invert_match);
                searcher = searcher.before_context(
                    self.args.flag_before_context);
                if let Err(err) = searcher.run() {
                    eprintln!("{}", err);
                }
            }
            let outbuf = printer.into_inner();
            if !outbuf.is_empty() {
                let mut stdout = self.stdout.lock();
                let _ = stdout.write_all(&outbuf);
                let _ = stdout.flush();
            }
            self.outbuf = Some(outbuf);
        }
    }
}
<commit_msg>Switch to Chase-Lev work stealing queue.<commit_after>#![allow(dead_code, unused_variables)]

extern crate crossbeam;
extern crate docopt;
extern crate env_logger;
extern crate grep;
#[macro_use]
extern crate log;
extern crate memchr;
extern crate memmap;
extern crate num_cpus;
extern crate parking_lot;
extern crate regex;
extern crate regex_syntax as syntax;
extern crate rustc_serialize;
extern crate thread_local;
extern crate walkdir;

use std::cmp;
use std::error::Error;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::result;
use std::sync::Arc;
use std::thread;

use crossbeam::sync::chase_lev::{self, Steal, Stealer};
use docopt::Docopt;
use grep::{Grep, GrepBuilder};
use parking_lot::Mutex;
use walkdir::WalkDir;

use ignore::Ignore;
use printer::Printer;
use search::{InputBuffer, Searcher};

macro_rules! errored {
    ($($tt:tt)*) => {
        return Err(From::from(format!($($tt)*)));
    }
}

macro_rules! eprintln {
    ($($tt:tt)*) => {{
        use std::io::Write;
        let _ = writeln!(&mut ::std::io::stderr(), $($tt)*);
    }}
}

mod gitignore;
mod glob;
mod ignore;
mod printer;
mod search;
mod walk;

const USAGE: &'static str = "
Usage: xrep [options] <pattern> [<path> ...]
       xrep --files [<path> ...]

xrep is like the silver searcher and grep, but faster than both.

WARNING: Searching stdin isn't yet supported.

Options:
    -c, --count                Suppress normal output and show count of line
                               matches.
    -A, --after-context NUM    Show NUM lines after each match.
    -B, --before-context NUM   Show NUM lines before each match.
    -C, --context NUM          Show NUM lines before and after each match.
    --debug                    Show debug messages.
    --files                    Print each file that would be searched
                               (but don't search).
    --hidden                   Search hidden directories and files.
    -i, --ignore-case          Case insensitive search.
    -L, --follow               Follow symlinks.
    -n, --line-number          Show line numbers (1-based).
    -t, --threads ARG          The number of threads to use. Defaults to the
                               number of logical CPUs. [default: 0]
    -v, --invert-match         Invert matching.
";

#[derive(RustcDecodable)]
struct Args {
    arg_pattern: String,
    arg_path: Vec<String>,
    flag_after_context: usize,
    flag_before_context: usize,
    flag_context: usize,
    flag_count: bool,
    flag_debug: bool,
    flag_files: bool,
    flag_follow: bool,
    flag_hidden: bool,
    flag_ignore_case: bool,
    flag_invert_match: bool,
    flag_line_number: bool,
    flag_threads: usize,
}

pub type Result<T> = result::Result<T, Box<Error + Send + Sync>>;

fn main() {
    let args: Args = Docopt::new(USAGE).and_then(|d| d.decode())
                                       .unwrap_or_else(|e| e.exit());
    match run(args) {
        Ok(_) => process::exit(0),
        Err(err) => {
            let _ = writeln!(&mut io::stderr(), "{}", err);
            process::exit(1);
        }
    }
}

fn run(mut args: Args) -> Result<()> {
    let mut logb = env_logger::LogBuilder::new();
    if args.flag_debug {
        logb.filter(None, log::LogLevelFilter::Debug);
    } else {
        logb.filter(None, log::LogLevelFilter::Warn);
    }
    if let Err(err) = logb.init() {
        errored!("failed to initialize logger: {}", err);
    }

    if args.arg_path.is_empty() {
        args.arg_path.push("./".to_string());
    }
    if args.arg_path.iter().any(|p| p == "-") {
        errored!("searching <stdin> isn't yet supported");
    }
    if args.flag_files {
        return run_files(args);
    }
    let args = Arc::new(args);
    let mut workers = vec![];
    let stdout = Arc::new(Mutex::new(io::BufWriter::new(io::stdout())));

    let mut chan_work_send = {
        let (worker, stealer) = chase_lev::deque();
        for _ in 0..args.num_workers() {
            let grepb =
                GrepBuilder::new(&args.arg_pattern)
                .case_insensitive(args.flag_ignore_case);
            let worker = Worker {
                args: args.clone(),
                stdout: stdout.clone(),
                chan_work: stealer.clone(),
                inpbuf: InputBuffer::new(),
                outbuf: Some(vec![]),
                grep: try!(grepb.build()),
            };
            workers.push(thread::spawn(move || worker.run()));
        }
        worker
    };

    for p in &args.arg_path {
        for path in args.walker(p) {
            chan_work_send.push(Message::Some(path));
        }
    }
    for _ in 0..workers.len() {
        chan_work_send.push(Message::Quit);
    }
    for worker in workers {
        worker.join().unwrap();
    }
    Ok(())
}

fn run_files(args: Args) -> Result<()> {
    let mut printer = Printer::new(io::BufWriter::new(io::stdout()));
    for p in &args.arg_path {
        for path in args.walker(p) {
            printer.path(path);
        }
    }
    Ok(())
}

impl Args {
    fn printer<W: io::Write>(&self, wtr: W) -> Printer<W> {
        Printer::new(wtr)
    }

    fn num_workers(&self) -> usize {
        let mut num = self.flag_threads;
        if num == 0 {
            num = cmp::min(8, num_cpus::get());
        }
        num
    }

    fn walker<P: AsRef<Path>>(&self, path: P) -> walk::Iter {
        let wd = WalkDir::new(path).follow_links(self.flag_follow);
        let mut ig = Ignore::new();
        ig.ignore_hidden(!self.flag_hidden);
        walk::Iter::new(ig, wd)
    }
}

enum Message<T> {
    Some(T),
    Quit,
}

struct Worker {
    args: Arc<Args>,
    stdout: Arc<Mutex<io::BufWriter<io::Stdout>>>,
    chan_work: Stealer<Message<PathBuf>>,
    inpbuf: InputBuffer,
    outbuf: Option<Vec<u8>>,
    grep: Grep,
}

impl Worker {
    fn run(mut self) {
        loop {
            let path = match self.chan_work.steal() {
                Steal::Empty | Steal::Abort => continue,
                Steal::Data(Message::Quit) => break,
                Steal::Data(Message::Some(path)) => path,
            };
            let file = match File::open(&path) {
                Ok(file) => file,
                Err(err) => {
                    eprintln!("{}: {}", path.display(), err);
                    continue;
                }
            };
            let mut outbuf = self.outbuf.take().unwrap();
            outbuf.clear();
            let mut printer = self.args.printer(outbuf);
            {
                let mut searcher = Searcher::new(
                    &mut self.inpbuf,
                    &mut printer,
                    &self.grep,
                    &path,
                    file,
                );
                searcher = searcher.count(self.args.flag_count);
                searcher = searcher.line_number(self.args.flag_line_number);
                searcher = searcher.invert_match(self.args.flag_invert_match);
                searcher = searcher.before_context(
                    self.args.flag_before_context);
                if let Err(err) = searcher.run() {
                    eprintln!("{}", err);
                }
            }
            let outbuf = printer.into_inner();
            if !outbuf.is_empty() {
                let mut stdout = self.stdout.lock();
                let _ = stdout.write_all(&outbuf);
                let _ = stdout.flush();
            }
            self.outbuf = Some(outbuf);
        }
    }
}
<|endoftext|>


<commit_before>#![feature(rustc_private)] // TODO Migrate to crates.io variant (json)
#![feature(core)]

extern crate hyper;
extern crate regex;
extern crate serialize;
extern crate websocket;
extern crate rustc_serialize;

mod authentication;
mod messages_stream;
mod user_view;
mod user;
mod message;
mod channel;
mod current_state;

use current_state::new_current_state_from_json;
use message::new_message_from_str;

#[allow(dead_code)]
fn main() {
    let (token,_guard) = authentication::get_oauth_token_or_panic();

    // let slack_stream = messages_stream::establish_stream(&token);
    // let current_state = new_current_state_from_json(&slack_stream.initial_state);
    // for message in slack_stream.iter() {
    //     match new_message_from_str(message.as_slice()) {
    //         Ok(message) => {
    //             match current_state.user_id_to_user(message.user.as_slice()) {
    //                 Some(user) => {
    //                     println!("{} - {}: {}", message.channel, user.name, message.text)
    //                 },
    //                 None => {
    //                     println!("{} - {}: {}", message.channel, "UnknownUser", message.text)
    //                 }

    //             }
    //         },
    //         Err(e) => println!("{}", e)
    //     }
    // }
}
<commit_msg>Print mapped users messages<commit_after>#![feature(rustc_private)] // TODO Migrate to crates.io variant (json)
#![feature(core)]
#![feature(convert)] // & instead of as_ref/as_slice

extern crate hyper;
extern crate regex;
extern crate serialize;
extern crate websocket;
extern crate rustc_serialize;

mod authentication;
mod messages_stream;
mod user_view;
mod user;
mod message;
mod channel;
mod current_state;

use current_state::new_current_state_from_json;
use message::new_message_from_str;

#[allow(dead_code)]
fn main() {
    let (token,_guard) = authentication::get_oauth_token_or_panic();

    let slack_stream = messages_stream::establish_stream(&token);
    let current_state = new_current_state_from_json(&slack_stream.initial_state);
    for message in slack_stream.iter() {
        match new_message_from_str(&message) {
            Ok(message) => {
                match message.event_type.unwrap_or("".to_string()).as_ref() {
                    "message" => {
                        match current_state.user_id_to_user(&message.user.unwrap_or("".to_string())) {
                            Some(user) => {
                                println!("{} - {}: {}", message.channel.unwrap(), user.name, message.text.unwrap())
                            },
                            None => {
                                println!("{} - {}: {}", message.channel.unwrap(), "UnknownUser", message.text.unwrap())
                            }

                        }
                    },
                    _ => println!("{}", message.text.unwrap_or("".to_string()))
                }
            },
            Err(e) => println!("{}", e)
        }
    }
}
<|endoftext|>


<commit_before>extern crate iron;
extern crate router;
extern crate rustc_serialize;

use std::io::Read;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

use iron::prelude::*;
use iron::status;
use router::Router;
use rustc_serialize::json::{self, Json};

#[derive(Debug)]
struct Document {
    data: Json,
}

impl Document {
    fn from_json(data: Json) -> Document {
        Document{
            data: data,
        }
    }
}

#[derive(Debug)]
enum Filter {
    Not(Box<Filter>),
    Or(Vec<Filter>),
    And(Vec<Filter>),
    Term(String, String),
}

impl Filter {
    fn matches(&self, doc: &Document) -> bool {
        match *self {
            Filter::Not(ref filter) => !filter.matches(doc),
            Filter::Or(ref filters) => {
                for filter in filters.iter() {
                    if (filter.matches(doc)) {
                        return true;
                    }
                }

                false
            },
            Filter::And(ref filters) => {
                for filter in filters.iter() {
                    if (!filter.matches(doc)) {
                        return false;
                    }
                }

                true
            },
            Filter::Term(ref field, ref value) => {
                let obj = doc.data.as_object().unwrap();

                if let Some(field_value) = obj.get(field) {
                    if let Json::String(ref field_value) = *field_value {
                        return field_value == value
                    }
                }

                false
            }
        }
    }
}

#[derive(Debug)]
struct Mapping {
    pub docs: HashMap<String, Document>,
}

impl Mapping {
    fn new() -> Mapping {
        Mapping{
            docs: HashMap::new(),
        }
    }
}

#[derive(Debug)]
struct Index {
    pub mappings: HashMap<String, Mapping>,
}

impl Index {
    fn new() -> Index {
        Index{
            mappings: HashMap::new(),
        }
    }
}

fn index_not_found_response() -> Response {
    let mut response = Response::with((status::NotFound, "{\"message\": \"Index not found\"}"));
    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
    return response;
}

fn main() {
    let indices = Arc::new(Mutex::new(HashMap::new()));
    let mut wagtail_index = Index::new();
    wagtail_index.mappings.insert("wagtaildocs_document".to_owned(), Mapping::new());
    indices.lock().unwrap().insert("wagtaildemo".to_owned(), wagtail_index);

    let f = Filter::Or(vec![
        Filter::Term("title".to_owned(), "test".to_owned()),
        Filter::Term("title".to_owned(), "foo".to_owned()),
    ]);

    println!("{:?}", f);

    let mut router = Router::new();

    router.get("/", |_: &mut Request| -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    });

    {
        let indices = indices.clone();

        router.get("/:index/_count", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load query from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // TODO: Run query

            // Temporary count and return numbers
            let mut count = 0;
            for mapping in index.mappings.values() {
                count += mapping.docs.len();
            }

            let mut response = Response::with((status::Ok, format!("{{\"count\": {}}}", count)));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/_search", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load query from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // TODO: Run query

            let mut response = Response::with((status::Ok, "{\"hits\": {\"total\": 0, \"hits\": []}}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            let doc_id = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Find mapping
            let mapping = match index.mappings.get(mapping_name) {
                Some(mapping) => mapping,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Mapping not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            // Find document
            let doc = match mapping.docs.get(doc_id) {
                Some(doc) => doc,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Document not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            let mut response = Response::with((status::Ok, json::encode(&doc.data).unwrap()));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            let ref doc_id = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Find index
            let mut index = match indices.get_mut(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Find mapping
            let mut mapping = match index.mappings.get_mut(mapping_name) {
                Some(mapping) => mapping,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Mapping not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Create and insert document
            if let Some(data) = data {
                let doc = Document::from_json(data);
                println!("{:?}", f.matches(&doc));
                mapping.docs.insert(doc_id.clone().to_owned(), doc);
            }

            let mut response = Response::with((status::Ok, "{}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let ref index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Create index
            indices.insert(index_name.clone().to_owned(), Index::new());

            let mut response = Response::with((status::Ok, "{\"acknowledged\": true}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/_mapping/:mapping", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let ref mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Find index
            let mut index = match indices.get_mut(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Insert mapping
            index.mappings.insert(mapping_name.clone().to_owned(), Mapping::new());

            let mut response = Response::with((status::Ok, "{\"acknowledged\": true}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    Iron::new(router).http("localhost:9200").unwrap();
}
<commit_msg>First pass at the bulk API<commit_after>extern crate iron;
extern crate router;
extern crate rustc_serialize;

use std::io::Read;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

use iron::prelude::*;
use iron::status;
use router::Router;
use rustc_serialize::json::{self, Json};

#[derive(Debug)]
struct Document {
    data: Json,
}

impl Document {
    fn from_json(data: Json) -> Document {
        Document{
            data: data,
        }
    }
}

#[derive(Debug)]
enum Filter {
    Not(Box<Filter>),
    Or(Vec<Filter>),
    And(Vec<Filter>),
    Term(String, String),
}

impl Filter {
    fn matches(&self, doc: &Document) -> bool {
        match *self {
            Filter::Not(ref filter) => !filter.matches(doc),
            Filter::Or(ref filters) => {
                for filter in filters.iter() {
                    if (filter.matches(doc)) {
                        return true;
                    }
                }

                false
            },
            Filter::And(ref filters) => {
                for filter in filters.iter() {
                    if (!filter.matches(doc)) {
                        return false;
                    }
                }

                true
            },
            Filter::Term(ref field, ref value) => {
                let obj = doc.data.as_object().unwrap();

                if let Some(field_value) = obj.get(field) {
                    if let Json::String(ref field_value) = *field_value {
                        return field_value == value
                    }
                }

                false
            }
        }
    }
}

#[derive(Debug)]
struct Mapping {
    pub docs: HashMap<String, Document>,
}

impl Mapping {
    fn new() -> Mapping {
        Mapping{
            docs: HashMap::new(),
        }
    }
}

#[derive(Debug)]
struct Index {
    pub mappings: HashMap<String, Mapping>,
}

impl Index {
    fn new() -> Index {
        Index{
            mappings: HashMap::new(),
        }
    }
}

fn index_not_found_response() -> Response {
    let mut response = Response::with((status::NotFound, "{\"message\": \"Index not found\"}"));
    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
    return response;
}

fn main() {
    let indices = Arc::new(Mutex::new(HashMap::new()));
    let mut wagtail_index = Index::new();
    wagtail_index.mappings.insert("wagtaildocs_document".to_owned(), Mapping::new());
    indices.lock().unwrap().insert("wagtaildemo".to_owned(), wagtail_index);

    let f = Filter::Or(vec![
        Filter::Term("title".to_owned(), "test".to_owned()),
        Filter::Term("title".to_owned(), "foo".to_owned()),
    ]);

    println!("{:?}", f);

    let mut router = Router::new();

    router.get("/", |_: &mut Request| -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    });

    {
        let indices = indices.clone();

        router.get("/:index/_count", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load query from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // TODO: Run query

            // Temporary count and return numbers
            let mut count = 0;
            for mapping in index.mappings.values() {
                count += mapping.docs.len();
            }

            let mut response = Response::with((status::Ok, format!("{{\"count\": {}}}", count)));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/_search", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load query from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // TODO: Run query

            let mut response = Response::with((status::Ok, "{\"hits\": {\"total\": 0, \"hits\": []}}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            let doc_id = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            // Lock index array
            let indices = indices.lock().unwrap();

            // Find index
            let index = match indices.get(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Find mapping
            let mapping = match index.mappings.get(mapping_name) {
                Some(mapping) => mapping,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Mapping not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            // Find document
            let doc = match mapping.docs.get(doc_id) {
                Some(doc) => doc,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Document not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            let mut response = Response::with((status::Ok, json::encode(&doc.data).unwrap()));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            let ref doc_id = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Find index
            let mut index = match indices.get_mut(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Find mapping
            let mut mapping = match index.mappings.get_mut(mapping_name) {
                Some(mapping) => mapping,
                None => {
                    let mut response = Response::with((status::NotFound, "{\"message\": \"Mapping not found\"}"));
                    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                    return Ok(response);
                }
            };

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Create and insert document
            if let Some(data) = data {
                let doc = Document::from_json(data);
                println!("{:?}", f.matches(&doc));
                mapping.docs.insert(doc_id.clone().to_owned(), doc);
            }

            let mut response = Response::with((status::Ok, "{}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let ref index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Create index
            indices.insert(index_name.clone().to_owned(), Index::new());

            let mut response = Response::with((status::Ok, "{\"acknowledged\": true}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/_mapping/:mapping", move |req: &mut Request| -> IronResult<Response> {
            // URL parameters
            let index_name = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            let ref mapping_name = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");

            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Find index
            let mut index = match indices.get_mut(index_name) {
                Some(index) => index,
                None => {
                    return Ok(index_not_found_response());
                }
            };

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            let data = if !payload.is_empty() {
                Some(match Json::from_str(&payload) {
                    Ok(data) => data,
                    Err(error) => {
                        // TODO: What specifically is bad about the JSON?
                        let mut response = Response::with((status::BadRequest, "{\"message\": \"Couldn't parse JSON\"}"));
                        response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                        return Ok(response);
                    }
                })
            } else {
                None
            };

            // Insert mapping
            index.mappings.insert(mapping_name.clone().to_owned(), Mapping::new());

            let mut response = Response::with((status::Ok, "{\"acknowledged\": true}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.post("/_bulk", move |req: &mut Request| -> IronResult<Response> {
            // Lock index array
            let mut indices = indices.lock().unwrap();

            // Load data from body
            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            for payload_part in payload.split('\n') {
                let data = if !payload.is_empty() {
                    Some(Json::from_str(&payload))
                } else {
                    None
                };
            }

            let mut response = Response::with((status::Ok, "{\"acknowledged\": true}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    Iron::new(router).http("localhost:9200").unwrap();
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::collections::HashMap;
use std::env;

include!("./sentiment.rs");

// Gets a normalized nick from a log nick.
// - Removes beginning '+' and '@'
// - Removes trailing '_' and '-'
fn get_nick(s: &str) -> &str {
    let ignored_prefixes: &[_] = &['+', '@', ' '];
    let ignored_suffixes: &[_] = &['_', '-', ' '];

    return &s.trim_left_matches(ignored_prefixes)
        .trim_right_matches(ignored_suffixes);
}

fn main() {
    // Parse arguments.
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
       panic!("Usage: {} [log file name]", args[0]);
    }
    let path = args[1].clone();

    // Read file.
    let f = match File::open(&path) {
        Err(why) => panic!("Couldn't open {}: {}", path, why),
        Ok(f) => f,
    };
    let f = BufReader::new(f);

    let analizer = sentiment::new("./src/wordlist.txt");

    // Fold all lines to a hashmap containing username -> score.
    let result = f.lines().fold(HashMap::new(), |mut res, line| {
        let line = line.expect("Couldn't parse line");

        let parts = line.split("\t").collect::<Vec<&str>>();
        let who = get_nick(parts[1]).to_string();
        let comment_value = analizer.analyze(parts[2]);

        if comment_value == 0.0 || ["*", "**", "***", "--", "---", "-->", "<--", "-", "", "<-", "=!=", "<"]
            .contains(&who.as_str()) {
                return res;
            }

        let val = match res.get(&who) {
            Some(existing_comment_value) => existing_comment_value + comment_value,
            None => comment_value,
        };

        res.insert(who, val);
        return res;
    });

    for (key, value) in result {
        print!("{} {}\n", key, value);
    }
}
<commit_msg>Run rustfmt<commit_after>use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::collections::HashMap;
use std::env;

include!("./sentiment.rs");

// Gets a normalized nick from a log nick.
// - Removes beginning '+' and '@'
// - Removes trailing '_' and '-'
fn get_nick(s: &str) -> &str {
    let ignored_prefixes: &[_] = &['+', '@', ' '];
    let ignored_suffixes: &[_] = &['_', '-', ' '];

    return &s.trim_left_matches(ignored_prefixes)
        .trim_right_matches(ignored_suffixes);
}

fn main() {
    // Parse arguments.
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        panic!("Usage: {} [log file name]", args[0]);
    }
    let path = args[1].clone();

    // Read file.
    let f = match File::open(&path) {
        Err(why) => panic!("Couldn't open {}: {}", path, why),
        Ok(f) => f,
    };
    let f = BufReader::new(f);

    let analizer = sentiment::new("./src/wordlist.txt");

    // Fold all lines to a hashmap containing username -> score.
    let result = f.lines().fold(HashMap::new(), |mut res, line| {
        let line = line.expect("Couldn't parse line");

        let parts = line.split("\t").collect::<Vec<&str>>();
        let who = get_nick(parts[1]).to_string();
        let comment_value = analizer.analyze(parts[2]);

        if comment_value == 0.0 ||
           ["*", "**", "***", "--", "---", "-->", "<--", "-", "", "<-", "=!=", "<"]
            .contains(&who.as_str()) {
            return res;
        }

        let val = match res.get(&who) {
            Some(existing_comment_value) => existing_comment_value + comment_value,
            None => comment_value,
        };

        res.insert(who, val);
        return res;
    });

    for (key, value) in result {
        print!("{} {}\n", key, value);
    }
}
<|endoftext|>