<commit_before>
use std::iter::range_step;
use std::collections::hashmap::HashSet;
use std::rand::random;
use graphics::*;
use piston::*;
use number_renderer::NumberRenderer;
use settings::Settings;
use tile::{
    Tile,
    TileStatic,
};

pub struct Board<'a> {
    tiles: Vec<Tile<'a>>,
    score: int,

    settings: &'a Settings,
}

impl<'a> Board<'a> {
    pub fn new(settings: &'a Settings) -> Board<'a> {
        let mut board = Board {
            tiles: Vec::<Tile>::new(),
            score: 0,
            settings: settings,
        };
        board.generate_tile();
        board.generate_tile();
        board
    }

    pub fn generate_tile(&mut self) {
        if self.tiles.len() == (self.settings.tile_width * self.settings.tile_height) as uint {
            return;
        }

        loop {
            let x = (random::<uint>() % self.settings.tile_width as uint) as int;
            let y = (random::<uint>() % self.settings.tile_height as uint) as int;
            if self.get_tile(x, y).is_none() {
                self.tiles.push(Tile::new(self.settings, 2, x, y));
                break;
            }
        }
    }

    pub fn update(&mut self, dt: f64) {
        for tile in self.tiles.mut_iter() {
            tile.update(dt);
        }

        if self.is_locking() {
            return;
        }
        let mut score_to_added = 0;
        let mut tiles_need_removed = HashSet::<uint>::new();
        let mut tiles_need_added = Vec::<Tile>::new();
        for i in range(0, self.tiles.len()) {
            let tile1 = self.tiles.get(i);
            if tile1.status != TileStatic {
                continue;
            }
            for j in range(i + 1, self.tiles.len()) {
                let tile2 = self.tiles.get(j);
                if tile2.status != TileStatic
                   || tile1.tile_x != tile2.tile_x
                   || tile1.tile_y != tile2.tile_y {
                    continue;
                }

                tiles_need_removed.insert(i);
                tiles_need_removed.insert(j);
                tiles_need_added.push(Tile::new_combined(self.settings, tile1.score + tile2.score, tile1.tile_x, tile1.tile_y));
                score_to_added += tile1.score + tile2.score;
                break;
            }
        }

        if tiles_need_removed.len() > 0 {
            let mut tiles = Vec::<Tile>::new();
            for i in range(0, self.tiles.len()) {
                if !tiles_need_removed.contains(&i) {
                    tiles.push(*self.tiles.get(i));
                }
            }
            self.tiles = tiles.append(tiles_need_added.as_slice());
            self.add_score(score_to_added);
        }
    }

    pub fn render(&self, number_renderer: &NumberRenderer, c: &Context, gl: &mut Gl) {
        number_renderer.render(
            self.score as u32,
            self.settings.best_rect[0] + self.settings.best_rect[2] / 2.0,
            self.settings.best_rect[1] + self.settings.best_rect[3] / 2.0,
            self.settings.best_rect[2],
            self.settings.text_light_color, c, gl);

        self.render_board(c, gl);
        self.render_tiles(number_renderer, c, gl);
    }

    pub fn merge_from_bottom_to_top(&mut self) {
        self.merge_col(0, self.settings.tile_height, 1);
    }

    pub fn merge_from_top_to_bottom(&mut self) {
        self.merge_col(self.settings.tile_height - 1, -1, -1);
    }

    fn merge_col(&mut self, y_start: int, y_end: int, y_step: int) {
        if self.is_locking() {
            return;
        }

        let mut need_generate = false;
        loop {
            // move all tiles to right place
            for col in range(0, self.settings.tile_width) {
                for row in range_step(y_start, y_end, y_step) {
                    match self.get_mut_tile(col, row) {
                        None => {
                            match self.get_mut_next_tile(col, row, 0, y_step) {
                                Some(ref mut tile) => {
                                    println!("move ({}, {}) to ({}, {})",
                                             tile.tile_x, tile.tile_y, col, row);
                                    need_generate = true;
                                    tile.start_moving(col, row);
                                },
                                _ => {},
                            }
                        },
                        _ => {},
                    }
                }
            }

            let mut did_merged = false;
            for col in range(0, self.settings.tile_width) {
                let mut found = false;
                let mut sx = 0;
                let mut sy = 0;
                let mut dx = 0;
                let mut dy = 0;
                for row in range_step(y_start, y_end, y_step) {
                    match self.get_tile(col, row) {
                        Some(ref d_tile) => {
                            match self.get_next_tile(col, row, 0, y_step) {
                                Some(ref s_tile)
                                if d_tile.score == s_tile.score
                                   && self.get_tile_count(d_tile.tile_x, d_tile.tile_y) == 1 => {
                                    found = true;
                                    dx = d_tile.tile_x;
                                    dy = d_tile.tile_y;
                                    sx = s_tile.tile_x;
                                    sy = s_tile.tile_y;
                                    break;
                                },
                                _ => {},
                            }
                        },
                        None => {
                            break;
                        }
                    }
                }
                if found {
                    need_generate = true;
                    did_merged = true;
                    let mut tile = self.get_mut_tile(sx, sy);
                    let tile = tile.get_mut_ref();
                    tile.start_moving(dx, dy);
                    println!("merge ({}, {}) to ({}, {})", sx, sy, dx, dy);
                }
            }

            if !did_merged {
                break;
            }
        }
        if need_generate {
            self.generate_tile();
        }
    }

    pub fn merge_from_left_to_right(&mut self) {
        self.merge_row(self.settings.tile_width - 1, -1, -1);
    }

    pub fn merge_from_right_to_left(&mut self) {
        self.merge_row(0, self.settings.tile_width, 1);
    }

    fn merge_row(&mut self, x_start: int, x_end: int, x_step: int) {
        if self.is_locking() {
            return;
        }

        let mut need_generate = false;
        loop {
            // move all tiles to right place
            for row in range(0, self.settings.tile_height) {
                for col in range_step(x_start, x_end, x_step) {
                    match self.get_mut_tile(col, row) {
                        None => {
                            match self.get_mut_next_tile(col, row, x_step, 0) {
                                Some(ref mut tile) => {
                                    println!("move ({}, {}) to ({}, {})", tile.tile_x, tile.tile_y, col, row);
                                    need_generate = true;
                                    tile.start_moving(col, row);
                                },
                                _ => {},
                            }
                        },
                        _ => {},
                    }
                }
            }

            // merge
            let mut did_merged = false;
            for row in range(0, self.settings.tile_height) {
                let mut found = false;
                let mut sx = 0;
                let mut sy = 0;
                let mut dx = 0;
                let mut dy = 0;
                for col in range_step(x_start, x_end, x_step) {
                    match self.get_tile(col, row) {
                        Some(ref d_tile) => {
                            match self.get_next_tile(col, row, x_step, 0) {
                                Some(ref s_tile)
                                if d_tile.score == s_tile.score
                                   && self.get_tile_count(d_tile.tile_x, d_tile.tile_y) == 1 => {
                                    found = true;
                                    dx = d_tile.tile_x;
                                    dy = d_tile.tile_y;
                                    sx = s_tile.tile_x;
                                    sy = s_tile.tile_y;
                                    break;
                                },
                                _ => {},
                            }
                        },
                        None => {
                            break;
                        }
                    }
                }
                if found {
                    need_generate = true;
                    did_merged = true;
                    let mut tile = self.get_mut_tile(sx, sy);
                    let tile = tile.get_mut_ref();
                    tile.start_moving(dx, dy);
                    println!("merge ({}, {}) to ({}, {})", sx, sy, dx, dy);
                }
            }

            if !did_merged {
                break;
            }
        }

        if need_generate {
            self.generate_tile();
        }
    }

    fn is_locking(&self) -> bool {
        for tile in self.tiles.iter() {
            if tile.status != TileStatic {
                return true;
            }
        }
        false
    }

    /// Returns next tile right besides (x, y)
    fn get_next_tile<'b>(&'b self, x: int, y: int, step_x: int, step_y: int) -> Option<&'b Tile<'a>> {
        let mut x = x + step_x;
        let mut y = y + step_y;
        while x >= 0 && x < self.settings.tile_width
              && y >= 0 && y < self.settings.tile_height {
            let tile = self.get_tile(x, y);
            if tile.is_some() {
                return tile;
            }
            x += step_x;
            y += step_y;
        }
        None
    }

    fn get_mut_next_tile<'b>(&'b mut self, x: int, y: int, step_x: int, step_y: int) -> Option<&'b mut Tile<'a>> {
        let mut x = x + step_x;
        let mut y = y + step_y;
        let mut found = false;
        while x >= 0 && x < self.settings.tile_width
              && y >= 0 && y < self.settings.tile_height {
            let tile = self.get_tile(x, y);
            if tile.is_some() {
                found = true;
                break;
            }
            x += step_x;
            y += step_y;
        }

        if found {
            self.get_mut_tile(x, y)
        } else {
            None
        }
    }

    fn get_tile<'b>(&'b self, x: int, y: int) -> Option<&'b Tile<'a>> {
        for tile in self.tiles.iter() {
            if tile.tile_x == x && tile.tile_y == y {
                return Some(tile);
            }
        }
        None
    }

    fn get_mut_tile<'b>(&'b mut self, x: int, y: int) -> Option<&'b mut Tile<'a>> {
        for tile in self.tiles.mut_iter() {
            if tile.tile_x == x && tile.tile_y == y {
                return Some(tile);
            }
        }
        None
    }

    fn get_tile_count(&self, x: int, y: int) -> int {
        let mut count = 0;
        for tile in self.tiles.iter() {
            if tile.tile_x == x && tile.tile_y == y {
                count += 1;
            }
        }
        count
    }

    fn render_board(&self, c: &Context, gl: &mut Gl) {
        c.view()
         .rect(self.settings.board_padding,
               self.settings.board_padding + self.settings.board_offset_y,
               self.settings.board_size[0],
               self.settings.board_size[1])
         .rgba(self.settings.tile_background_color[0],
               self.settings.tile_background_color[1],
               self.settings.tile_background_color[2],
               1.0)
         .fill(gl);

        let mut x = self.settings.board_padding + self.settings.tile_padding;
        let mut y = self.settings.board_padding + self.settings.board_offset_y + self.settings.tile_padding;
        for _ in range(0, self.settings.tile_height) {
            for _ in range(0, self.settings.tile_width) {
                c.view()
                 .rect(x, y, self.settings.tile_size, self.settings.tile_size)
                 .rgba(self.settings.tiles_colors.get(0)[0],
                       self.settings.tiles_colors.get(0)[1],
                       self.settings.tiles_colors.get(0)[2],
                       1.0)
                 .fill(gl);

                x += self.settings.tile_padding + self.settings.tile_size;
            }
            x = self.settings.board_padding + self.settings.tile_padding;
            y += self.settings.tile_padding + self.settings.tile_size;
        }
    }

    fn render_tiles(&self, number_renderer: &NumberRenderer, c: &Context, gl: &mut Gl) {
        for tile in self.tiles.iter() {
            tile.render(number_renderer, c, gl);
        }
    }

    fn add_score(&mut self, score: int) {
        self.score += score;
        println!("Score: {}", self.score);
    }
}

<commit_msg>Upgraded to latest rust<commit_after>
use std::iter::range_step;
use std::collections::hashmap::HashSet;
use std::rand::random;
use graphics::*;
use piston::*;
use number_renderer::NumberRenderer;
use settings::Settings;
use tile::{
    Tile,
    TileStatic,
};

pub struct Board<'a> {
    tiles: Vec<Tile<'a>>,
    score: int,

    settings: &'a Settings,
}

impl<'a> Board<'a> {
    pub fn new(settings: &'a Settings) -> Board<'a> {
        let mut board = Board {
            tiles: Vec::<Tile>::new(),
            score: 0,
            settings: settings,
        };
        board.generate_tile();
        board.generate_tile();
        board
    }

    pub fn generate_tile(&mut self) {
        if self.tiles.len() == (self.settings.tile_width * self.settings.tile_height) as uint {
            return;
        }

        loop {
            let x = (random::<uint>() % self.settings.tile_width as uint) as int;
            let y = (random::<uint>() % self.settings.tile_height as uint) as int;
            if self.get_tile(x, y).is_none() {
                self.tiles.push(Tile::new(self.settings, 2, x, y));
                break;
            }
        }
    }

    pub fn update(&mut self, dt: f64) {
        for tile in self.tiles.mut_iter() {
            tile.update(dt);
        }

        if self.is_locking() {
            return;
        }
        let mut score_to_added = 0;
        let mut tiles_need_removed = HashSet::<uint>::new();
        let mut tiles_need_added = Vec::<Tile>::new();
        for i in range(0, self.tiles.len()) {
            let tile1 = self.tiles.get(i);
            if tile1.status != TileStatic {
                continue;
            }
            for j in range(i + 1, self.tiles.len()) {
                let tile2 = self.tiles.get(j);
                if tile2.status != TileStatic
                   || tile1.tile_x != tile2.tile_x
                   || tile1.tile_y != tile2.tile_y {
                    continue;
                }

                tiles_need_removed.insert(i);
                tiles_need_removed.insert(j);
                tiles_need_added.push(Tile::new_combined(self.settings, tile1.score + tile2.score, tile1.tile_x, tile1.tile_y));
                score_to_added += tile1.score + tile2.score;
                break;
            }
        }

        if tiles_need_removed.len() > 0 {
            let mut tiles = Vec::<Tile>::new();
            for i in range(0, self.tiles.len()) {
                if !tiles_need_removed.contains(&i) {
                    tiles.push(*self.tiles.get(i));
                }
            }
            self.tiles = tiles.append(tiles_need_added.as_slice());
            self.add_score(score_to_added);
        }
    }

    pub fn render(&self, number_renderer: &NumberRenderer, c: &Context, gl: &mut Gl) {
        number_renderer.render(
            self.score as u32,
            self.settings.best_rect[0] + self.settings.best_rect[2] / 2.0,
            self.settings.best_rect[1] + self.settings.best_rect[3] / 2.0,
            self.settings.best_rect[2],
            self.settings.text_light_color, c, gl);

        self.render_board(c, gl);
        self.render_tiles(number_renderer, c, gl);
    }

    pub fn merge_from_bottom_to_top(&mut self) {
        let height = self.settings.tile_height;
        self.merge_col(0, height, 1);
    }

    pub fn merge_from_top_to_bottom(&mut self) {
        let height = self.settings.tile_height;
        self.merge_col(height - 1, -1, -1);
    }

    fn merge_col(&mut self, y_start: int, y_end: int, y_step: int) {
        if self.is_locking() {
            return;
        }

        let mut need_generate = false;
        loop {
            // move all tiles to right place
            for col in range(0, self.settings.tile_width) {
                for row in range_step(y_start, y_end, y_step) {
                    match self.get_mut_tile(col, row) {
                        None => {
                            match self.get_mut_next_tile(col, row, 0, y_step) {
                                Some(ref mut tile) => {
                                    println!("move ({}, {}) to ({}, {})",
                                             tile.tile_x, tile.tile_y, col, row);
                                    need_generate = true;
                                    tile.start_moving(col, row);
                                },
                                _ => {},
                            }
                        },
                        _ => {},
                    }
                }
            }

            let mut did_merged = false;
            for col in range(0, self.settings.tile_width) {
                let mut found = false;
                let mut sx = 0;
                let mut sy = 0;
                let mut dx = 0;
                let mut dy = 0;
                for row in range_step(y_start, y_end, y_step) {
                    match self.get_tile(col, row) {
                        Some(ref d_tile) => {
                            match self.get_next_tile(col, row, 0, y_step) {
                                Some(ref s_tile)
                                if d_tile.score == s_tile.score
                                   && self.get_tile_count(d_tile.tile_x, d_tile.tile_y) == 1 => {
                                    found = true;
                                    dx = d_tile.tile_x;
                                    dy = d_tile.tile_y;
                                    sx = s_tile.tile_x;
                                    sy = s_tile.tile_y;
                                    break;
                                },
                                _ => {},
                            }
                        },
                        None => {
                            break;
                        }
                    }
                }
                if found {
                    need_generate = true;
                    did_merged = true;
                    let mut tile = self.get_mut_tile(sx, sy);
                    let tile = tile.get_mut_ref();
                    tile.start_moving(dx, dy);
                    println!("merge ({}, {}) to ({}, {})", sx, sy, dx, dy);
                }
            }

            if !did_merged {
                break;
            }
        }
        if need_generate {
            self.generate_tile();
        }
    }

    pub fn merge_from_left_to_right(&mut self) {
        let width = self.settings.tile_width;
        self.merge_row(width - 1, -1, -1);
    }

    pub fn merge_from_right_to_left(&mut self) {
        let width = self.settings.tile_width;
        self.merge_row(0, width, 1);
    }

    fn merge_row(&mut self, x_start: int, x_end: int, x_step: int) {
        if self.is_locking() {
            return;
        }

        let mut need_generate = false;
        loop {
            // move all tiles to right place
            for row in range(0, self.settings.tile_height) {
                for col in range_step(x_start, x_end, x_step) {
                    match self.get_mut_tile(col, row) {
                        None => {
                            match self.get_mut_next_tile(col, row, x_step, 0) {
                                Some(ref mut tile) => {
                                    println!("move ({}, {}) to ({}, {})", tile.tile_x, tile.tile_y, col, row);
                                    need_generate = true;
                                    tile.start_moving(col, row);
                                },
                                _ => {},
                            }
                        },
                        _ => {},
                    }
                }
            }

            // merge
            let mut did_merged = false;
            for row in range(0, self.settings.tile_height) {
                let mut found = false;
                let mut sx = 0;
                let mut sy = 0;
                let mut dx = 0;
                let mut dy = 0;
                for col in range_step(x_start, x_end, x_step) {
                    match self.get_tile(col, row) {
                        Some(ref d_tile) => {
                            match self.get_next_tile(col, row, x_step, 0) {
                                Some(ref s_tile)
                                if d_tile.score == s_tile.score
                                   && self.get_tile_count(d_tile.tile_x, d_tile.tile_y) == 1 => {
                                    found = true;
                                    dx = d_tile.tile_x;
                                    dy = d_tile.tile_y;
                                    sx = s_tile.tile_x;
                                    sy = s_tile.tile_y;
                                    break;
                                },
                                _ => {},
                            }
                        },
                        None => {
                            break;
                        }
                    }
                }
                if found {
                    need_generate = true;
                    did_merged = true;
                    let mut tile = self.get_mut_tile(sx, sy);
                    let tile = tile.get_mut_ref();
                    tile.start_moving(dx, dy);
                    println!("merge ({}, {}) to ({}, {})", sx, sy, dx, dy);
                }
            }

            if !did_merged {
                break;
            }
        }

        if need_generate {
            self.generate_tile();
        }
    }

    fn is_locking(&self) -> bool {
        for tile in self.tiles.iter() {
            if tile.status != TileStatic {
                return true;
            }
        }
        false
    }

    /// Returns next tile right besides (x, y)
    fn get_next_tile<'b>(&'b self, x: int, y: int, step_x: int, step_y: int) -> Option<&'b Tile<'a>> {
        let mut x = x + step_x;
        let mut y = y + step_y;
        while x >= 0 && x < self.settings.tile_width
              && y >= 0 && y < self.settings.tile_height {
            let tile = self.get_tile(x, y);
            if tile.is_some() {
                return tile;
            }
            x += step_x;
            y += step_y;
        }
        None
    }

    fn get_mut_next_tile<'b>(&'b mut self, x: int, y: int, step_x: int, step_y: int) -> Option<&'b mut Tile<'a>> {
        let mut x = x + step_x;
        let mut y = y + step_y;
        let mut found = false;
        while x >= 0 && x < self.settings.tile_width
              && y >= 0 && y < self.settings.tile_height {
            let tile = self.get_tile(x, y);
            if tile.is_some() {
                found = true;
                break;
            }
            x += step_x;
            y += step_y;
        }

        if found {
            self.get_mut_tile(x, y)
        } else {
            None
        }
    }

    fn get_tile<'b>(&'b self, x: int, y: int) -> Option<&'b Tile<'a>> {
        for tile in self.tiles.iter() {
            if tile.tile_x == x && tile.tile_y == y {
                return Some(tile);
            }
        }
        None
    }

    fn get_mut_tile<'b>(&'b mut self, x: int, y: int) -> Option<&'b mut Tile<'a>> {
        for tile in self.tiles.mut_iter() {
            if tile.tile_x == x && tile.tile_y == y {
                return Some(tile);
            }
        }
        None
    }

    fn get_tile_count(&self, x: int, y: int) -> int {
        let mut count = 0;
        for tile in self.tiles.iter() {
            if tile.tile_x == x && tile.tile_y == y {
                count += 1;
            }
        }
        count
    }

    fn render_board(&self, c: &Context, gl: &mut Gl) {
        c.view()
         .rect(self.settings.board_padding,
               self.settings.board_padding + self.settings.board_offset_y,
               self.settings.board_size[0],
               self.settings.board_size[1])
         .rgba(self.settings.tile_background_color[0],
               self.settings.tile_background_color[1],
               self.settings.tile_background_color[2],
               1.0)
         .fill(gl);

        let mut x = self.settings.board_padding + self.settings.tile_padding;
        let mut y = self.settings.board_padding + self.settings.board_offset_y + self.settings.tile_padding;
        for _ in range(0, self.settings.tile_height) {
            for _ in range(0, self.settings.tile_width) {
                c.view()
                 .rect(x, y, self.settings.tile_size, self.settings.tile_size)
                 .rgba(self.settings.tiles_colors.get(0)[0],
                       self.settings.tiles_colors.get(0)[1],
                       self.settings.tiles_colors.get(0)[2],
                       1.0)
                 .fill(gl);

                x += self.settings.tile_padding + self.settings.tile_size;
            }
            x = self.settings.board_padding + self.settings.tile_padding;
            y += self.settings.tile_padding + self.settings.tile_size;
        }
    }

    fn render_tiles(&self, number_renderer: &NumberRenderer, c: &Context, gl: &mut Gl) {
        for tile in self.tiles.iter() {
            tile.render(number_renderer, c, gl);
        }
    }

    fn add_score(&mut self, score: int) {
        self.score += score;
        println!("Score: {}", self.score);
    }
}

<|endoftext|>


<commit_before>#[macro_use]
extern crate clap;
extern crate regex;
extern crate xml;

pub mod parse;
pub mod serialize;

use clap::{App, Arg};
use std::fs::File;
use std::io::BufReader;

fn main() {
    let args = App::new("script-extractor")
                   .version(&crate_version!())
                   .about("Parse movie scripts (pdf) to a structured format (xml)")
                   .arg(Arg::with_name("input-file")
                            .help("xml extracted using 'pdftohtml -xml script.pdf'")
                            .index(1)
                            .required(true)
                            .validator(check_file_exists))
                   .get_matches();

    let input_file = args.value_of("input-file").unwrap();

    let file_reader = File::open(input_file).expect("Cannot open file");
    let buffered_file_reader = Box::new(BufReader::new(file_reader));

    let scenes = parse::parse_script(buffered_file_reader);

    serialize::xml::format_script(&scenes, &mut std::io::stdout()).unwrap();
}

fn check_file_exists(file_name: String) -> Result<(), String> {
    if let Ok(metadata) = std::fs::metadata(&file_name) {
        if metadata.is_file() && !metadata.permissions().readonly() {
            Ok(())
        } else {
            Err(format!("Cannot read file '{}'", file_name))
        }
    } else {
        Err(format!("File '{}' not found", file_name))
    }
}
<commit_msg>Allow reading the input from stdin<commit_after>#[macro_use]
extern crate clap;
extern crate regex;
extern crate xml;

pub mod parse;
pub mod serialize;

use clap::{App, Arg};
use std::fs::File;
use std::io::{BufReader, Read};

fn main() {
    let args = App::new("script-extractor")
                   .version(&crate_version!())
                   .about("Parse movie scripts (pdf) to a structured format (xml)")
                   .arg(Arg::with_name("input-file")
                            .help("xml extracted using 'pdftohtml -xml script.pdf'")
                            .index(1)
                            .validator(check_file_exists))
                   .get_matches();

    let input: Box<Read> = if let Some(input_file) = args.value_of("input-file") {
        let file_reader = File::open(input_file).expect("Cannot open input-file");
        Box::new(BufReader::new(file_reader))
    } else {
        Box::new(BufReader::new(std::io::stdin()))
    };

    let scenes = parse::parse_script(input);

    serialize::xml::format_script(&scenes, &mut std::io::stdout()).unwrap();
}

fn check_file_exists(file_name: String) -> Result<(), String> {
    if let Ok(metadata) = std::fs::metadata(&file_name) {
        if metadata.is_file() && !metadata.permissions().readonly() {
            Ok(())
        } else {
            Err(format!("Cannot read file '{}'", file_name))
        }
    } else {
        Err(format!("File '{}' not found", file_name))
    }
}
<|endoftext|>


<commit_before>use response;
use request::RequestBuilder;

/// The main structure through which all calls are made. This holds a slice of the AUTH TOKEN
pub struct DoManager<'t> {
    auth: &'t str,
}

impl<'t> DoManager<'t> {
    /// Creates a new instance of `DoManager` with a string slice of your AUTH TOKEN
    pub fn with_token(token: &'t str) -> DoManager<'t> {
        DoManager { auth: token }
    }

    /// Returns a request that can be used to view account information.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.account()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn account(&self) -> RequestBuilder<'t, response::Account> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/account")
    }

    /// Returns a request that can be used to list all regions
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.regions()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn regions(&self) -> RequestBuilder<'t, response::Regions> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/regions")
    }

    /// Returns a request that can be used to list all available sizes
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.sizes()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn sizes(&self) -> RequestBuilder<'t, response::Sizes> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/sizes")
    }

    /// Returns a request that can be used gain additional requests for a particular image
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// // Or domgr.image("some slug")
    /// match domgr.image("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn image(&self, id: &str) -> RequestBuilder<'t, response::Image> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/images/{}", id))
    }

    /// Returns a request that can be used to view all available images, or actions on multiple
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.images()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn images(&self) -> RequestBuilder<'t, response::Images> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/images")
    }

    /// Returns a request that can be used to view all SSH keys or actions on multiple keys
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.ssh_keys()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn ssh_keys(&self) -> RequestBuilder<'t, response::SshKeys> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/account/keys")
    }

    /// Returns a request that can be used to view a single SSH key, or actions that apply to only
    /// one key
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// // or domgr.ssh_key("some finger print")
    /// match domgr.ssh_key("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn ssh_key(&self, id: &str) -> RequestBuilder<'t, response::SshKey> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/account/keys/{}", id))
    }

    /// Returns a request that can be used to view a single droplet, or actions that only apply to
    /// one droplet
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.droplet("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn droplet(&self, id: &str) -> RequestBuilder<'t, response::Droplet> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/droplets/{}", id))
    }

    /// Returns a request that can be used to view all available droplets, or actions that apply to
    /// multiple droplets
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.droplets()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn droplets(&self) -> RequestBuilder<'t, response::Droplets> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/droplets")
    }

    /// Returns a request that can be used to view all domains, or actions that apply to multiple
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.domains()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn domains(&self) -> RequestBuilder<'t, response::Domains> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/domains")
    }

    /// Returns a request that can be used to view a single domain, or actions that apply to only
    /// one
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.domain("super.com")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn domain(&self, name: &str) -> RequestBuilder<'t, response::Domain> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/domains/{}", name))
    }
}
<commit_msg>Derive Clone for DoManager<commit_after>use response;
use request::RequestBuilder;

/// The main structure through which all calls are made. This holds a slice of the AUTH TOKEN
#[derive(Clone)]
pub struct DoManager<'t> {
    auth: &'t str,
}

impl<'t> DoManager<'t> {
    /// Creates a new instance of `DoManager` with a string slice of your AUTH TOKEN
    pub fn with_token(token: &'t str) -> DoManager<'t> {
        DoManager { auth: token }
    }

    /// Returns a request that can be used to view account information.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.account()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn account(&self) -> RequestBuilder<'t, response::Account> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/account")
    }

    /// Returns a request that can be used to list all regions
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.regions()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn regions(&self) -> RequestBuilder<'t, response::Regions> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/regions")
    }

    /// Returns a request that can be used to list all available sizes
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.sizes()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn sizes(&self) -> RequestBuilder<'t, response::Sizes> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/sizes")
    }

    /// Returns a request that can be used gain additional requests for a particular image
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// // Or domgr.image("some slug")
    /// match domgr.image("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn image(&self, id: &str) -> RequestBuilder<'t, response::Image> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/images/{}", id))
    }

    /// Returns a request that can be used to view all available images, or actions on multiple
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.images()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn images(&self) -> RequestBuilder<'t, response::Images> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/images")
    }

    /// Returns a request that can be used to view all SSH keys or actions on multiple keys
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.ssh_keys()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn ssh_keys(&self) -> RequestBuilder<'t, response::SshKeys> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/account/keys")
    }

    /// Returns a request that can be used to view a single SSH key, or actions that apply to only
    /// one key
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// // or domgr.ssh_key("some finger print")
    /// match domgr.ssh_key("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn ssh_key(&self, id: &str) -> RequestBuilder<'t, response::SshKey> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/account/keys/{}", id))
    }

    /// Returns a request that can be used to view a single droplet, or actions that only apply to
    /// one droplet
    ///
    /// **NOTE**: `id` may either be an image ID, or slug
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.droplet("1234")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn droplet(&self, id: &str) -> RequestBuilder<'t, response::Droplet> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/droplets/{}", id))
    }

    /// Returns a request that can be used to view all available droplets, or actions that apply to
    /// multiple droplets
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.droplets()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn droplets(&self) -> RequestBuilder<'t, response::Droplets> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/droplets")
    }

    /// Returns a request that can be used to view all domains, or actions that apply to multiple
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.domains()
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn domains(&self) -> RequestBuilder<'t, response::Domains> {
        RequestBuilder::new(self.auth, "https://api.digitalocean.com/v2/domains")
    }

    /// Returns a request that can be used to view a single domain, or actions that apply to only
    /// one
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use doapi::DoManager;
    /// # use doapi::DoRequest;
    /// let domgr = DoManager::with_token("asfasdfasdf");
    /// match domgr.domain("super.com")
    ///            .retrieve() {
    ///     Ok(_)  => println!("Success"),
    ///     Err(_) => println!("Error")
    /// }
    /// ```
    pub fn domain(&self, name: &str) -> RequestBuilder<'t, response::Domain> {
        RequestBuilder::new(self.auth,
                            format!("https://api.digitalocean.com/v2/domains/{}", name))
    }
}
<|endoftext|>


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

use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::{OnErrorEventHandlerNonNull, EventHandlerNonNull};
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::WindowBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::error::{Fallible, InvalidCharacter};
use dom::bindings::global;
use dom::bindings::js::{MutNullableJS, JSRef, Temporary, OptionalSettable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::browsercontext::BrowserContext;
use dom::console::Console;
use dom::document::Document;
use dom::eventtarget::{EventTarget, WindowTypeId, EventTargetHelpers};
use dom::location::Location;
use dom::navigator::Navigator;
use dom::performance::Performance;
use dom::screen::Screen;
use dom::storage::Storage;
use layout_interface::NoQuery;
use page::Page;
use script_task::{ExitWindowMsg, ScriptChan, TriggerLoadMsg, TriggerFragmentMsg};
use script_task::FromWindow;
use script_traits::ScriptControlChan;
use timers::{Interval, NonInterval, TimerId, TimerManager};

use servo_msg::compositor_msg::ScriptListener;
use servo_msg::constellation_msg::LoadData;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::storage_task::StorageTask;
use servo_util::str::{DOMString,HTML_SPACE_CHARACTERS};

use js::jsapi::JS_EvaluateUCScript;
use js::jsapi::JSContext;
use js::jsapi::{JS_GC, JS_GetRuntime};
use js::jsval::{JSVal, UndefinedValue};
use js::rust::with_compartment;
use url::{Url, UrlParser};

use libc;
use serialize::base64::{FromBase64, ToBase64, STANDARD};
use std::cell::{Ref, RefMut};
use std::default::Default;
use std::rc::Rc;
use time;

#[dom_struct]
pub struct Window {
    eventtarget: EventTarget,
    script_chan: ScriptChan,
    control_chan: ScriptControlChan,
    console: MutNullableJS<Console>,
    location: MutNullableJS<Location>,
    navigator: MutNullableJS<Navigator>,
    image_cache_task: ImageCacheTask,
    compositor: DOMRefCell<Box<ScriptListener+'static>>,
    browser_context: DOMRefCell<Option<BrowserContext>>,
    page: Rc<Page>,
    performance: MutNullableJS<Performance>,
    navigation_start: u64,
    navigation_start_precise: f64,
    screen: MutNullableJS<Screen>,
    session_storage: MutNullableJS<Storage>,
    timers: TimerManager
}

impl Window {
    pub fn get_cx(&self) -> *mut JSContext {
        let js_info = self.page().js_info();
        (*js_info.as_ref().unwrap().js_context).ptr
    }

    pub fn script_chan<'a>(&'a self) -> &'a ScriptChan {
        &self.script_chan
    }

    pub fn control_chan<'a>(&'a self) -> &'a ScriptControlChan {
        &self.control_chan
    }

    pub fn image_cache_task<'a>(&'a self) -> &'a ImageCacheTask {
        &self.image_cache_task
    }

    pub fn compositor(&self) -> RefMut<Box<ScriptListener+'static>> {
        self.compositor.borrow_mut()
    }

    pub fn browser_context(&self) -> Ref<Option<BrowserContext>> {
        self.browser_context.borrow()
    }

    pub fn page<'a>(&'a self) -> &'a Page {
        &*self.page
    }

    pub fn navigation_start(&self) -> u64 {
        self.navigation_start
    }

    pub fn navigation_start_precise(&self) -> f64 {
        self.navigation_start_precise
    }

    pub fn get_url(&self) -> Url {
        self.page().get_url()
    }

    pub fn storage_task(&self) -> StorageTask {
        self.page().storage_task.clone()
    }
}

// http://www.whatwg.org/html/#atob
pub fn base64_btoa(btoa: DOMString) -> Fallible<DOMString> {
    let input = btoa.as_slice();
    // "The btoa() method must throw an InvalidCharacterError exception if
    //  the method's first argument contains any character whose code point
    //  is greater than U+00FF."
    if input.chars().any(|c: char| c > '\u00FF') {
        Err(InvalidCharacter)
    } else {
        // "Otherwise, the user agent must convert that argument to a
        //  sequence of octets whose nth octet is the eight-bit
        //  representation of the code point of the nth character of
        //  the argument,"
        let octets = input.chars().map(|c: char| c as u8).collect::<Vec<u8>>();

        // "and then must apply the base64 algorithm to that sequence of
        //  octets, and return the result. [RFC4648]"
        Ok(octets.as_slice().to_base64(STANDARD))
    }
}

// http://www.whatwg.org/html/#atob
pub fn base64_atob(atob: DOMString) -> Fallible<DOMString> {
    // "Let input be the string being parsed."
    let mut input = atob.as_slice();

    // "Remove all space characters from input."
    // serialize::base64::from_base64 ignores \r and \n,
    // but it treats the other space characters as
    // invalid input.
    fn is_html_space(c: char) -> bool {
        HTML_SPACE_CHARACTERS.iter().any(|&m| m == c)
    }
    let without_spaces = input.chars()
        .filter(|&c| ! is_html_space(c))
        .collect::<String>();
    input = without_spaces.as_slice();

    // "If the length of input divides by 4 leaving no remainder, then:
    //  if input ends with one or two U+003D EQUALS SIGN (=) characters,
    //  remove them from input."
    if input.len() % 4 == 0 {
        if input.ends_with("==") {
            input = input.slice_to(input.len() - 2)
        } else if input.ends_with("=") {
            input = input.slice_to(input.len() - 1)
        }
    }

    // "If the length of input divides by 4 leaving a remainder of 1,
    //  throw an InvalidCharacterError exception and abort these steps."
    if input.len() % 4 == 1 {
        return Err(InvalidCharacter)
    }

    // "If input contains a character that is not in the following list of
    //  characters and character ranges, throw an InvalidCharacterError
    //  exception and abort these steps:
    //
    //  U+002B PLUS SIGN (+)
    //  U+002F SOLIDUS (/)
    //  Alphanumeric ASCII characters"
    if input.chars()
        .find(|&c| !(c == '+' || c == '/' || c.is_alphanumeric()))
        .is_some() {
            return Err(InvalidCharacter)
        }

    match input.from_base64() {
        Ok(data) => Ok(data.iter().map(|&b| b as char).collect::<String>()),
        Err(..) => Err(InvalidCharacter)
    }
}

impl<'a> WindowMethods for JSRef<'a, Window> {
    fn Alert(self, s: DOMString) {
        // Right now, just print to the console
        println!("ALERT: {:s}", s);
    }

    fn Close(self) {
        let ScriptChan(ref chan) = self.script_chan;
        chan.send(ExitWindowMsg(self.page.id.clone()));
    }

    fn Document(self) -> Temporary<Document> {
        let frame = self.page().frame();
        Temporary::new(frame.as_ref().unwrap().document.clone())
    }

    fn Location(self) -> Temporary<Location> {
        if self.location.get().is_none() {
            let page = self.page.clone();
            let location = Location::new(self, page);
            self.location.assign(Some(location));
        }
        self.location.get().unwrap()
    }

    fn SessionStorage(self) -> Temporary<Storage> {
        if self.session_storage.get().is_none() {
            let session_storage = Storage::new(&global::Window(self));
            self.session_storage.assign(Some(session_storage));
        }
        self.session_storage.get().unwrap()
    }

    fn Console(self) -> Temporary<Console> {
        if self.console.get().is_none() {
            let console = Console::new(global::Window(self));
            self.console.assign(Some(console));
        }
        self.console.get().unwrap()
    }

    fn Navigator(self) -> Temporary<Navigator> {
        if self.navigator.get().is_none() {
            let navigator = Navigator::new(self);
            self.navigator.assign(Some(navigator));
        }
        self.navigator.get().unwrap()
    }

    fn SetTimeout(self, _cx: *mut JSContext, callback: Function, timeout: i32, args: Vec<JSVal>) -> i32 {
        self.timers.set_timeout_or_interval(callback,
                                            args,
                                            timeout,
                                            NonInterval,
                                            FromWindow(self.page.id.clone()),
                                            self.script_chan.clone())
    }

    fn ClearTimeout(self, handle: i32) {
        self.timers.clear_timeout_or_interval(handle);
    }

    fn SetInterval(self, _cx: *mut JSContext, callback: Function, timeout: i32, args: Vec<JSVal>) -> i32 {
        self.timers.set_timeout_or_interval(callback,
                                            args,
                                            timeout,
                                            Interval,
                                            FromWindow(self.page.id.clone()),
                                            self.script_chan.clone())
    }

    fn ClearInterval(self, handle: i32) {
        self.ClearTimeout(handle);
    }

    fn Window(self) -> Temporary<Window> {
        Temporary::from_rooted(self)
    }

    fn Self(self) -> Temporary<Window> {
        self.Window()
    }

    // http://www.whatwg.org/html/#dom-frames
    fn Frames(self) -> Temporary<Window> {
        self.Window()
    }

    fn Parent(self) -> Temporary<Window> {
        //TODO - Once we support iframes correctly this needs to return the parent frame
        self.Window()
    }

    fn Performance(self) -> Temporary<Performance> {
        if self.performance.get().is_none() {
            let performance = Performance::new(self);
            self.performance.assign(Some(performance));
        }
        self.performance.get().unwrap()
    }

    event_handler!(click, GetOnclick, SetOnclick)
    event_handler!(load, GetOnload, SetOnload)
    event_handler!(unload, GetOnunload, SetOnunload)
    error_event_handler!(error, GetOnerror, SetOnerror)

    fn Screen(self) -> Temporary<Screen> {
        if self.screen.get().is_none() {
            let screen = Screen::new(self);
            self.screen.assign(Some(screen));
        }
        self.screen.get().unwrap()
    }

    fn Debug(self, message: DOMString) {
        debug!("{:s}", message);
    }

    fn Gc(self) {
        unsafe {
            JS_GC(JS_GetRuntime(self.get_cx()));
        }
    }

    fn Btoa(self, btoa: DOMString) -> Fallible<DOMString> {
        base64_btoa(btoa)
    }

    fn Atob(self, atob: DOMString) -> Fallible<DOMString> {
        base64_atob(atob)
    }
}

impl Reflectable for Window {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        self.eventtarget.reflector()
    }
}

pub trait WindowHelpers {
    fn reflow(self);
    fn flush_layout(self);
    fn wait_until_safe_to_modify_dom(self);
    fn init_browser_context(self, doc: JSRef<Document>);
    fn load_url(self, href: DOMString);
    fn handle_fire_timer(self, timer_id: TimerId);
    fn evaluate_js_with_result(self, code: &str) -> JSVal;
    fn evaluate_script_with_result(self, code: &str, filename: &str) -> JSVal;
}

impl<'a> WindowHelpers for JSRef<'a, Window> {
    fn evaluate_js_with_result(self, code: &str) -> JSVal {
        self.evaluate_script_with_result(code, "")
    }

    fn evaluate_script_with_result(self, code: &str, filename: &str) -> JSVal {
        let global = self.reflector().get_jsobject();
        let code: Vec<u16> = code.as_slice().utf16_units().collect();
        let mut rval = UndefinedValue();
        let filename = filename.to_c_str();
        let cx = self.get_cx();

        with_compartment(cx, global, || {
            unsafe {
                if JS_EvaluateUCScript(cx, global, code.as_ptr(),
                                       code.len() as libc::c_uint,
                                       filename.as_ptr(), 1, &mut rval) == 0 {
                    debug!("error evaluating JS string");
                }
                rval
            }
        })
    }

    fn reflow(self) {
        self.page().damage();
    }

    fn flush_layout(self) {
        self.page().flush_layout(NoQuery);
    }

    fn wait_until_safe_to_modify_dom(self) {
        // FIXME: This disables concurrent layout while we are modifying the DOM, since
        //        our current architecture is entirely unsafe in the presence of races.
        self.page().join_layout();
    }

    fn init_browser_context(self, doc: JSRef<Document>) {
        *self.browser_context.borrow_mut() = Some(BrowserContext::new(doc));
    }

    /// Commence a new URL load which will either replace this window or scroll to a fragment.
    fn load_url(self, href: DOMString) {
        let base_url = self.page().get_url();
        debug!("current page url is {}", base_url);
        let url = UrlParser::new().base_url(&base_url).parse(href.as_slice());
        // FIXME: handle URL parse errors more gracefully.
        let url = url.unwrap();
        let ScriptChan(ref script_chan) = self.script_chan;
        if href.as_slice().starts_with("#") {
            script_chan.send(TriggerFragmentMsg(self.page.id, url));
        } else {
            script_chan.send(TriggerLoadMsg(self.page.id, LoadData::new(url)));
        }
    }

    fn handle_fire_timer(self, timer_id: TimerId) {
        self.timers.fire_timer(timer_id, self.clone());
        self.flush_layout();
    }
}

impl Window {
    pub fn new(cx: *mut JSContext,
               page: Rc<Page>,
               script_chan: ScriptChan,
               control_chan: ScriptControlChan,
               compositor: Box<ScriptListener+'static>,
               image_cache_task: ImageCacheTask)
               -> Temporary<Window> {
        let win = box Window {
            eventtarget: EventTarget::new_inherited(WindowTypeId),
            script_chan: script_chan,
            control_chan: control_chan,
            console: Default::default(),
            compositor: DOMRefCell::new(compositor),
            page: page,
            location: Default::default(),
            navigator: Default::default(),
            image_cache_task: image_cache_task,
            browser_context: DOMRefCell::new(None),
            performance: Default::default(),
            navigation_start: time::get_time().sec as u64,
            navigation_start_precise: time::precise_time_s(),
            screen: Default::default(),
            session_storage: Default::default(),
            timers: TimerManager::new()
        };

        WindowBinding::Wrap(cx, win)
    }
}
<commit_msg>Use MutNullableJS::or_init in Window.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::EventHandlerBinding::{OnErrorEventHandlerNonNull, EventHandlerNonNull};
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::WindowBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::error::{Fallible, InvalidCharacter};
use dom::bindings::global;
use dom::bindings::js::{MutNullableJS, JSRef, Temporary};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::browsercontext::BrowserContext;
use dom::console::Console;
use dom::document::Document;
use dom::eventtarget::{EventTarget, WindowTypeId, EventTargetHelpers};
use dom::location::Location;
use dom::navigator::Navigator;
use dom::performance::Performance;
use dom::screen::Screen;
use dom::storage::Storage;
use layout_interface::NoQuery;
use page::Page;
use script_task::{ExitWindowMsg, ScriptChan, TriggerLoadMsg, TriggerFragmentMsg};
use script_task::FromWindow;
use script_traits::ScriptControlChan;
use timers::{Interval, NonInterval, TimerId, TimerManager};

use servo_msg::compositor_msg::ScriptListener;
use servo_msg::constellation_msg::LoadData;
use servo_net::image_cache_task::ImageCacheTask;
use servo_net::storage_task::StorageTask;
use servo_util::str::{DOMString,HTML_SPACE_CHARACTERS};

use js::jsapi::JS_EvaluateUCScript;
use js::jsapi::JSContext;
use js::jsapi::{JS_GC, JS_GetRuntime};
use js::jsval::{JSVal, UndefinedValue};
use js::rust::with_compartment;
use url::{Url, UrlParser};

use libc;
use serialize::base64::{FromBase64, ToBase64, STANDARD};
use std::cell::{Ref, RefMut};
use std::default::Default;
use std::rc::Rc;
use time;

#[dom_struct]
pub struct Window {
    eventtarget: EventTarget,
    script_chan: ScriptChan,
    control_chan: ScriptControlChan,
    console: MutNullableJS<Console>,
    location: MutNullableJS<Location>,
    navigator: MutNullableJS<Navigator>,
    image_cache_task: ImageCacheTask,
    compositor: DOMRefCell<Box<ScriptListener+'static>>,
    browser_context: DOMRefCell<Option<BrowserContext>>,
    page: Rc<Page>,
    performance: MutNullableJS<Performance>,
    navigation_start: u64,
    navigation_start_precise: f64,
    screen: MutNullableJS<Screen>,
    session_storage: MutNullableJS<Storage>,
    timers: TimerManager
}

impl Window {
    pub fn get_cx(&self) -> *mut JSContext {
        let js_info = self.page().js_info();
        (*js_info.as_ref().unwrap().js_context).ptr
    }

    pub fn script_chan<'a>(&'a self) -> &'a ScriptChan {
        &self.script_chan
    }

    pub fn control_chan<'a>(&'a self) -> &'a ScriptControlChan {
        &self.control_chan
    }

    pub fn image_cache_task<'a>(&'a self) -> &'a ImageCacheTask {
        &self.image_cache_task
    }

    pub fn compositor(&self) -> RefMut<Box<ScriptListener+'static>> {
        self.compositor.borrow_mut()
    }

    pub fn browser_context(&self) -> Ref<Option<BrowserContext>> {
        self.browser_context.borrow()
    }

    pub fn page<'a>(&'a self) -> &'a Page {
        &*self.page
    }

    pub fn navigation_start(&self) -> u64 {
        self.navigation_start
    }

    pub fn navigation_start_precise(&self) -> f64 {
        self.navigation_start_precise
    }

    pub fn get_url(&self) -> Url {
        self.page().get_url()
    }

    pub fn storage_task(&self) -> StorageTask {
        self.page().storage_task.clone()
    }
}

// http://www.whatwg.org/html/#atob
pub fn base64_btoa(btoa: DOMString) -> Fallible<DOMString> {
    let input = btoa.as_slice();
    // "The btoa() method must throw an InvalidCharacterError exception if
    //  the method's first argument contains any character whose code point
    //  is greater than U+00FF."
    if input.chars().any(|c: char| c > '\u00FF') {
        Err(InvalidCharacter)
    } else {
        // "Otherwise, the user agent must convert that argument to a
        //  sequence of octets whose nth octet is the eight-bit
        //  representation of the code point of the nth character of
        //  the argument,"
        let octets = input.chars().map(|c: char| c as u8).collect::<Vec<u8>>();

        // "and then must apply the base64 algorithm to that sequence of
        //  octets, and return the result. [RFC4648]"
        Ok(octets.as_slice().to_base64(STANDARD))
    }
}

// http://www.whatwg.org/html/#atob
pub fn base64_atob(atob: DOMString) -> Fallible<DOMString> {
    // "Let input be the string being parsed."
    let mut input = atob.as_slice();

    // "Remove all space characters from input."
    // serialize::base64::from_base64 ignores \r and \n,
    // but it treats the other space characters as
    // invalid input.
    fn is_html_space(c: char) -> bool {
        HTML_SPACE_CHARACTERS.iter().any(|&m| m == c)
    }
    let without_spaces = input.chars()
        .filter(|&c| ! is_html_space(c))
        .collect::<String>();
    input = without_spaces.as_slice();

    // "If the length of input divides by 4 leaving no remainder, then:
    //  if input ends with one or two U+003D EQUALS SIGN (=) characters,
    //  remove them from input."
    if input.len() % 4 == 0 {
        if input.ends_with("==") {
            input = input.slice_to(input.len() - 2)
        } else if input.ends_with("=") {
            input = input.slice_to(input.len() - 1)
        }
    }

    // "If the length of input divides by 4 leaving a remainder of 1,
    //  throw an InvalidCharacterError exception and abort these steps."
    if input.len() % 4 == 1 {
        return Err(InvalidCharacter)
    }

    // "If input contains a character that is not in the following list of
    //  characters and character ranges, throw an InvalidCharacterError
    //  exception and abort these steps:
    //
    //  U+002B PLUS SIGN (+)
    //  U+002F SOLIDUS (/)
    //  Alphanumeric ASCII characters"
    if input.chars()
        .find(|&c| !(c == '+' || c == '/' || c.is_alphanumeric()))
        .is_some() {
            return Err(InvalidCharacter)
        }

    match input.from_base64() {
        Ok(data) => Ok(data.iter().map(|&b| b as char).collect::<String>()),
        Err(..) => Err(InvalidCharacter)
    }
}

impl<'a> WindowMethods for JSRef<'a, Window> {
    fn Alert(self, s: DOMString) {
        // Right now, just print to the console
        println!("ALERT: {:s}", s);
    }

    fn Close(self) {
        let ScriptChan(ref chan) = self.script_chan;
        chan.send(ExitWindowMsg(self.page.id.clone()));
    }

    fn Document(self) -> Temporary<Document> {
        let frame = self.page().frame();
        Temporary::new(frame.as_ref().unwrap().document.clone())
    }

    fn Location(self) -> Temporary<Location> {
        self.location.or_init(|| Location::new(self, self.page.clone()))
    }

    fn SessionStorage(self) -> Temporary<Storage> {
        self.session_storage.or_init(|| Storage::new(&global::Window(self)))
    }

    fn Console(self) -> Temporary<Console> {
        self.console.or_init(|| Console::new(global::Window(self)))
    }

    fn Navigator(self) -> Temporary<Navigator> {
        self.navigator.or_init(|| Navigator::new(self))
    }

    fn SetTimeout(self, _cx: *mut JSContext, callback: Function, timeout: i32, args: Vec<JSVal>) -> i32 {
        self.timers.set_timeout_or_interval(callback,
                                            args,
                                            timeout,
                                            NonInterval,
                                            FromWindow(self.page.id.clone()),
                                            self.script_chan.clone())
    }

    fn ClearTimeout(self, handle: i32) {
        self.timers.clear_timeout_or_interval(handle);
    }

    fn SetInterval(self, _cx: *mut JSContext, callback: Function, timeout: i32, args: Vec<JSVal>) -> i32 {
        self.timers.set_timeout_or_interval(callback,
                                            args,
                                            timeout,
                                            Interval,
                                            FromWindow(self.page.id.clone()),
                                            self.script_chan.clone())
    }

    fn ClearInterval(self, handle: i32) {
        self.ClearTimeout(handle);
    }

    fn Window(self) -> Temporary<Window> {
        Temporary::from_rooted(self)
    }

    fn Self(self) -> Temporary<Window> {
        self.Window()
    }

    // http://www.whatwg.org/html/#dom-frames
    fn Frames(self) -> Temporary<Window> {
        self.Window()
    }

    fn Parent(self) -> Temporary<Window> {
        //TODO - Once we support iframes correctly this needs to return the parent frame
        self.Window()
    }

    fn Performance(self) -> Temporary<Performance> {
        self.performance.or_init(|| Performance::new(self))
    }

    event_handler!(click, GetOnclick, SetOnclick)
    event_handler!(load, GetOnload, SetOnload)
    event_handler!(unload, GetOnunload, SetOnunload)
    error_event_handler!(error, GetOnerror, SetOnerror)

    fn Screen(self) -> Temporary<Screen> {
        self.screen.or_init(|| Screen::new(self))
    }

    fn Debug(self, message: DOMString) {
        debug!("{:s}", message);
    }

    fn Gc(self) {
        unsafe {
            JS_GC(JS_GetRuntime(self.get_cx()));
        }
    }

    fn Btoa(self, btoa: DOMString) -> Fallible<DOMString> {
        base64_btoa(btoa)
    }

    fn Atob(self, atob: DOMString) -> Fallible<DOMString> {
        base64_atob(atob)
    }
}

impl Reflectable for Window {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        self.eventtarget.reflector()
    }
}

pub trait WindowHelpers {
    fn reflow(self);
    fn flush_layout(self);
    fn wait_until_safe_to_modify_dom(self);
    fn init_browser_context(self, doc: JSRef<Document>);
    fn load_url(self, href: DOMString);
    fn handle_fire_timer(self, timer_id: TimerId);
    fn evaluate_js_with_result(self, code: &str) -> JSVal;
    fn evaluate_script_with_result(self, code: &str, filename: &str) -> JSVal;
}

impl<'a> WindowHelpers for JSRef<'a, Window> {
    fn evaluate_js_with_result(self, code: &str) -> JSVal {
        self.evaluate_script_with_result(code, "")
    }

    fn evaluate_script_with_result(self, code: &str, filename: &str) -> JSVal {
        let global = self.reflector().get_jsobject();
        let code: Vec<u16> = code.as_slice().utf16_units().collect();
        let mut rval = UndefinedValue();
        let filename = filename.to_c_str();
        let cx = self.get_cx();

        with_compartment(cx, global, || {
            unsafe {
                if JS_EvaluateUCScript(cx, global, code.as_ptr(),
                                       code.len() as libc::c_uint,
                                       filename.as_ptr(), 1, &mut rval) == 0 {
                    debug!("error evaluating JS string");
                }
                rval
            }
        })
    }

    fn reflow(self) {
        self.page().damage();
    }

    fn flush_layout(self) {
        self.page().flush_layout(NoQuery);
    }

    fn wait_until_safe_to_modify_dom(self) {
        // FIXME: This disables concurrent layout while we are modifying the DOM, since
        //        our current architecture is entirely unsafe in the presence of races.
        self.page().join_layout();
    }

    fn init_browser_context(self, doc: JSRef<Document>) {
        *self.browser_context.borrow_mut() = Some(BrowserContext::new(doc));
    }

    /// Commence a new URL load which will either replace this window or scroll to a fragment.
    fn load_url(self, href: DOMString) {
        let base_url = self.page().get_url();
        debug!("current page url is {}", base_url);
        let url = UrlParser::new().base_url(&base_url).parse(href.as_slice());
        // FIXME: handle URL parse errors more gracefully.
        let url = url.unwrap();
        let ScriptChan(ref script_chan) = self.script_chan;
        if href.as_slice().starts_with("#") {
            script_chan.send(TriggerFragmentMsg(self.page.id, url));
        } else {
            script_chan.send(TriggerLoadMsg(self.page.id, LoadData::new(url)));
        }
    }

    fn handle_fire_timer(self, timer_id: TimerId) {
        self.timers.fire_timer(timer_id, self.clone());
        self.flush_layout();
    }
}

impl Window {
    pub fn new(cx: *mut JSContext,
               page: Rc<Page>,
               script_chan: ScriptChan,
               control_chan: ScriptControlChan,
               compositor: Box<ScriptListener+'static>,
               image_cache_task: ImageCacheTask)
               -> Temporary<Window> {
        let win = box Window {
            eventtarget: EventTarget::new_inherited(WindowTypeId),
            script_chan: script_chan,
            control_chan: control_chan,
            console: Default::default(),
            compositor: DOMRefCell::new(compositor),
            page: page,
            location: Default::default(),
            navigator: Default::default(),
            image_cache_task: image_cache_task,
            browser_context: DOMRefCell::new(None),
            performance: Default::default(),
            navigation_start: time::get_time().sec as u64,
            navigation_start_precise: time::precise_time_s(),
            screen: Default::default(),
            session_storage: Default::default(),
            timers: TimerManager::new()
        };

        WindowBinding::Wrap(cx, win)
    }
}
<|endoftext|>


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

use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLScriptElementCast};
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable, Root};
use dom::comment::Comment;
use dom::document::{Document, DocumentHelpers};
use dom::documenttype::DocumentType;
use dom::element::{Element, AttributeHandlers, ElementHelpers, ParserCreated};
use dom::htmlscriptelement::HTMLScriptElement;
use dom::htmlscriptelement::HTMLScriptElementHelpers;
use dom::node::{Node, NodeHelpers, TrustedNodeAddress};
use dom::servohtmlparser;
use dom::servohtmlparser::ServoHTMLParser;
use dom::text::Text;
use page::Page;
use parse::Parser;

use encoding::all::UTF_8;
use encoding::types::{Encoding, DecodeReplace};

use servo_net::resource_task::{Load, LoadData, Payload, Done, ResourceTask};
use servo_msg::constellation_msg::LoadData as MsgLoadData;
use servo_util::task_state;
use servo_util::task_state::IN_HTML_PARSER;
use std::ascii::AsciiExt;
use std::comm::channel;
use std::fmt::{mod, Show};
use std::str::MaybeOwned;
use url::Url;
use time::{Tm, strptime};
use html5ever::Attribute;
use html5ever::tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText};
use string_cache::QualName;
use hyper::header::{Header, HeaderFormat};
use hyper::header::common::util as header_util;

pub enum HTMLInput {
    InputString(String),
    InputUrl(Url),
}

//FIXME(seanmonstar): uplift to Hyper
#[deriving(Clone)]
struct LastModified(pub Tm);

impl Header for LastModified {
    #[inline]
    fn header_name(_: Option<LastModified>) -> &'static str {
        "Last-Modified"
    }

    // Parses an RFC 2616 compliant date/time string,
    fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> {
        header_util::from_one_raw_str(raw).and_then(|s: String| {
            let s = s.as_slice();
            strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
                strptime(s, "%A, %d-%b-%y %T %Z")
            }).or_else(|_| {
                strptime(s, "%c")
            }).ok().map(|tm| LastModified(tm))
        })
    }
}

impl HeaderFormat for LastModified {
    // a localized date/time string in a format suitable
    // for document.lastModified.
    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let LastModified(ref tm) = *self;
        match tm.tm_gmtoff {
            0 => tm.rfc822().fmt(f),
            _ => tm.to_utc().rfc822().fmt(f)
        }
    }
}

fn dom_last_modified(tm: &Tm) -> String {
    tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap()
}

trait SinkHelpers {
    fn get_or_create(&self, child: NodeOrText<TrustedNodeAddress>) -> Temporary<Node>;
}

impl SinkHelpers for servohtmlparser::Sink {
    fn get_or_create(&self, child: NodeOrText<TrustedNodeAddress>) -> Temporary<Node> {
        match child {
            AppendNode(n) => Temporary::new(unsafe { JS::from_trusted_node_address(n) }),
            AppendText(t) => {
                let doc = self.document.root();
                let text = Text::new(t, *doc);
                NodeCast::from_temporary(text)
            }
        }
    }
}

impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
    fn get_document(&mut self) -> TrustedNodeAddress {
        let doc = self.document.root();
        let node: JSRef<Node> = NodeCast::from_ref(*doc);
        node.to_trusted_node_address()
    }

    fn same_node(&self, x: TrustedNodeAddress, y: TrustedNodeAddress) -> bool {
        x == y
    }

    fn elem_name(&self, target: TrustedNodeAddress) -> QualName {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
        let elem: JSRef<Element> = ElementCast::to_ref(*node)
            .expect("tried to get name of non-Element in HTML parsing");
        QualName {
            ns: elem.namespace().clone(),
            local: elem.local_name().clone(),
        }
    }

    fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>)
            -> TrustedNodeAddress {
        let doc = self.document.root();
        let elem = Element::create(name, None, *doc, ParserCreated).root();

        for attr in attrs.into_iter() {
            elem.set_attribute_from_parser(attr.name, attr.value, None);
        }

        let node: JSRef<Node> = NodeCast::from_ref(*elem);
        node.to_trusted_node_address()
    }

    fn create_comment(&mut self, text: String) -> TrustedNodeAddress {
        let doc = self.document.root();
        let comment = Comment::new(text, *doc);
        let node: Root<Node> = NodeCast::from_temporary(comment).root();
        node.to_trusted_node_address()
    }

    fn append_before_sibling(&mut self,
            sibling: TrustedNodeAddress,
            new_node: NodeOrText<TrustedNodeAddress>) -> Result<(), NodeOrText<TrustedNodeAddress>> {
        // If there is no parent, return the node to the parser.
        let sibling: Root<Node> = unsafe { JS::from_trusted_node_address(sibling).root() };
        let parent = match sibling.parent_node() {
            Some(p) => p.root(),
            None => return Err(new_node),
        };

        let child = self.get_or_create(new_node).root();
        assert!(parent.InsertBefore(*child, Some(*sibling)).is_ok());
        Ok(())
    }

    fn parse_error(&mut self, msg: MaybeOwned<'static>) {
        debug!("Parse error: {:s}", msg);
    }

    fn set_quirks_mode(&mut self, mode: QuirksMode) {
        let doc = self.document.root();
        doc.set_quirks_mode(mode);
    }

    fn append(&mut self, parent: TrustedNodeAddress, child: NodeOrText<TrustedNodeAddress>) {
        let parent: Root<Node> = unsafe { JS::from_trusted_node_address(parent).root() };
        let child = self.get_or_create(child).root();

        // FIXME(#3701): Use a simpler algorithm and merge adjacent text nodes
        assert!(parent.AppendChild(*child).is_ok());
    }

    fn append_doctype_to_document(&mut self, name: String, public_id: String, system_id: String) {
        let doc = self.document.root();
        let doc_node: JSRef<Node> = NodeCast::from_ref(*doc);
        let doctype = DocumentType::new(name, Some(public_id), Some(system_id), *doc);
        let node: Root<Node> = NodeCast::from_temporary(doctype).root();

        assert!(doc_node.AppendChild(*node).is_ok());
    }

    fn add_attrs_if_missing(&mut self, target: TrustedNodeAddress, attrs: Vec<Attribute>) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
        let elem: JSRef<Element> = ElementCast::to_ref(*node)
            .expect("tried to set attrs on non-Element in HTML parsing");
        for attr in attrs.into_iter() {
            elem.set_attribute_from_parser(attr.name, attr.value, None);
        }
    }

    fn remove_from_parent(&mut self, _target: TrustedNodeAddress) {
        error!("remove_from_parent not implemented!");
    }

    fn mark_script_already_started(&mut self, node: TrustedNodeAddress) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
        let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node);
        script.map(|script| script.mark_already_started());
    }

    fn complete_script(&mut self, node: TrustedNodeAddress) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
        let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node);
        script.map(|script| script.prepare());
    }
}

// The url from msg_load_data is ignored here
pub fn parse_html(page: &Page,
                  document: JSRef<Document>,
                  input: HTMLInput,
                  resource_task: ResourceTask,
                  msg_load_data: MsgLoadData) {
    let (base_url, load_response) = match input {
        InputUrl(ref url) => {
            // Wait for the LoadResponse so that the parser knows the final URL.
            let (input_chan, input_port) = channel();
            let mut load_data = LoadData::new(url.clone(), input_chan);
            load_data.headers = msg_load_data.headers;
            load_data.method = msg_load_data.method;
            load_data.data = msg_load_data.data;
            resource_task.send(Load(load_data));

            let load_response = input_port.recv();

            load_response.metadata.headers.as_ref().map(|headers| {
                headers.get().map(|&LastModified(ref tm)| {
                    document.set_last_modified(dom_last_modified(tm));
                });
            });

            let base_url = load_response.metadata.final_url.clone();

            {
                // Store the final URL before we start parsing, so that DOM routines
                // (e.g. HTMLImageElement::update_image) can resolve relative URLs
                // correctly.
                *page.mut_url() = Some((base_url.clone(), true));
            }

            (Some(base_url), Some(load_response))
        },
        InputString(_) => {
            match *page.url() {
                Some((ref page_url, _)) => (Some(page_url.clone()), None),
                None => (None, None),
            }
        },
    };

    let parser = ServoHTMLParser::new(base_url.clone(), document).root();
    let parser: JSRef<ServoHTMLParser> = *parser;

    task_state::enter(IN_HTML_PARSER);

    match input {
        InputString(s) => {
            parser.parse_chunk(s);
        }
        InputUrl(url) => {
            let load_response = load_response.unwrap();
            match load_response.metadata.content_type {
                Some((ref t, _)) if t.as_slice().eq_ignore_ascii_case("image") => {
                    let page = format!("", base_url.as_ref().unwrap().serialize());
                    parser.parse_chunk(page);
                },
                _ => {
                    for msg in load_response.progress_port.iter() {
                        match msg {
                            Payload(data) => {
                                // FIXME: use Vec<u8> (html5ever #34)
                                let data = UTF_8.decode(data.as_slice(), DecodeReplace).unwrap();
                                parser.parse_chunk(data);
                            }
                            Done(Err(err)) => {
                                panic!("Failed to load page URL {:s}, error: {:s}", url.serialize(), err);
                            }
                            Done(Ok(())) => break,
                        }
                    }
                }
            }
        }
    }

    parser.finish();

    task_state::exit(IN_HTML_PARSER);

    debug!("finished parsing");
}
<commit_msg>Simplify the LoadData creation in parse_html.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, HTMLScriptElementCast};
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable, Root};
use dom::comment::Comment;
use dom::document::{Document, DocumentHelpers};
use dom::documenttype::DocumentType;
use dom::element::{Element, AttributeHandlers, ElementHelpers, ParserCreated};
use dom::htmlscriptelement::HTMLScriptElement;
use dom::htmlscriptelement::HTMLScriptElementHelpers;
use dom::node::{Node, NodeHelpers, TrustedNodeAddress};
use dom::servohtmlparser;
use dom::servohtmlparser::ServoHTMLParser;
use dom::text::Text;
use page::Page;
use parse::Parser;

use encoding::all::UTF_8;
use encoding::types::{Encoding, DecodeReplace};

use servo_net::resource_task::{Load, LoadData, Payload, Done, ResourceTask};
use servo_msg::constellation_msg::LoadData as MsgLoadData;
use servo_util::task_state;
use servo_util::task_state::IN_HTML_PARSER;
use std::ascii::AsciiExt;
use std::comm::channel;
use std::fmt::{mod, Show};
use std::str::MaybeOwned;
use url::Url;
use time::{Tm, strptime};
use html5ever::Attribute;
use html5ever::tree_builder::{TreeSink, QuirksMode, NodeOrText, AppendNode, AppendText};
use string_cache::QualName;
use hyper::header::{Header, HeaderFormat};
use hyper::header::common::util as header_util;

pub enum HTMLInput {
    InputString(String),
    InputUrl(Url),
}

//FIXME(seanmonstar): uplift to Hyper
#[deriving(Clone)]
struct LastModified(pub Tm);

impl Header for LastModified {
    #[inline]
    fn header_name(_: Option<LastModified>) -> &'static str {
        "Last-Modified"
    }

    // Parses an RFC 2616 compliant date/time string,
    fn parse_header(raw: &[Vec<u8>]) -> Option<LastModified> {
        header_util::from_one_raw_str(raw).and_then(|s: String| {
            let s = s.as_slice();
            strptime(s, "%a, %d %b %Y %T %Z").or_else(|_| {
                strptime(s, "%A, %d-%b-%y %T %Z")
            }).or_else(|_| {
                strptime(s, "%c")
            }).ok().map(|tm| LastModified(tm))
        })
    }
}

impl HeaderFormat for LastModified {
    // a localized date/time string in a format suitable
    // for document.lastModified.
    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let LastModified(ref tm) = *self;
        match tm.tm_gmtoff {
            0 => tm.rfc822().fmt(f),
            _ => tm.to_utc().rfc822().fmt(f)
        }
    }
}

fn dom_last_modified(tm: &Tm) -> String {
    tm.to_local().strftime("%m/%d/%Y %H:%M:%S").unwrap()
}

trait SinkHelpers {
    fn get_or_create(&self, child: NodeOrText<TrustedNodeAddress>) -> Temporary<Node>;
}

impl SinkHelpers for servohtmlparser::Sink {
    fn get_or_create(&self, child: NodeOrText<TrustedNodeAddress>) -> Temporary<Node> {
        match child {
            AppendNode(n) => Temporary::new(unsafe { JS::from_trusted_node_address(n) }),
            AppendText(t) => {
                let doc = self.document.root();
                let text = Text::new(t, *doc);
                NodeCast::from_temporary(text)
            }
        }
    }
}

impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
    fn get_document(&mut self) -> TrustedNodeAddress {
        let doc = self.document.root();
        let node: JSRef<Node> = NodeCast::from_ref(*doc);
        node.to_trusted_node_address()
    }

    fn same_node(&self, x: TrustedNodeAddress, y: TrustedNodeAddress) -> bool {
        x == y
    }

    fn elem_name(&self, target: TrustedNodeAddress) -> QualName {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
        let elem: JSRef<Element> = ElementCast::to_ref(*node)
            .expect("tried to get name of non-Element in HTML parsing");
        QualName {
            ns: elem.namespace().clone(),
            local: elem.local_name().clone(),
        }
    }

    fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>)
            -> TrustedNodeAddress {
        let doc = self.document.root();
        let elem = Element::create(name, None, *doc, ParserCreated).root();

        for attr in attrs.into_iter() {
            elem.set_attribute_from_parser(attr.name, attr.value, None);
        }

        let node: JSRef<Node> = NodeCast::from_ref(*elem);
        node.to_trusted_node_address()
    }

    fn create_comment(&mut self, text: String) -> TrustedNodeAddress {
        let doc = self.document.root();
        let comment = Comment::new(text, *doc);
        let node: Root<Node> = NodeCast::from_temporary(comment).root();
        node.to_trusted_node_address()
    }

    fn append_before_sibling(&mut self,
            sibling: TrustedNodeAddress,
            new_node: NodeOrText<TrustedNodeAddress>) -> Result<(), NodeOrText<TrustedNodeAddress>> {
        // If there is no parent, return the node to the parser.
        let sibling: Root<Node> = unsafe { JS::from_trusted_node_address(sibling).root() };
        let parent = match sibling.parent_node() {
            Some(p) => p.root(),
            None => return Err(new_node),
        };

        let child = self.get_or_create(new_node).root();
        assert!(parent.InsertBefore(*child, Some(*sibling)).is_ok());
        Ok(())
    }

    fn parse_error(&mut self, msg: MaybeOwned<'static>) {
        debug!("Parse error: {:s}", msg);
    }

    fn set_quirks_mode(&mut self, mode: QuirksMode) {
        let doc = self.document.root();
        doc.set_quirks_mode(mode);
    }

    fn append(&mut self, parent: TrustedNodeAddress, child: NodeOrText<TrustedNodeAddress>) {
        let parent: Root<Node> = unsafe { JS::from_trusted_node_address(parent).root() };
        let child = self.get_or_create(child).root();

        // FIXME(#3701): Use a simpler algorithm and merge adjacent text nodes
        assert!(parent.AppendChild(*child).is_ok());
    }

    fn append_doctype_to_document(&mut self, name: String, public_id: String, system_id: String) {
        let doc = self.document.root();
        let doc_node: JSRef<Node> = NodeCast::from_ref(*doc);
        let doctype = DocumentType::new(name, Some(public_id), Some(system_id), *doc);
        let node: Root<Node> = NodeCast::from_temporary(doctype).root();

        assert!(doc_node.AppendChild(*node).is_ok());
    }

    fn add_attrs_if_missing(&mut self, target: TrustedNodeAddress, attrs: Vec<Attribute>) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
        let elem: JSRef<Element> = ElementCast::to_ref(*node)
            .expect("tried to set attrs on non-Element in HTML parsing");
        for attr in attrs.into_iter() {
            elem.set_attribute_from_parser(attr.name, attr.value, None);
        }
    }

    fn remove_from_parent(&mut self, _target: TrustedNodeAddress) {
        error!("remove_from_parent not implemented!");
    }

    fn mark_script_already_started(&mut self, node: TrustedNodeAddress) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
        let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node);
        script.map(|script| script.mark_already_started());
    }

    fn complete_script(&mut self, node: TrustedNodeAddress) {
        let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
        let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node);
        script.map(|script| script.prepare());
    }
}

// The url from msg_load_data is ignored here
pub fn parse_html(page: &Page,
                  document: JSRef<Document>,
                  input: HTMLInput,
                  resource_task: ResourceTask,
                  msg_load_data: MsgLoadData) {
    let (base_url, load_response) = match input {
        InputUrl(ref url) => {
            // Wait for the LoadResponse so that the parser knows the final URL.
            let (input_chan, input_port) = channel();
            resource_task.send(Load(LoadData {
                url: url.clone(),
                method: msg_load_data.method,
                headers: msg_load_data.headers,
                data: msg_load_data.data,
                cors: None,
                consumer: input_chan,
            }));

            let load_response = input_port.recv();

            load_response.metadata.headers.as_ref().map(|headers| {
                headers.get().map(|&LastModified(ref tm)| {
                    document.set_last_modified(dom_last_modified(tm));
                });
            });

            let base_url = load_response.metadata.final_url.clone();

            {
                // Store the final URL before we start parsing, so that DOM routines
                // (e.g. HTMLImageElement::update_image) can resolve relative URLs
                // correctly.
                *page.mut_url() = Some((base_url.clone(), true));
            }

            (Some(base_url), Some(load_response))
        },
        InputString(_) => {
            match *page.url() {
                Some((ref page_url, _)) => (Some(page_url.clone()), None),
                None => (None, None),
            }
        },
    };

    let parser = ServoHTMLParser::new(base_url.clone(), document).root();
    let parser: JSRef<ServoHTMLParser> = *parser;

    task_state::enter(IN_HTML_PARSER);

    match input {
        InputString(s) => {
            parser.parse_chunk(s);
        }
        InputUrl(url) => {
            let load_response = load_response.unwrap();
            match load_response.metadata.content_type {
                Some((ref t, _)) if t.as_slice().eq_ignore_ascii_case("image") => {
                    let page = format!("", base_url.as_ref().unwrap().serialize());
                    parser.parse_chunk(page);
                },
                _ => {
                    for msg in load_response.progress_port.iter() {
                        match msg {
                            Payload(data) => {
                                // FIXME: use Vec<u8> (html5ever #34)
                                let data = UTF_8.decode(data.as_slice(), DecodeReplace).unwrap();
                                parser.parse_chunk(data);
                            }
                            Done(Err(err)) => {
                                panic!("Failed to load page URL {:s}, error: {:s}", url.serialize(), err);
                            }
                            Done(Ok(())) => break,
                        }
                    }
                }
            }
        }
    }

    parser.finish();

    task_state::exit(IN_HTML_PARSER);

    debug!("finished parsing");
}
<|endoftext|>