<commit_before>// Copyright (c) 2018 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use clap;
use std::fs;
use std::io::Write;

use common::ui::{UI, Status};
use export_docker;
use export_docker::Result;
use export_k8s::{Manifest, ManifestJson};

use chartfile::ChartFile;
use values::Values;

pub struct Chart<'a> {
    name: String,
    chartfile: ChartFile,
    manifest_template: ManifestJson,
    values: Values,
    ui: &'a mut UI,
}

impl<'a> Chart<'a> {
    pub fn new_for_cli_matches(ui: &'a mut UI, matches: &clap::ArgMatches) -> Result<Self> {
        let image = if !matches.is_present("NO_DOCKER_IMAGE") {
            export_docker::export_for_cli_matches(ui, &matches)?
        } else {
            None
        };
        let manifest = Manifest::new_from_cli_matches(ui, &matches, image)?;

        let name = matches
            .value_of("CHART")
            .unwrap_or(&manifest.metadata_name)
            .to_string();
        let version = matches.value_of("VERSION");
        let description = matches.value_of("DESCRIPTION");
        let chartfile = ChartFile::new(&name, version, description);

        Ok(Self::new_for_manifest(manifest, name, chartfile, ui))
    }

    fn new_for_manifest(
        manifest: Manifest,
        name: String,
        chartfile: ChartFile,
        ui: &'a mut UI,
    ) -> Self {
        let main = json!({
            "metadata_name": "{{.Values.metadataName}}",
            "image": "{{.Values.imageName}}",
            "count": "{{.Values.instanceCount}}",
            "service_topology": "{{.Values.serviceTopology}}",
            "service_group": manifest.service_group.clone().map(|_| "{{.Values.serviceGroup}}"),
            "config": manifest.config
                .clone()
                .map(|_| "{{.Values.config}}"),
            "ring_secret_name": manifest.ring_secret_name
                .clone()
                .map(|_| "{{.Values.ringSecretName}}"),
            "bind": !manifest.binds.is_empty(),
        });

        let mut values = Values::new();
        values.add_entry("metadataName", &manifest.metadata_name);
        values.add_entry("imageName", &manifest.image);
        values.add_entry("instanceCount", &manifest.count.to_string());
        values.add_entry("serviceTopology", &manifest.service_topology.to_string());
        if let Some(ref group) = manifest.service_group {
            values.add_entry("serviceGroup", group);
        }
        if let Some(ref config) = manifest.config {
            values.add_entry("config", config);
        }
        if let Some(ref name) = manifest.ring_secret_name {
            values.add_entry("ringSecretName", name);
        }

        let mut binds = Vec::new();
        let mut i = 0;
        for bind in &manifest.binds {
            let name_var = format!("bindName{}", i);
            let service_var = format!("bindService{}", i);
            let group_var = format!("bindGroup{}", i);
            i = i + 1;

            values.add_entry(&name_var, &bind.name);
            values.add_entry(&service_var, &bind.service_group.service());
            values.add_entry(&group_var, &bind.service_group.group());

            let json = json!({
                "name": format!("{{{{.Values.{}}}}}", name_var),
                "service": format!("{{{{.Values.{}}}}}", service_var),
                "group": format!("{{{{.Values.{}}}}}", group_var),
            });

            binds.push(json);
        }

        let manifest_template = ManifestJson {
            main: main,
            binds: binds,
        };

        Chart {
            name,
            chartfile,
            manifest_template,
            values,
            ui,
        }
    }

    pub fn generate(mut self) -> Result<()> {
        self.ui.status(
            Status::Creating,
            format!("directory `{}`", self.name),
        )?;
        fs::create_dir_all(&self.name)?;

        self.generate_chartfile()?;

        let template_path = format!("{}/{}", self.name, "templates");
        self.ui.status(
            Status::Creating,
            format!("directory `{}`", template_path),
        )?;

        self.generate_values()?;

        fs::create_dir_all(&template_path)?;
        self.generate_manifest_template(&template_path)
    }

    pub fn generate_chartfile(&mut self) -> Result<()> {
        let path = format!("{}/Chart.yaml", self.name);
        self.ui.status(Status::Creating, format!("file `{}`", path))?;
        let mut write = fs::File::create(path)?;
        let out = self.chartfile.into_string()?;

        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn generate_manifest_template(self, template_path: &str) -> Result<()> {
        let manifest_path = format!("{}/{}.yaml", template_path, self.name);
        self.ui.status(
            Status::Creating,
            format!("file `{}`", manifest_path),
        )?;
        let mut write = fs::File::create(manifest_path)?;
        let out: String = self.manifest_template.into();

        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn generate_values(&mut self) -> Result<()> {
        let path = format!("{}/values.yaml", self.name);
        self.ui.status(Status::Creating, format!("file `{}`", path))?;
        let mut write = fs::File::create(path)?;

        self.values.generate(&mut write)?;

        Ok(())
    }
}
<commit_msg>pkg-export-helm: Refactor Chart::generate()<commit_after>// Copyright (c) 2018 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use clap;
use std::fs;
use std::io::Write;

use common::ui::{UI, Status};
use export_docker;
use export_docker::Result;
use export_k8s::{Manifest, ManifestJson};

use chartfile::ChartFile;
use values::Values;

pub struct Chart<'a> {
    name: String,
    chartfile: ChartFile,
    manifest_template: ManifestJson,
    values: Values,
    ui: &'a mut UI,
}

impl<'a> Chart<'a> {
    pub fn new_for_cli_matches(ui: &'a mut UI, matches: &clap::ArgMatches) -> Result<Self> {
        let image = if !matches.is_present("NO_DOCKER_IMAGE") {
            export_docker::export_for_cli_matches(ui, &matches)?
        } else {
            None
        };
        let manifest = Manifest::new_from_cli_matches(ui, &matches, image)?;

        let name = matches
            .value_of("CHART")
            .unwrap_or(&manifest.metadata_name)
            .to_string();
        let version = matches.value_of("VERSION");
        let description = matches.value_of("DESCRIPTION");
        let chartfile = ChartFile::new(&name, version, description);

        Ok(Self::new_for_manifest(manifest, name, chartfile, ui))
    }

    fn new_for_manifest(
        manifest: Manifest,
        name: String,
        chartfile: ChartFile,
        ui: &'a mut UI,
    ) -> Self {
        let main = json!({
            "metadata_name": "{{.Values.metadataName}}",
            "image": "{{.Values.imageName}}",
            "count": "{{.Values.instanceCount}}",
            "service_topology": "{{.Values.serviceTopology}}",
            "service_group": manifest.service_group.clone().map(|_| "{{.Values.serviceGroup}}"),
            "config": manifest.config
                .clone()
                .map(|_| "{{.Values.config}}"),
            "ring_secret_name": manifest.ring_secret_name
                .clone()
                .map(|_| "{{.Values.ringSecretName}}"),
            "bind": !manifest.binds.is_empty(),
        });

        let mut values = Values::new();
        values.add_entry("metadataName", &manifest.metadata_name);
        values.add_entry("imageName", &manifest.image);
        values.add_entry("instanceCount", &manifest.count.to_string());
        values.add_entry("serviceTopology", &manifest.service_topology.to_string());
        if let Some(ref group) = manifest.service_group {
            values.add_entry("serviceGroup", group);
        }
        if let Some(ref config) = manifest.config {
            values.add_entry("config", config);
        }
        if let Some(ref name) = manifest.ring_secret_name {
            values.add_entry("ringSecretName", name);
        }

        let mut binds = Vec::new();
        let mut i = 0;
        for bind in &manifest.binds {
            let name_var = format!("bindName{}", i);
            let service_var = format!("bindService{}", i);
            let group_var = format!("bindGroup{}", i);
            i = i + 1;

            values.add_entry(&name_var, &bind.name);
            values.add_entry(&service_var, &bind.service_group.service());
            values.add_entry(&group_var, &bind.service_group.group());

            let json = json!({
                "name": format!("{{{{.Values.{}}}}}", name_var),
                "service": format!("{{{{.Values.{}}}}}", service_var),
                "group": format!("{{{{.Values.{}}}}}", group_var),
            });

            binds.push(json);
        }

        let manifest_template = ManifestJson {
            main: main,
            binds: binds,
        };

        Chart {
            name,
            chartfile,
            manifest_template,
            values,
            ui,
        }
    }

    pub fn generate(mut self) -> Result<()> {
        self.ui.status(
            Status::Creating,
            format!("directory `{}`", self.name),
        )?;
        fs::create_dir_all(&self.name)?;

        self.generate_chartfile()?;

        self.generate_values()?;

        self.generate_manifest_template()
    }

    pub fn generate_chartfile(&mut self) -> Result<()> {
        let path = format!("{}/Chart.yaml", self.name);
        self.ui.status(Status::Creating, format!("file `{}`", path))?;
        let mut write = fs::File::create(path)?;
        let out = self.chartfile.into_string()?;

        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn generate_manifest_template(self) -> Result<()> {
        let template_path = format!("{}/{}", self.name, "templates");
        self.ui.status(
            Status::Creating,
            format!("directory `{}`", template_path),
        )?;
        fs::create_dir_all(&template_path)?;

        let manifest_path = format!("{}/{}.yaml", template_path, self.name);
        self.ui.status(
            Status::Creating,
            format!("file `{}`", manifest_path),
        )?;
        let mut write = fs::File::create(manifest_path)?;
        let out: String = self.manifest_template.into();

        write.write(out.as_bytes())?;

        Ok(())
    }

    pub fn generate_values(&mut self) -> Result<()> {
        let path = format!("{}/values.yaml", self.name);
        self.ui.status(Status::Creating, format!("file `{}`", path))?;
        let mut write = fs::File::create(path)?;

        self.values.generate(&mut write)?;

        Ok(())
    }
}
<|endoftext|>


<commit_before>/* CPU, Graphics and Memory core */

//enum mode = {SCHIP, CHIP}; /* differentiate between CHIP and SCHIP modes */

static MAX_RAM : u16 = 4096;

struct CPU {
    registers : [u8, ..16], /* 16 8 bit general purpose registers */
    mem : [u8, .. 0xFFF], /* 4096bytes of memory */
    i : u16, /* 16 bit index register */
    pc: u16, /* Program counter */
    sp: u16, /* Stack Pointer */
    stack : [u16, ..16], /* 16 stack frames */
    sound_timer : u8,
    delay_timer : u8,
    hp_48_flags: [u16, ..8] /*SCHIP */

}

fn dec_pc(pc:u16) -> uint {
    ((pc - 1) % MAX_RAM) as uint
}

fn dec_pc_n(pc:u16, n:u16) -> uint {
    ((pc - n) % MAX_RAM) as uint
}

fn inc_pc(pc:u16) -> uint {
    ((pc + 1) % MAX_RAM) as uint
}

fn inc_pc_n(pc:u16, n:u16) -> uint {
    ((pc + n) % MAX_RAM) as uint
}

impl CPU {

    fn call(&self) {
        self.pc = ((self.mem[dec_pc_n(self.pc, 2)]
            & 0x0F) << 8) as u16 | self.mem[dec_pc(self.pc)] as u16;
    }
}

fn main() {

    print!("hello");
}

<commit_msg>Added decoding functionality to perform the correct function for the specified opcode<commit_after>use std::rand::random;
use graphics::Graphics;
/* CPU, Graphics and Memory core */

mod graphics;

//enum mode = {SCHIP, CHIP}; /* differentiate between CHIP and SCHIP modes */

static U12_MAX : u16 = 4096;
static FLAG : uint = 15;

struct CPU {
    registers : [u8, ..16], /* 16 8 bit general purpose registers */
    mem : [u8, .. 0xFFF], /* 4096bytes of memory */
    I : u16, /* 16 bit index register */
    pc: u16, /* Program counter */
    sp: uint, /* Stack Pointer */
    stack : [u16, ..16], /* 16 stack frames */
    sound_timer : u8,
    delay_timer : u8,
    hp_48_flags: [u16, ..8], /*SCHIP */
    opcode : u16,
    graphics :Graphics

}

fn dec_u12(val:u16) -> uint {
    ((val - 1) % U12_MAX) as uint
}

fn dec_u12_n(val:u16, n:u16) -> uint {
    ((val - n) % U12_MAX) as uint
}

fn inc_u12(val:u16) -> uint {
    ((val + 1) % U12_MAX) as uint
}

fn inc_u12_n(val:u16, n:u16) -> uint {
    ((val + n) % U12_MAX) as uint
}

/* returns 1 if true, 0 if false */
fn bool_to_int(b:bool) -> u8 {
    match b {
        true => 1,
        false => 0
    }
}

impl CPU {

    fn new(mut mem: Vec<u8>) -> CPU {
        let mut cpu = CPU { registers: [0u8, ..16],
              mem: [0u8, ..0xFFF],
              I: 0,
              pc: 0,
              sp: 1,
              stack : [0u16, ..16],
              sound_timer: 0,
              delay_timer: 0,
              hp_48_flags: [0u16, ..8],
              opcode : 0,
              graphics : Graphics::new()
       };

       /* Move values out of supplied vector and into
        * CPU mem */
       mem.reverse(); /* reverse vector first as poping off the end (O(1))
                         is much cheaper than shifting from the front (O(n)) */
       for val in cpu.mem.mut_iter() {
            *val = match mem.pop() {
                    Some(item) => item,
                    None => 0x0
            };
       }

       return cpu;
    }

    fn to_addr(dig1 :u8, dig2 :u8, dig :u8) -> u16 {
        ((dig1 << 8) | (dig2 << 4) | dig3) as u16
    }

    fn to_val(dig1 :u8, dig2 :u8) -> u8 {
        (dig1 << 4) | dig2
    }

    fn u16_to_hex_vec(hex :u16) => (u8, u8, u8, u8) {
         (hex & 0xF000) >> 12,  (hex & 0x0F00 >> 8),
         (hex & 0x00F0 >> 4, hex & 0x000F)
    }

    fn perform_cycle(&mut self) {

        opcode = u16_to_hex_vec(self.get_opcode());
        self.inc_pc();

        match opcode {
            (0x0, 0x0 ,0xE, 0x0) => self.clear_screen(),
            (0x0, 0x0, 0xE, 0xE) => self.ret(),
            (0x0, N1, N2, N3)  => {},
            (0x1, N1, N2, N3)  => self.jump(to_addr(N1, N2, N3)),
            (0x2, N1, N2, N3)  => self.call(to_addr(N1, N2, N3)),
            (0x3, X, N1, N2)  => self.skip_equals_reg_val(X, to_val(N1, N2)),
            (0x4, X, N, N)  => self.skip_not_equals_reg_val(X, to_val(N1, N2)),
            (0x5  X, Y, 0x0)  => self.skip_equals_regs(X, Y),
            (0x6  X, N1, N2)  => self.mov_reg_val(X, to_val(N1, N2)),
            (0x7, X, N1, N2)  => self.add_reg_val(X, to_val(N1, N2)),
            (0x8, X, Y, 0x0) => self.mov_regs(X, Y),
            (0x8, X, Y, 0x1) => self.or_regs(X, Y),
            (0x8, X, Y, 0x2) => self.and_regs(X, Y),
            (0x8, X, Y, 0x3) => self.xor_regs(X, Y),
            (0x8, X, Y, 0x4) => self.add_regs(X, Y),
            (0x8, X, Y, 0x5) => self.sub_regs(X, Y),
            (0x8, X, Y, 0x6) => self.shift_right(X, Y),
            (0x8, X, Y, 0x7) => self.sub_regs(Y, X),
            (0x8, X, Y, 0xE) => self.shift_left(X, Y),
            (0x9, X, Y, 0x0) => self.skip_not_equals_regs(X, Y),
            (0xA, N1, N2, N3) => self.set_i(to_addr(N1, N2, N3)),
            (0xB, N1, N2, N3) => self.jump_val_reg0(to_addr(N1, N2, N3)),
            (0xC, X, N1, N2) => self.rand(X, to_val(N1, N2)),
            (0xD, X, Y, N) => {},
            (0xE, X, 0x9, 0xE) => {},
            (0xE, X, 0xA, 0x1) => {},
            (0xF, X, 0x0, 0x7) => {},
            (0xF, X, 0x0, 0xA) => {},
            (0xF, X, 0x1, 0x5) => self.set_reg_delay(X),
            (0xF, X, 0x1, 0x8) => self.set_reg_sound(X),
            (0xF, X, 0x1, 0xE) => self.add_reg_index(X),
            (0xF, X, 0x2, 0x9) =>  {},
            (0xF, X, 0x3, 0x3) => self.binary_decimal(X),
            (0xF, X, 0x5, 0x5) => self.store_regs(X),
            (0xF, X, 0x6, 0x5) => self.load_regs(X)
        }
    }

    fn regs_op(&mut self, op: |u8, u8| -> u8) {
        let reg1 = self.get_reg_no_1();
        let reg2 = self.get_reg_no_1();

        self.registers[reg1] =
            op(self.registers[reg1], self.registers[reg2]);

    }

    fn regs_op_flags(&mut self, op: |u8, u8| -> u8, flag_val: |u8, u8| -> u8) {
        let reg1 = self.get_reg_no_1();
        let reg2 = self.get_reg_no_2();

        self.registers[FLAG] =
            flag_val(self.registers[reg1], self.registers[reg2]);

        self.registers[reg1] =
            flag_val(self.registers[reg1], self.registers[reg2]);
    }

    fn reg_val_op(&mut self, op: |u8, u8| -> u8) {
        let reg = self.get_reg_no_1();
        let val = self.get_val();

        self.registers[reg] = op(self.registers[reg], val)
   }

    fn reset(&mut self) {
        self.pc = 0x200;
        self.sp = 0;
    }

    fn pop(&mut self) -> u16 {
        let item = self.stack[self.sp];
        self.sp -= 1;
        return item;

    }

    fn push(&mut self, val:u16) {
        self.sp += 1;
        self.stack[self.sp] = val;
    }

    fn inc_pc(&mut self) {
        self.pc += 2;
    }

    /* Jump to address at 0NNN */
    fn call(&mut self) {
        self.pc = self.opcode & 0xFFF;
    }

    /* Clear the screen */
    fn clear_screen(&mut self) {

    }

    /* Return from a subroutine */
    fn ret(&mut self) {
        self.pc = self.pop();
    }

    fn jump(&mut self, addr: u16) {
        self.pc = addr & 0xFFF;
    }

    /* Skip next instruction if register X is equal to NN */
    fn skip_equals_reg_val(&mut self, reg:u8, val:u8) {
        if self.registers[reg] == val {
            self.inc_pc();
        }

    }

    fn skip_not_equals_reg_val(&mut self, reg:u8, val:u8) {
        if self.registers[reg as uint] != val {
            self.inc_pc();
        }
    }

    fn skip_equals_regs(&mut self, reg1:u8, reg2:u8) {

        if self.registers[reg1 as uint] == self.registers[reg2 as uint] {
               self.inc_pc();
        }
    }

    fn skip_not_equals_regs(&mut self, reg1:u8, reg2:u8) {
        if self.registers[reg1 as uint] != self.registers[reg2 as uint] {
               self.inc_pc();
           }
    }

    fn mov_reg_val(&mut self, reg:u8, val:u8) {
        self.registers[reg as uint] = val;
    }

    fn add_reg_val(&mut self, reg:u8, val:u8) {
        self.registers[reg as uint] += val;
    }

    fn mov_regs(&mut self) {
        self.regs_op(|i, j| j);
    }

    fn or_regs(&mut self) {
        self.regs_op(|i, j| i | j);
    }

    fn and_regs(&mut self) {
        self.regs_op(|i, j| i & j);
    }

    fn xor_regs(&mut self) {
        self.regs_op(|i, j| i ^ j);
    }

    /* Add two regs, if overflow set flag register otherwise
     * unset flag register */
    fn add_regs(&mut self) {
        self.regs_op_flags(|reg1, reg2| reg1 + reg2,
                           |reg1, reg2| bool_to_int(0xFF - reg1 > reg2));
    }

    /* Sub reg2 from reg1, unset flag register if underflow,
     * set otherwise */
    fn sub_regs(&mut self) {
        self.regs_op_flags(|reg1, reg2| reg1 - reg2,
                           |reg1, reg2| bool_to_int(reg2 < reg1));

    }

    /* Sub reg1 from reg2, unset flag register if underflow,
     * set otherwise */
    fn sub_regs_inv(&mut self) {
        self.regs_op_flags(|reg1, reg2| reg2 - reg1,
                           |reg1, reg2| bool_to_int(reg1 < reg2));
    }

    /* Shift register left by 1, set flag register to most significant bit
     * before shifting */
    fn shift_left(&mut self) {
        self.regs_op_flags(|reg1, reg2| reg1 << 1, |reg1, reg2| reg1 & 0x80 >> 7);
    }

    /* Shift register right by 1, set flag register to least significant bit
     * before shifting */
    fn shift_right(&mut self) {
        self.regs_op_flags(|reg1, reg2| reg1 >> 1, |reg1, reg2| reg1 & 0x1);
    }

    /* Set index register to address in opcode */
    fn set_i(&mut self) {
        self.I = self.get_addr();
    }

    fn jump_val_reg0(&mut self) {
        self.pc = self.registers[0] as u16 + self.get_addr();
    }

    fn rand(&mut self) {
        self.reg_val_op( |reg, val| val & random::<u8>());
    }

    fn set_reg_delay(&mut self) {
        self.registers[self.get_reg_no_1()] = self.delay_timer;
    }

    fn set_reg_sound(&mut self) {
        self.registers[self.get_reg_no_1()] = self.sound_timer;
    }

    fn add_reg_index(&mut self) {
        let temp = self.I;
        self.I += self.registers[self.get_reg_no_1()] as u16;
        if (temp > self.I)  {
            self.registers[FLAG] = 1
        }
    }

    fn store_regs(&mut self) {
        let mut addr = self.I;
        for reg in self.registers.iter() {
            self.mem[addr as uint] = *reg;
            addr += 1;
        }
    }

    fn load_regs(&mut self) {
        let mut addr = self.I;
        for reg in self.registers.mut_iter() {
            *reg = self.mem[addr as uint];
            addr += 1;
        }
    }

    /*stores the Binary-coded decimal representation of VX, with the
     * most significant of three digits at the address in I, the middle digit
     * at I + 1, and the lsg at I + 2.*/
    fn binary_decimal(&mut self) {
        let val = self.registers[self.get_reg_no_1()];
        self.mem[self.I as uint] = val/100;
        self.mem[(self.I + 1) as uint] = (val % 100)/10;
        self.mem[(self.I + 2) as uint] = (val % 100)%10;

    }

}

fn main() {

    print!("yay");
}

<|endoftext|>


<commit_before>use std::cmp::{max, min};

use cairo::{self, ImageSurface};
use markup5ever::{expanded_name, local_name, namespace_url, ns, QualName};

use crate::drawing_ctx::DrawingCtx;
use crate::error::*;
use crate::node::{NodeResult, NodeTrait, RsvgNode};
use crate::parsers;
use crate::property_bag::PropertyBag;
use crate::rect::IRect;
use crate::surface_utils::{
    iterators::{PixelRectangle, Pixels},
    shared_surface::SharedImageSurface,
    EdgeMode,
    ImageSurfaceDataExt,
    Pixel,
};

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::{FilterEffect, FilterError, PrimitiveWithInput};

/// Enumeration of the possible morphology operations.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum Operator {
    Erode,
    Dilate,
}

/// The `feMorphology` filter primitive.
pub struct FeMorphology {
    base: PrimitiveWithInput,
    operator: Operator,
    radius: (f64, f64),
}

impl Default for FeMorphology {
    /// Constructs a new `Morphology` with empty properties.
    #[inline]
    fn default() -> FeMorphology {
        FeMorphology {
            base: PrimitiveWithInput::new::<Self>(),
            operator: Operator::Erode,
            radius: (0.0, 0.0),
        }
    }
}

impl NodeTrait for FeMorphology {
    impl_node_as_filter_effect!();

    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)?;

        for (attr, value) in pbag.iter() {
            match attr.expanded() {
                expanded_name!(svg "operator") => self.operator = Operator::parse(attr, value)?,
                expanded_name!(svg "radius") => {
                    self.radius = parsers::number_optional_number(value)
                        .and_then(|(x, y)| {
                            if x >= 0.0 && y >= 0.0 {
                                Ok((x, y))
                            } else {
                                Err(ValueErrorKind::value_error("radius cannot be negative"))
                            }
                        }).attribute(attr)?
                }
                _ => (),
            }
        }

        Ok(())
    }
}

impl FilterEffect for FeMorphology {
    fn render(
        &self,
        _node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .into_irect(draw_ctx);

        let (rx, ry) = self.radius;
        let (rx, ry) = ctx.paffine().transform_distance(rx, ry);

        // The radii can become negative here due to the transform.
        let rx = rx.abs();
        let ry = ry.abs();

        let mut output_surface = ImageSurface::create(
            cairo::Format::ARgb32,
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        )?;

        let output_stride = output_surface.get_stride() as usize;
        {
            let mut output_data = output_surface.get_data().unwrap();

            for (x, y, _pixel) in Pixels::new(input.surface(), bounds) {
                // Compute the kernel rectangle bounds.
                let kernel_bounds = IRect::new(
                    (f64::from(x) - rx).floor() as i32,
                    (f64::from(y) - ry).floor() as i32,
                    (f64::from(x) + rx).ceil() as i32 + 1,
                    (f64::from(y) + ry).ceil() as i32 + 1,
                );

                // Compute the new pixel values.
                let initial = match self.operator {
                    Operator::Erode => u8::max_value(),
                    Operator::Dilate => u8::min_value(),
                };

                let mut output_pixel = Pixel {
                    r: initial,
                    g: initial,
                    b: initial,
                    a: initial,
                };

                for (_x, _y, pixel) in
                    PixelRectangle::new(&input.surface(), bounds, kernel_bounds, EdgeMode::None)
                {
                    let op = match self.operator {
                        Operator::Erode => min,
                        Operator::Dilate => max,
                    };

                    output_pixel.r = op(output_pixel.r, pixel.r);
                    output_pixel.g = op(output_pixel.g, pixel.g);
                    output_pixel.b = op(output_pixel.b, pixel.b);
                    output_pixel.a = op(output_pixel.a, pixel.a);
                }

                output_data.set_pixel(output_stride, output_pixel, x, y);
            }
        }

        Ok(FilterResult {
            name: self.base.result.clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, input.surface().surface_type())?,
                bounds,
            },
        })
    }

    #[inline]
    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        false
    }
}

impl Operator {
    fn parse(attr: QualName, s: &str) -> Result<Self, NodeError> {
        match s {
            "erode" => Ok(Operator::Erode),
            "dilate" => Ok(Operator::Dilate),
            _ => Err(NodeError::parse_error(attr, "invalid value")),
        }
    }
}
<commit_msg>morphology.rs: Don't create a NodeError directly<commit_after>use std::cmp::{max, min};

use cairo::{self, ImageSurface};
use markup5ever::{expanded_name, local_name, namespace_url, ns, QualName};

use crate::drawing_ctx::DrawingCtx;
use crate::error::*;
use crate::node::{NodeResult, NodeTrait, RsvgNode};
use crate::parsers;
use crate::property_bag::PropertyBag;
use crate::rect::IRect;
use crate::surface_utils::{
    iterators::{PixelRectangle, Pixels},
    shared_surface::SharedImageSurface,
    EdgeMode,
    ImageSurfaceDataExt,
    Pixel,
};

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::{FilterEffect, FilterError, PrimitiveWithInput};

/// Enumeration of the possible morphology operations.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum Operator {
    Erode,
    Dilate,
}

/// The `feMorphology` filter primitive.
pub struct FeMorphology {
    base: PrimitiveWithInput,
    operator: Operator,
    radius: (f64, f64),
}

impl Default for FeMorphology {
    /// Constructs a new `Morphology` with empty properties.
    #[inline]
    fn default() -> FeMorphology {
        FeMorphology {
            base: PrimitiveWithInput::new::<Self>(),
            operator: Operator::Erode,
            radius: (0.0, 0.0),
        }
    }
}

impl NodeTrait for FeMorphology {
    impl_node_as_filter_effect!();

    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)?;

        for (attr, value) in pbag.iter() {
            match attr.expanded() {
                expanded_name!(svg "operator") => self.operator = Operator::parse(attr, value)?,
                expanded_name!(svg "radius") => {
                    self.radius = parsers::number_optional_number(value)
                        .and_then(|(x, y)| {
                            if x >= 0.0 && y >= 0.0 {
                                Ok((x, y))
                            } else {
                                Err(ValueErrorKind::value_error("radius cannot be negative"))
                            }
                        }).attribute(attr)?
                }
                _ => (),
            }
        }

        Ok(())
    }
}

impl FilterEffect for FeMorphology {
    fn render(
        &self,
        _node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .into_irect(draw_ctx);

        let (rx, ry) = self.radius;
        let (rx, ry) = ctx.paffine().transform_distance(rx, ry);

        // The radii can become negative here due to the transform.
        let rx = rx.abs();
        let ry = ry.abs();

        let mut output_surface = ImageSurface::create(
            cairo::Format::ARgb32,
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        )?;

        let output_stride = output_surface.get_stride() as usize;
        {
            let mut output_data = output_surface.get_data().unwrap();

            for (x, y, _pixel) in Pixels::new(input.surface(), bounds) {
                // Compute the kernel rectangle bounds.
                let kernel_bounds = IRect::new(
                    (f64::from(x) - rx).floor() as i32,
                    (f64::from(y) - ry).floor() as i32,
                    (f64::from(x) + rx).ceil() as i32 + 1,
                    (f64::from(y) + ry).ceil() as i32 + 1,
                );

                // Compute the new pixel values.
                let initial = match self.operator {
                    Operator::Erode => u8::max_value(),
                    Operator::Dilate => u8::min_value(),
                };

                let mut output_pixel = Pixel {
                    r: initial,
                    g: initial,
                    b: initial,
                    a: initial,
                };

                for (_x, _y, pixel) in
                    PixelRectangle::new(&input.surface(), bounds, kernel_bounds, EdgeMode::None)
                {
                    let op = match self.operator {
                        Operator::Erode => min,
                        Operator::Dilate => max,
                    };

                    output_pixel.r = op(output_pixel.r, pixel.r);
                    output_pixel.g = op(output_pixel.g, pixel.g);
                    output_pixel.b = op(output_pixel.b, pixel.b);
                    output_pixel.a = op(output_pixel.a, pixel.a);
                }

                output_data.set_pixel(output_stride, output_pixel, x, y);
            }
        }

        Ok(FilterResult {
            name: self.base.result.clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, input.surface().surface_type())?,
                bounds,
            },
        })
    }

    #[inline]
    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        false
    }
}

impl Operator {
    fn parse(attr: QualName, s: &str) -> Result<Self, NodeError> {
        match s {
            "erode" => Ok(Operator::Erode),
            "dilate" => Ok(Operator::Dilate),
            _ => Err(ValueErrorKind::parse_error("invalid value")).attribute(attr),
        }
    }
}
<|endoftext|>


<commit_before>extern crate ssz;

use self::ssz::{
    SszStream,
};
use std::sync::Arc;
use super::{
    validate_ssz_block,
    BlockStatus,
    AttesterMap,
    ProposerMap,
};
use super::db::stores::{
    BlockStore,
    PoWChainStore,
    ValidatorStore,
};
use super::db::{
    MemoryDB,
};
use super::utils::types::{
    Hash256,
    Bitfield,
};
use super::{
    Block,
    SszBlock,
};
use super::super::attestation_record::AttestationRecord;
use super::super::super::bls::{
    Keypair,
    Signature,
    AggregateSignature,
};

struct TestStore {
    db: Arc<MemoryDB>,
    block: Arc<BlockStore<MemoryDB>>,
    pow_chain: Arc<PoWChainStore<MemoryDB>>,
    validator: Arc<ValidatorStore<MemoryDB>>,
}

impl TestStore {
    pub fn new() -> Self {
        let db = Arc::new(MemoryDB::open());
        let block = Arc::new(BlockStore::new(db.clone()));
        let pow_chain = Arc::new(PoWChainStore::new(db.clone()));
        let validator = Arc::new(ValidatorStore::new(db.clone()));
        Self {
            db,
            block,
            pow_chain,
            validator,
        }
    }
}

#[test]
fn test_block_validation() {
    let stores = TestStore::new();

    let cycle_length = 2;
    let shard_count = 2;
    let present_slot = u64::from(cycle_length) * 10000;
    let justified_slot = present_slot - u64::from(cycle_length);
    let justified_block_hash = Hash256::from("justified_hash".as_bytes());
    let shard_block_hash = Hash256::from("shard_hash".as_bytes());
    let parent_hashes = (0..(cycle_length * 2))
        .map(|i| Hash256::from(i as u64))
        .collect();
    let pow_chain_ref = Hash256::from("pow_chain".as_bytes());
    let active_state_root = Hash256::from("active_state".as_bytes());
    let crystallized_state_root = Hash256::from("cry_state".as_bytes());

    stores.pow_chain.put_block_hash(pow_chain_ref.as_ref()).unwrap();
    stores.block.put_block(justified_block_hash.as_ref(), &vec![42]).unwrap();

    let validators_per_shard = 2;

    let block_slot = present_slot;
    let validator_index: usize = 0;
    let proposer_map = {
        let mut proposer_map = ProposerMap::new();
        proposer_map.insert(present_slot, validator_index);
        proposer_map
    };
    let (attester_map, attestations, _keypairs) = {
        let mut i = 0;
        let mut attester_map = AttesterMap::new();
        let mut attestations = vec![];
        let mut keypairs = vec![];
        for shard in 0..shard_count {
            println!("hello");
            let mut attesters = vec![];
            let mut attester_bitfield = Bitfield::new();
            let mut aggregate_sig = AggregateSignature::new();
            let attestation_slot = block_slot - 1;

            let attestation_message = {
                let mut stream = SszStream::new();
                stream.append(&attestation_slot);
                stream.append_vec(&parent_hashes);
                stream.append(&shard);
                stream.append(&shard_block_hash);
                stream.append(&justified_slot);
                stream.drain()
            };

            for _ in 0..validators_per_shard {
               /*
                * Add the attester to the attestation indices for this shard.
                */
               attesters.push(i);
               /*
                * Set the voters bit on the bitfield to true.
                */
               attester_bitfield.set_bit(i, true);
               /*
                * Generate a random keypair for this validatior and clone it into the
                * list of keypairs.
                */
               let keypair = Keypair::random();
               keypairs.push(keypair.clone());
               /*
                * Store the validators public key in the database.
                */
               stores.validator.put_public_key_by_index(i, &keypair.pk).unwrap();
               /*
                * Generate a new signature and aggregate it on the rolling signature.
                */
               let sig = Signature::new(&attestation_message, &keypair.sk);
               aggregate_sig.add(&sig);
               /*
                * Increment the validator counter to monotonically assign validators.
                */
               i += 1;
            }

            attester_map.insert((attestation_slot, shard), attesters);
            let attestation = AttestationRecord {
                slot: attestation_slot,
                shard_id: shard,
                oblique_parent_hashes: vec![],
                shard_block_hash: Hash256::from("shardhash".as_bytes()),
                attester_bitfield,
                justified_slot,
                justified_block_hash,
                aggregate_sig,
            };
            attestations.push(attestation);
        }
        (attester_map, attestations, keypairs)
    };

    let block = Block {
        parent_hash: Hash256::from("parent".as_bytes()),
        slot_number: block_slot,
        randao_reveal: Hash256::from("randao".as_bytes()),
        attestations,
        pow_chain_ref,
        active_state_root,
        crystallized_state_root,
    };

    let mut stream = SszStream::new();
    stream.append(&block);
    let serialized_block = stream.drain();
    let ssz_block = SszBlock::from_slice(&serialized_block[..]).unwrap();

    println!("this happened");

    let status = validate_ssz_block(
        &ssz_block,
        present_slot,
        cycle_length,
        justified_slot,
        Arc::new(parent_hashes),
        Arc::new(proposer_map),
        Arc::new(attester_map),
        stores.block.clone(),
        stores.validator.clone(),
        stores.pow_chain.clone()).unwrap();

    assert_eq!(status, BlockStatus::NewBlock);
}
<commit_msg>Add/fix message hashing in block validation tests<commit_after>extern crate ssz;

use self::ssz::{
    SszStream,
};
use std::sync::Arc;
use super::{
    validate_ssz_block,
    BlockStatus,
    AttesterMap,
    ProposerMap,
};
use super::db::stores::{
    BlockStore,
    PoWChainStore,
    ValidatorStore,
};
use super::db::{
    MemoryDB,
};
use super::utils::hash::canonical_hash;
use super::utils::types::{
    Hash256,
    Bitfield,
};
use super::{
    Block,
    SszBlock,
};
use super::super::attestation_record::AttestationRecord;
use super::super::super::bls::{
    Keypair,
    Signature,
    AggregateSignature,
};

struct TestStore {
    db: Arc<MemoryDB>,
    block: Arc<BlockStore<MemoryDB>>,
    pow_chain: Arc<PoWChainStore<MemoryDB>>,
    validator: Arc<ValidatorStore<MemoryDB>>,
}

impl TestStore {
    pub fn new() -> Self {
        let db = Arc::new(MemoryDB::open());
        let block = Arc::new(BlockStore::new(db.clone()));
        let pow_chain = Arc::new(PoWChainStore::new(db.clone()));
        let validator = Arc::new(ValidatorStore::new(db.clone()));
        Self {
            db,
            block,
            pow_chain,
            validator,
        }
    }
}

#[test]
fn test_block_validation() {
    let stores = TestStore::new();

    let cycle_length: u8 = 2;
    let shard_count: u16 = 2;
    let present_slot = u64::from(cycle_length) * 10000;
    let justified_slot = present_slot - u64::from(cycle_length);
    let justified_block_hash = Hash256::from("justified_hash".as_bytes());
    let shard_block_hash = Hash256::from("shard_hash".as_bytes());
    let parent_hashes = (0..(cycle_length * 2))
        .map(|i| Hash256::from(i as u64))
        .collect();
    let pow_chain_ref = Hash256::from("pow_chain".as_bytes());
    let active_state_root = Hash256::from("active_state".as_bytes());
    let crystallized_state_root = Hash256::from("cry_state".as_bytes());

    stores.pow_chain.put_block_hash(pow_chain_ref.as_ref()).unwrap();
    stores.block.put_block(justified_block_hash.as_ref(), &vec![42]).unwrap();

    let validators_per_shard = 2;

    let block_slot = present_slot;
    let validator_index: usize = 0;
    let proposer_map = {
        let mut proposer_map = ProposerMap::new();
        proposer_map.insert(present_slot, validator_index);
        proposer_map
    };
    let (attester_map, attestations, _keypairs) = {
        let mut i = 0;
        let mut attester_map = AttesterMap::new();
        let mut attestations = vec![];
        let mut keypairs = vec![];
        for shard in 0..shard_count {
            println!("hello");
            let mut attesters = vec![];
            let mut attester_bitfield = Bitfield::new();
            let mut aggregate_sig = AggregateSignature::new();
            let attestation_slot = block_slot - 1;

            let attestation_message = {
                let mut stream = SszStream::new();
                stream.append(&attestation_slot);
                stream.append_vec(&parent_hashes);
                stream.append(&shard);
                stream.append(&shard_block_hash);
                stream.append(&justified_slot);
                let bytes = stream.drain();
                canonical_hash(&bytes)
            };

            for _ in 0..validators_per_shard {
               /*
                * Add the attester to the attestation indices for this shard.
                */
               attesters.push(i);
               /*
                * Set the voters bit on the bitfield to true.
                */
               attester_bitfield.set_bit(i, true);
               /*
                * Generate a random keypair for this validatior and clone it into the
                * list of keypairs.
                */
               let keypair = Keypair::random();
               keypairs.push(keypair.clone());
               /*
                * Store the validators public key in the database.
                */
               stores.validator.put_public_key_by_index(i, &keypair.pk).unwrap();
               /*
                * Generate a new signature and aggregate it on the rolling signature.
                */
               let sig = Signature::new(&attestation_message, &keypair.sk);
               aggregate_sig.add(&sig);
               /*
                * Increment the validator counter to monotonically assign validators.
                */
               i += 1;
            }

            attester_map.insert((attestation_slot, shard), attesters);
            let attestation = AttestationRecord {
                slot: attestation_slot,
                shard_id: shard,
                oblique_parent_hashes: vec![],
                shard_block_hash: Hash256::from("shardhash".as_bytes()),
                attester_bitfield,
                justified_slot,
                justified_block_hash,
                aggregate_sig,
            };
            attestations.push(attestation);
        }
        (attester_map, attestations, keypairs)
    };

    let block = Block {
        parent_hash: Hash256::from("parent".as_bytes()),
        slot_number: block_slot,
        randao_reveal: Hash256::from("randao".as_bytes()),
        attestations,
        pow_chain_ref,
        active_state_root,
        crystallized_state_root,
    };

    let mut stream = SszStream::new();
    stream.append(&block);
    let serialized_block = stream.drain();
    let ssz_block = SszBlock::from_slice(&serialized_block[..]).unwrap();

    println!("this happened");

    let status = validate_ssz_block(
        &ssz_block,
        present_slot,
        cycle_length,
        justified_slot,
        Arc::new(parent_hashes),
        Arc::new(proposer_map),
        Arc::new(attester_map),
        stores.block.clone(),
        stores.validator.clone(),
        stores.pow_chain.clone()).unwrap();

    assert_eq!(status, BlockStatus::NewBlock);
}
<|endoftext|>


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

#![feature(conservative_impl_trait)]

extern crate futures;
extern crate gtk;
#[macro_use]
extern crate relm;
extern crate tokio_core;
extern crate url;

use std::net::ToSocketAddrs;

use futures::Future;
use futures::future::ok;
use gtk::{Button, ButtonExt, ContainerExt, Image, Label, WidgetExt, Window, WindowType};
use gtk::Orientation::Vertical;
use relm::{EventStream, Handle, QuitFuture, Relm, UnitFuture, Widget, connect};
use tokio_core::net::TcpStream;
use url::Url;

use self::Msg::*;

#[derive(Clone, Debug)]
struct Model {
    gif_url: String,
    topic: String,
}

#[derive(Clone)]
enum Msg {
    FetchImage,
    FetchUrl,
    NewGif(String),
    Quit,
}

struct Widgets {
    button: Button,
    image: Image,
    label: Label,
    window: Window,
}

struct Win {
    model: Model,
    widgets: Widgets,
}

impl Win {
    fn view() -> Widgets {
        let vbox = gtk::Box::new(Vertical, 0);

        let label = Label::new(None);
        vbox.add(&label);

        let image = Image::new_from_resource("https://k1.okccdn.com/php/load_okc_image.php/images/120x120/120x120/0x65/531x597/2/6119803335702555186.jpeg?v=1");
        vbox.add(&image);

        let button = Button::new_with_label("Load image");
        vbox.add(&button);

        let window = Window::new(WindowType::Toplevel);

        window.add(&vbox);

        window.show_all();

        Widgets {
            button: button,
            image: image,
            label: label,
            window: window,
        }
    }
}

impl Widget<Msg> for Win {
    fn connect_events(&self, relm: &Relm<Msg>) {
        connect!(relm, self.widgets.button, connect_clicked(_), FetchUrl);
        connect_no_inhibit!(relm, self.widgets.window, connect_delete_event(_, _), Quit);
    }

    fn new() -> Self {
        Win {
            model: Model {
                gif_url: "waiting.gif".to_string(),
                topic: "cats".to_string(),
            },
            widgets: Self::view(),
        }
    }

    fn update(&mut self, event: Msg, handle: Handle, stream: EventStream<Msg>) -> UnitFuture {
        match event {
            FetchImage => {
            },
            FetchUrl => {
                let url = format!("https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag={}", self.model.topic);
                let http_future = http_get(&url, handle);
                return connect(http_future, NewGif, stream).boxed();
            },
            NewGif(result) => {
                println!("{}", result);
            },
            Quit => return QuitFuture.boxed(),
        }

        ok(()).boxed()
    }
}

fn http_get<'a>(url: &str, handle: Handle) -> impl Future<Item=String, Error=()> + 'a {
    let url = Url::parse(url).unwrap();
    let path = format!("{}?{}", url.path(), url.query().unwrap_or(""));
    let url = url.host_str();
    let url = url.unwrap();
    let host = format!("{}:80", url);
    let addr = host.to_socket_addrs().unwrap().next().unwrap();
    let socket = TcpStream::connect(&addr, &handle);
    let http = format!("\
        GET {} HTTP/1.0\r\n\
        Host: {}\r\n\
        \r\n\
    ", path, url);
    let request = socket.and_then(move |socket| {
        tokio_core::io::write_all(socket, http.into_bytes())
    });

    let response = request.and_then(|(socket, _request)| {
        tokio_core::io::read_to_end(socket, Vec::new())
    });
    response.and_then(|(_socket, response)| {
        let string = String::from_utf8(response).unwrap();
        let strings: Vec<_> = string.split("\n\n").collect();
        let body = strings[1].to_string();
        ok(body)
    })
        // TODO: try to box (so that it becomes Send) the error to keep it instead of ignoring it.
        .map_err(|_| ())
}

fn main() {
    Relm::run::<Win>().unwrap();
}
<commit_msg>Refactor and fix the http request code.<commit_after>/*
 * Copyright (c) 2017 Boucher, Antoni <bouanto@zoho.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#![feature(conservative_impl_trait)]

extern crate futures;
extern crate gtk;
#[macro_use]
extern crate relm;
extern crate tokio_core;
extern crate url;

use std::io::Error;
use std::net::ToSocketAddrs;

use futures::Future;
use futures::future::ok;
use gtk::{Button, ButtonExt, ContainerExt, Image, Label, WidgetExt, Window, WindowType};
use gtk::Orientation::Vertical;
use relm::{EventStream, Handle, QuitFuture, Relm, UnitFuture, Widget, connect};
use tokio_core::net::TcpStream;
use url::Url;

use self::Msg::*;

#[derive(Clone, Debug)]
struct Model {
    gif_url: String,
    topic: String,
}

#[derive(Clone)]
enum Msg {
    FetchImage,
    FetchUrl,
    NewGif(String),
    Quit,
}

struct Widgets {
    button: Button,
    image: Image,
    label: Label,
    window: Window,
}

struct Win {
    model: Model,
    widgets: Widgets,
}

impl Win {
    fn view() -> Widgets {
        let vbox = gtk::Box::new(Vertical, 0);

        let label = Label::new(None);
        vbox.add(&label);

        let image = Image::new_from_resource("https://k1.okccdn.com/php/load_okc_image.php/images/120x120/120x120/0x65/531x597/2/6119803335702555186.jpeg?v=1");
        vbox.add(&image);

        let button = Button::new_with_label("Load image");
        vbox.add(&button);

        let window = Window::new(WindowType::Toplevel);

        window.add(&vbox);

        window.show_all();

        Widgets {
            button: button,
            image: image,
            label: label,
            window: window,
        }
    }
}

impl Widget<Msg> for Win {
    fn connect_events(&self, relm: &Relm<Msg>) {
        connect!(relm, self.widgets.button, connect_clicked(_), FetchUrl);
        connect_no_inhibit!(relm, self.widgets.window, connect_delete_event(_, _), Quit);
    }

    fn new() -> Self {
        Win {
            model: Model {
                gif_url: "waiting.gif".to_string(),
                topic: "cats".to_string(),
            },
            widgets: Self::view(),
        }
    }

    fn update(&mut self, event: Msg, handle: Handle, stream: EventStream<Msg>) -> UnitFuture {
        match event {
            FetchImage => {
            },
            FetchUrl => {
                let url = format!("https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag={}", self.model.topic);
                let http_future = http_get(&url, handle);
                return connect(http_future, NewGif, stream).boxed();
            },
            NewGif(result) => {
                println!("{}", result);
            },
            Quit => return QuitFuture.boxed(),
        }

        ok(()).boxed()
    }
}

fn http_get<'a>(url: &str, handle: Handle) -> impl Future<Item=String, Error=Error> + 'a {
    let url = Url::parse(url).unwrap();
    let path = format!("{}?{}", url.path(), url.query().unwrap_or(""));
    let url = url.host_str();
    let url = url.unwrap();
    let host = format!("{}:80", url);
    let addr = host.to_socket_addrs().unwrap().next().unwrap();
    let socket = TcpStream::connect(&addr, &handle);
    let http = format!("\
        GET {} HTTP/1.0\r\n\
        Host: {}\r\n\
        \r\n\
    ", path, url);
    let request = socket.and_then(move |socket| {
        tokio_core::io::write_all(socket, http.into_bytes())
    });

    let response = request.and_then(|(socket, _request)| {
        tokio_core::io::read_to_end(socket, Vec::new())
    });
    response.and_then(|(_socket, response)| {
        let string = String::from_utf8(response).unwrap();
        let strings: Vec<_> = string.split("\n\n").collect();
        let body = strings[1..].join("\n\n");
        ok(body)
    })
}

fn main() {
    Relm::run::<Win>().unwrap();
}
<|endoftext|>


<commit_before>extern crate ruroonga_client;
extern crate json_flex;

use json_flex::Unwrap;

use ruroonga_client as groonga;

fn create_table() {
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("table_create");
    command.set_argument(vec![("name", "Sites"),
                              ("flags","TABLE_HASH_KEY"),("key_type","ShortText")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("load url: {}", url);
    let res = request.load(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
}

fn create_column() {
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("column_create");
    command.set_argument(vec![("table", "Sites"),
                              ("name","title"),("type","ShortText")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("load url: {}", url);
    let res = request.load(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
}

fn load() {
    let data = r#"
[
{"_key":"http://example.org/","title":"This is test record 1!"},
{"_key":"http://example.net/","title":"test record 2."},
{"_key":"http://example.com/","title":"test test record three."},
{"_key":"http://example.net/afr","title":"test record four."},
{"_key":"http://example.org/aba","title":"test test test record five."},
{"_key":"http://example.com/rab","title":"test test test test record six."},
{"_key":"http://example.net/atv","title":"test test test record seven."},
{"_key":"http://example.org/gat","title":"test test record eight."},
{"_key":"http://example.com/vdw","title":"test test record nine."},
]"#;
    let mut request = groonga::HTTPRequest::new();
    let mut load_command = groonga::CommandQuery::new("load");
    load_command.set_argument(vec![("table", "Sites"),
                                   ("input_type","json"), ("values", data)]);
    let load_url = format!("http://localhost:10041{}", load_command.encode());
    println!("load url: {}", load_url);
    let load_res = request.load(load_url);
    let load_result = request.receive(&mut load_res.unwrap());
    println!("result: {}", load_result);
}

fn main() {
    create_table();
    create_column();
    load();
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("select");
    command.set_argument(vec![("table", "Sites")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("url: {}", url);
    let res = request.get(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
    let mut decode = groonga::ResultParser::new(result);
    println!("status: {:?}", decode.status().unwrap());
    println!("start: {:?}", decode.start_time().unwrap());
    println!("elapsed: {:?}", decode.elapsed_time().unwrap());
    println!("matched columns: {:?}", decode.matched_columns().unwrap());
    let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
    println!("index access: {:?}", vec[2]);
    // Read got response
    for v in decode.result().unwrap().pop().unwrap().unwrap_vec().iter() {
        println!("{:?}", v);
        for vv in v.unwrap_vec().iter() {
            if vv.is_integer() {
                println!("{:?}", vv.unwrap_i64())
            } else if vv.is_string() {
                println!("{:?}", vv.unwrap_string())
            } else {
                println!("-- schema column --");
                println!("{:?}", vv)
            }
        }
    }
}
<commit_msg>Map got result into user-defined struct<commit_after>extern crate ruroonga_client;
extern crate json_flex;

use json_flex::Unwrap;

use ruroonga_client as groonga;

fn create_table() {
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("table_create");
    command.set_argument(vec![("name", "Sites"),
                              ("flags","TABLE_HASH_KEY"),("key_type","ShortText")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("load url: {}", url);
    let res = request.load(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
}

fn create_column() {
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("column_create");
    command.set_argument(vec![("table", "Sites"),
                              ("name","title"),("type","ShortText")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("load url: {}", url);
    let res = request.load(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
}

fn load() {
    let data = r#"
[
{"_key":"http://example.org/","title":"This is test record 1!"},
{"_key":"http://example.net/","title":"test record 2."},
{"_key":"http://example.com/","title":"test test record three."},
{"_key":"http://example.net/afr","title":"test record four."},
{"_key":"http://example.org/aba","title":"test test test record five."},
{"_key":"http://example.com/rab","title":"test test test test record six."},
{"_key":"http://example.net/atv","title":"test test test record seven."},
{"_key":"http://example.org/gat","title":"test test record eight."},
{"_key":"http://example.com/vdw","title":"test test record nine."},
]"#;
    let mut request = groonga::HTTPRequest::new();
    let mut load_command = groonga::CommandQuery::new("load");
    load_command.set_argument(vec![("table", "Sites"),
                                   ("input_type","json"), ("values", data)]);
    let load_url = format!("http://localhost:10041{}", load_command.encode());
    println!("load url: {}", load_url);
    let load_res = request.load(load_url);
    let load_result = request.receive(&mut load_res.unwrap());
    println!("result: {}", load_result);
}

#[derive(Clone, Debug)]
struct Result {
    id: i64,
    key: String,
    title: String
}

fn main() {
    create_table();
    create_column();
    load();
    let mut request = groonga::HTTPRequest::new();
    let mut command = groonga::CommandQuery::new("select");
    command.set_argument(vec![("table", "Sites")]);
    let url = format!("http://localhost:10041{}", command.encode());
    println!("url: {}", url);
    let res = request.get(url);
    let result = request.receive(&mut res.unwrap());
    println!("result: {}", result);
    let mut decode = groonga::ResultParser::new(result);
    println!("status: {:?}", decode.status().unwrap());
    println!("start: {:?}", decode.start_time().unwrap());
    println!("elapsed: {:?}", decode.elapsed_time().unwrap());
    println!("matched columns: {:?}", decode.matched_columns().unwrap());
    let vec = decode.result().unwrap().pop().unwrap().unwrap_vec().clone();
    println!("index access: {:?}", vec[2]);
    // Read got response
    let mut result_vec: Vec<Result> = Vec::new();
    // Skip reading result header
    for v in decode.result().unwrap().pop().unwrap().unwrap_vec().iter().skip(2) {
        println!("{:?}", v);
        let raw = v.unwrap_vec();
        let elem = Result { id: raw[0].unwrap_i64().clone(),
                            key: raw[1].unwrap_string().clone(),
                            title: raw[2].unwrap_string().clone() };
        result_vec.push(elem.clone());
    }
    println!("{:?}", result_vec);
}
<|endoftext|>


<commit_before>extern crate tini;
use tini::Ini;

static INPUT: &'static str = "./examples/example.ini";

fn main() {
    let config = Ini::from_file(INPUT).unwrap();

    // if you are sure
    let name1: i32 = config.get("section_one", "name1").unwrap();

    // if you aren't sure
    let mut name5: bool = false;
    name5 = config.get("section_one", "name5").unwrap_or(name5); // non-existing key

    // check
    println!("name1: {}", name1);
    println!("name5: {}", name5);
}
<commit_msg>[upd] example<commit_after>extern crate tini;
use tini::Ini;

static INPUT: &'static str = "./examples/example.ini";

fn main() {
    let config = Ini::from_file(INPUT).unwrap();

    // if you are sure
    let name1: i32 = config.get("section_one", "name1").unwrap();

    // if you aren't sure
    let name5: bool = config.get("section_one", "name5").unwrap_or(false); // non-existing key

    // check
    println!("name1: {}", name1);
    println!("name5: {}", name5);
}
<|endoftext|>


<commit_before>extern crate byteorder;
extern crate rosc;

use byteorder::{BigEndian, ByteOrder};
use std::mem;

use rosc::{decoder, encoder};

#[test]
fn test_decode_no_args() {
    // message to build: /some/valid/address/4 ,
    let raw_addr = "/some/valid/address/4";
    let addr = encoder::encode_string(raw_addr);
    let type_tags = encoder::encode_string(",");
    let merged: Vec<u8> = addr.into_iter().chain(type_tags.into_iter()).collect();
    let osc_packet: Result<rosc::OscPacket, rosc::OscError> = decoder::decode(&merged);
    assert!(osc_packet.is_ok());
    match osc_packet {
        Ok(rosc::OscPacket::Message(msg)) => {
            assert_eq!(raw_addr, msg.addr);
            assert!(msg.args.is_none());
        }
        Ok(_) => panic!("Expected an OscMessage!"),
        Err(e) => panic!(e),
    }
}

#[test]
fn test_decode_args() {
    // /another/valid/address/123 ,fdih 3.1415 3.14159265359 12345678i32
    // -1234567891011
    let addr = encoder::encode_string("/another/valid/address/123");
    // args
    let f = 3.1415f32;
    let mut f_bytes: [u8; 4] = [0u8; 4];
    BigEndian::write_f32(&mut f_bytes, f);
    assert_eq!(BigEndian::read_f32(&f_bytes), f);

    let d = 3.14159265359f64;
    let mut d_bytes: [u8; 8] = [0u8; 8];
    BigEndian::write_f64(&mut d_bytes, d);
    assert_eq!(BigEndian::read_f64(&d_bytes), d);

    let i = 12345678i32;
    let i_bytes: [u8; 4] = unsafe { mem::transmute(i.to_be()) };

    let l = -1234567891011i64;
    let h_bytes: [u8; 8] = unsafe { mem::transmute(l.to_be()) };

    let blob_size: [u8; 4] = unsafe { mem::transmute(6u32.to_be()) };
    let blob: Vec<u8> = vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8];

    let s = "I am an osc test string.";
    assert!(s.is_ascii());
    // Osc strings are null terminated like in C!
    let s_bytes: Vec<u8> = encoder::encode_string(s);

    let c = '$';
    let c_bytes: [u8; 4] = unsafe { mem::transmute((c as u32).to_be()) };

    let type_tags = encoder::encode_string(",fdsTFibhNIc");

    let args: Vec<u8> = f_bytes
        .iter()
        .chain(d_bytes.iter())
        .chain(s_bytes.iter())
        .chain(i_bytes.iter())
        .chain(blob_size.iter())
        .chain(blob.iter())
        .chain(vec![0u8, 0u8].iter())
        .chain(h_bytes.iter())
        .chain(c_bytes.iter())
        .map(|x| *x)
        .collect::<Vec<u8>>();

    let merged: Vec<u8> = addr.into_iter()
        .chain(type_tags.into_iter())
        .chain(args)
        .collect::<Vec<u8>>();

    match decoder::decode(&merged).unwrap() {
        rosc::OscPacket::Message(msg) => {
            for arg in msg.args.unwrap() {
                match arg {
                    rosc::OscType::Int(x) => assert_eq!(i, x),
                    rosc::OscType::Long(x) => assert_eq!(l, x),
                    rosc::OscType::Float(x) => assert_eq!(f, x),
                    rosc::OscType::Double(x) => assert_eq!(d, x),
                    rosc::OscType::String(x) => assert_eq!(s, x),
                    rosc::OscType::Blob(x) => assert_eq!(blob, x),
                    // cant assign bool args to type_tag
                    // , so there is no real test wether the value is
                    // correct or not
                    rosc::OscType::Bool(_) => (),
                    rosc::OscType::Inf => (),
                    rosc::OscType::Nil => (),
                    // test time-tags, midi-messages and chars
                    rosc::OscType::Char(x) => assert_eq!(c, x),
                    _ => panic!(),
                }
            }
        }
        _ => panic!("Expected an OSC message!"),
    }
}
<commit_msg>Add decoder test for OscArray<commit_after>extern crate byteorder;
extern crate rosc;

use byteorder::{BigEndian, ByteOrder};
use std::mem;

use rosc::{decoder, encoder, OscType};

#[test]
fn test_decode_no_args() {
    // message to build: /some/valid/address/4 ,
    let raw_addr = "/some/valid/address/4";
    let addr = encoder::encode_string(raw_addr);
    let type_tags = encoder::encode_string(",");
    let merged: Vec<u8> = addr.into_iter().chain(type_tags.into_iter()).collect();
    let osc_packet: Result<rosc::OscPacket, rosc::OscError> = decoder::decode(&merged);
    assert!(osc_packet.is_ok());
    match osc_packet {
        Ok(rosc::OscPacket::Message(msg)) => {
            assert_eq!(raw_addr, msg.addr);
            assert!(msg.args.is_none());
        }
        Ok(_) => panic!("Expected an OscMessage!"),
        Err(e) => panic!(e),
    }
}

#[test]
fn test_decode_args() {
    // /another/valid/address/123 ,fdih 3.1415 3.14159265359 12345678i32
    // -1234567891011
    let addr = encoder::encode_string("/another/valid/address/123");
    // args
    let f = 3.1415f32;
    let mut f_bytes: [u8; 4] = [0u8; 4];
    BigEndian::write_f32(&mut f_bytes, f);
    assert_eq!(BigEndian::read_f32(&f_bytes), f);

    let d = 3.14159265359f64;
    let mut d_bytes: [u8; 8] = [0u8; 8];
    BigEndian::write_f64(&mut d_bytes, d);
    assert_eq!(BigEndian::read_f64(&d_bytes), d);

    let i = 12345678i32;
    let i_bytes: [u8; 4] = unsafe { mem::transmute(i.to_be()) };

    let l = -1234567891011i64;
    let h_bytes: [u8; 8] = unsafe { mem::transmute(l.to_be()) };

    let blob_size: [u8; 4] = unsafe { mem::transmute(6u32.to_be()) };
    let blob: Vec<u8> = vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8];

    let s = "I am an osc test string.";
    assert!(s.is_ascii());
    // Osc strings are null terminated like in C!
    let s_bytes: Vec<u8> = encoder::encode_string(s);

    let c = '$';
    let c_bytes: [u8; 4] = unsafe { mem::transmute((c as u32).to_be()) };

    let a = vec![OscType::Int(i), OscType::Float(f), OscType::Int(i)];

    let type_tags = encoder::encode_string(",fdsTFibhNIc[ifi]");

    let args: Vec<u8> = f_bytes
        .iter()
        .chain(d_bytes.iter())
        .chain(s_bytes.iter())
        .chain(i_bytes.iter())
        .chain(blob_size.iter())
        .chain(blob.iter())
        .chain(vec![0u8, 0u8].iter())
        .chain(h_bytes.iter())
        .chain(c_bytes.iter())
        // array content
        .chain(i_bytes.iter())
        .chain(f_bytes.iter())
        .chain(i_bytes.iter())
        .map(|x| *x)
        .collect::<Vec<u8>>();

    let merged: Vec<u8> = addr.into_iter()
        .chain(type_tags.into_iter())
        .chain(args)
        .collect::<Vec<u8>>();

    match decoder::decode(&merged).unwrap() {
        rosc::OscPacket::Message(msg) => {
            for arg in msg.args.unwrap() {
                match arg {
                    rosc::OscType::Int(x) => assert_eq!(i, x),
                    rosc::OscType::Long(x) => assert_eq!(l, x),
                    rosc::OscType::Float(x) => assert_eq!(f, x),
                    rosc::OscType::Double(x) => assert_eq!(d, x),
                    rosc::OscType::String(x) => assert_eq!(s, x),
                    rosc::OscType::Blob(x) => assert_eq!(blob, x),
                    // cant assign bool args to type_tag
                    // , so there is no real test wether the value is
                    // correct or not
                    rosc::OscType::Bool(_) => (),
                    rosc::OscType::Inf => (),
                    rosc::OscType::Nil => (),
                    // test time-tags, midi-messages and chars
                    rosc::OscType::Char(x) => assert_eq!(c, x),
                    rosc::OscType::Array(x) => assert_eq!(a, x.content),
                    _ => panic!(),
                }
            }
        }
        _ => panic!("Expected an OSC message!"),
    }
}
<|endoftext|>


<commit_before>#[deriving(Clone)]
pub enum CellValue {
  alive, dead
}  // enum CellValue

#[deriving(Clone)]
pub struct Cell {
  value: CellValue
}  // struct Cell

impl Cell {
fn print(&self) {
  match self.value {
    alive => print!("x"),
    dead  => print!(".")
  }
}  // fn print
}  // impl Cell

pub struct Row(uint);
pub struct Column(uint);

#[deriving(Clone)]
pub struct Grid {
  inner: ~[~[Cell]]
} // struct Grid

impl Grid {
pub fn print(&self) {
  for row in range(0, self.height()) {
    for column in range(0, self.width()) {
      self.inner[row][column].print();
    }
    println!("");
  }
}  // fn print

pub fn cell_alive(&self, Row(row): Row, Column(column): Column) -> uint {
  if (row >= self.height() || column >= self.width()) {
    return 0;
  }
  return match self.inner[row][column].value {
   dead  => 0,
   alive => 1
  };
}

pub fn width(&self) -> uint {
  return self.inner[0].len();
}  // fn width

pub fn height(&self) -> uint {
  return self.inner.len();
}  // fn height

}  // impl Grid
<commit_msg>fixed compiler warning.<commit_after>#[deriving(Clone)]
pub enum CellValue {
  alive, dead
}  // enum CellValue

#[deriving(Clone)]
pub struct Cell {
  value: CellValue
}  // struct Cell

impl Cell {
fn print(&self) {
  match self.value {
    alive => print!("x"),
    dead  => print!(".")
  }
}  // fn print
}  // impl Cell

pub struct Row(uint);
pub struct Column(uint);

#[deriving(Clone)]
pub struct Grid {
  inner: ~[~[Cell]]
} // struct Grid

impl Grid {
pub fn print(&self) {
  for row in range(0, self.height()) {
    for column in range(0, self.width()) {
      self.inner[row][column].print();
    }
    println!("");
  }
}  // fn print

pub fn cell_alive(&self, Row(row): Row, Column(column): Column) -> uint {
  if row >= self.height() || column >= self.width() {
    return 0;
  }
  return match self.inner[row][column].value {
   dead  => 0,
   alive => 1
  };
}

pub fn width(&self) -> uint {
  return self.inner[0].len();
}  // fn width

pub fn height(&self) -> uint {
  return self.inner.len();
}  // fn height

}  // impl Grid
<|endoftext|>


<commit_before>use parking_lot::RwLock;
use std::any::Any;
use std::rc::Rc;

use super::Mode;

use crate::core::codepointinfo::CodepointInfo;
use crate::core::codepointinfo::TextStyle;

use crate::core::editor::check_view_by_id;
use crate::core::editor::get_view_by_id;
use crate::core::editor::InputStageActionMap;

use crate::core::modes::core_mode::split_with_direction;
use crate::core::Editor;
use crate::core::EditorEnv;

use crate::core::view;
use crate::core::view::ContentFilter;

use crate::core::view::FilterIo;
use crate::core::view::LayoutDirection;
use crate::core::view::LayoutEnv;
use crate::core::view::LayoutOperation;

use crate::core::view::View;

use crate::core::buffer::BufferBuilder;
use crate::core::buffer::BufferKind;

pub struct BasicEditorMode {
    // add common fields
}
pub struct BasicEditorModeContext {
    // add per view fields
}

impl<'a> Mode for BasicEditorMode {
    fn name(&self) -> &'static str {
        &"basic-editor"
    }

    fn build_action_map(&self) -> InputStageActionMap<'static> {
        let mut map = InputStageActionMap::new();
        Self::register_input_stage_actions(&mut map);
        map
    }

    fn alloc_ctx(&self) -> Box<dyn Any> {
        dbg_println!("alloc BasicEditorMode-mode ctx");
        let ctx = BasicEditorModeContext {};
        Box::new(ctx)
    }

    fn configure_view(
        &mut self,
        mut editor: &mut Editor<'static>,
        mut env: &mut EditorEnv<'static>,
        mut view: &mut View<'static>,
    ) {
        let buffer = view.buffer();

        let status_buffer = BufferBuilder::new(BufferKind::File)
            .buffer_name("status-bar")
            .internal(true)
            //           .use_buffer_log(false)
            .finalize();

        // hsplit

        // children_layout_and_modes
        let ops_modes = vec![
            // title
            (
                LayoutOperation::Fixed {
                    size: 1 + 0, /* nano-like */
                },
                buffer.clone(),
                vec![], // TODO(ceg): title-mode
            ),
            // main text view
            (
                LayoutOperation::RemainMinus { minus: 1 },
                buffer.clone(),
                vec!["simple-view".to_owned()],
            ),
            /*
            (
                LayoutOperation::Fixed { size: 1 },
                None,
                vec!["hsplit-mode".to_owned()],
            ),
            */
            // status bar
            (
                LayoutOperation::RemainPercent { p: 100.0 },
                status_buffer,
                vec!["status-mode".to_owned()],
            ),
        ];

        let mut layout_ops = vec![];
        let mut buffers = vec![];
        let mut modes = vec![];

        for e in &ops_modes {
            layout_ops.push(e.0.clone());
            buffers.push(e.1.clone());
            modes.push(e.2.clone());
        }

        let (width, height) = view.dimension();
        dbg_println!("width {}  height {}", width, height);

        split_with_direction(
            &mut editor,
            &mut env,
            &mut view,
            width,
            height,
            LayoutDirection::Vertical,
            &layout_ops,
            &buffers,
            &modes,
        );

        // mark children as non destroyable
        for i in 0..view.children.len() {
            let vid = view.children[i].id;
            let v = get_view_by_id(editor, vid);
            v.write().destroyable = false;
        }

        // TODO(ceg): put some kind of label/name? on
        // like view.label = 'text-view'
        // like view.label = 'status-line'
        // view.children_by_label<String, (vid, index)>
        view.destroyable = false; // root view

        // set focus on text view : TODO(ceg): title mode + configure
        let title_view_id = view.children[0].id;
        let v = get_view_by_id(editor, title_view_id);
        v.write()
            .compose_content_filters
            .borrow_mut()
            .push(Box::new(BasicEditorTitle::new()));

        // set focus on text view (simple-view mode)
        let simple_view_idx = 1;
        let simple_view_id = view.children[simple_view_idx].id;
        view.focus_to = Some(simple_view_id); // TODO(ceg):

        // TODO(ceg): status mode + configure
        // setup status view
        let status_view_idx = view.children.len() - 1;
        let status_view_id = view.children[status_view_idx].id;

        // set status_view_id
        view.status_view_id = Some(status_view_id);
        env.status_view_id = Some(status_view_id);
    }
}

impl BasicEditorMode {
    pub fn new() -> Self {
        dbg_println!("BasicEditorMode");
        BasicEditorMode {}
    }

    pub fn register_input_stage_actions<'a>(_map: &'a mut InputStageActionMap<'a>) {}
}

///////////////////////////////////////////////////////////////////////////////////////////////////

struct BasicEditorTitle {
    title: String,
    width: usize,
    height: usize,
}

impl BasicEditorTitle {
    pub fn new() -> Self {
        BasicEditorTitle {
            title: String::new(),
            width: 0,
            height: 0,
        }
    }
}

use crate::core::VERSION;

impl ContentFilter<'_> for BasicEditorTitle {
    fn name(&self) -> &'static str {
        &"editor-title"
    }

    fn setup(
        &mut self,
        editor: &Editor<'static>,
        env: &mut LayoutEnv,
        view: &Rc<RwLock<View>>,
        _parent_view: Option<&View<'static>>,
    ) {
        self.width = env.screen.width();
        self.height = env.screen.height();

        let mut w = self.width;
        self.title = format!("unlimitED {} ", VERSION);
        w = w.saturating_sub(self.title.len());

        let view = view.read();
        let d = view.buffer().unwrap();
        let d = d.read();
        let mut buffer_info = format!("{}", d.name);
        let dlen = buffer_info.len();
        if w > dlen {
            let margin = 1; // w / 2 - dlen / 2;
            let margin = (0..margin).map(|_| " ").collect::<String>();
            self.title.push_str(&margin);
        }

        if d.changed {
            buffer_info.push_str("* ");
        } else {
            buffer_info.push_str("  ");
            //            buffer_info.push_str(" ❰❱❮❯");
        }
        if d.is_syncing {
            buffer_info.push_str("(sync)");
        }

        buffer_info.push_str(&format!(" {} bytes", d.size()));
        buffer_info.push_str(&format!(" (F1 for help)"));

        if env.focus_view_id != view::Id(0) {
            if let Some(_v) = check_view_by_id(editor, env.focus_view_id) {
                buffer_info.push_str(&format!(" (focus vid: {:?})", env.focus_view_id));
            }
        }

        self.title.push_str(&buffer_info);
    }

    fn run(
        &mut self,
        _view: &View,
        env: &mut LayoutEnv,
        _filter_in: &[FilterIo],
        _filter_out: &mut Vec<FilterIo>,
    ) {
        let color = TextStyle::title_color();
        let bg_color = TextStyle::title_bg_color();

        let width = env.screen.width();
        let mut count = 0;
        for c in self.title.chars().take(width) {
            let mut cpi = CodepointInfo::new();
            cpi.displayed_cp = c;
            cpi.style.color = color;
            cpi.style.bg_color = bg_color;
            let (b, _) = env.screen.push(cpi.clone());
            if !b {
                break;
            }
            count += 1;
        }

        let _fill = ' ' as char;
        let mut cpi = CodepointInfo::new();
        cpi.style.color = color;
        cpi.style.bg_color = bg_color;
        for _i in count..width {
            let (b, _) = env.screen.push(cpi.clone());
            if !b {
                break;
            }
        }

        env.quit = true;
    }

    fn finish(&mut self, _view: &View, _env: &mut LayoutEnv) {}
}
<commit_msg>save some codepoints for later use<commit_after>use parking_lot::RwLock;
use std::any::Any;
use std::rc::Rc;

use super::Mode;

use crate::core::codepointinfo::CodepointInfo;
use crate::core::codepointinfo::TextStyle;

use crate::core::editor::check_view_by_id;
use crate::core::editor::get_view_by_id;
use crate::core::editor::InputStageActionMap;

use crate::core::modes::core_mode::split_with_direction;
use crate::core::Editor;
use crate::core::EditorEnv;

use crate::core::view;
use crate::core::view::ContentFilter;

use crate::core::view::FilterIo;
use crate::core::view::LayoutDirection;
use crate::core::view::LayoutEnv;
use crate::core::view::LayoutOperation;

use crate::core::view::View;

use crate::core::buffer::BufferBuilder;
use crate::core::buffer::BufferKind;

pub struct BasicEditorMode {
    // add common fields
}
pub struct BasicEditorModeContext {
    // add per view fields
}

impl<'a> Mode for BasicEditorMode {
    fn name(&self) -> &'static str {
        &"basic-editor"
    }

    fn build_action_map(&self) -> InputStageActionMap<'static> {
        let mut map = InputStageActionMap::new();
        Self::register_input_stage_actions(&mut map);
        map
    }

    fn alloc_ctx(&self) -> Box<dyn Any> {
        dbg_println!("alloc BasicEditorMode-mode ctx");
        let ctx = BasicEditorModeContext {};
        Box::new(ctx)
    }

    fn configure_view(
        &mut self,
        mut editor: &mut Editor<'static>,
        mut env: &mut EditorEnv<'static>,
        mut view: &mut View<'static>,
    ) {
        let buffer = view.buffer();

        let status_buffer = BufferBuilder::new(BufferKind::File)
            .buffer_name("status-bar")
            .internal(true)
            //           .use_buffer_log(false)
            .finalize();

        // hsplit

        // children_layout_and_modes
        let ops_modes = vec![
            // title
            (
                LayoutOperation::Fixed {
                    size: 1 + 0, /* nano-like */
                },
                buffer.clone(),
                vec![], // TODO(ceg): title-mode
            ),
            // main text view
            (
                LayoutOperation::RemainMinus { minus: 1 },
                buffer.clone(),
                vec!["simple-view".to_owned()],
            ),
            /*
            (
                LayoutOperation::Fixed { size: 1 },
                None,
                vec!["hsplit-mode".to_owned()],
            ),
            */
            // status bar
            (
                LayoutOperation::RemainPercent { p: 100.0 },
                status_buffer,
                vec!["status-mode".to_owned()],
            ),
        ];

        let mut layout_ops = vec![];
        let mut buffers = vec![];
        let mut modes = vec![];

        for e in &ops_modes {
            layout_ops.push(e.0.clone());
            buffers.push(e.1.clone());
            modes.push(e.2.clone());
        }

        let (width, height) = view.dimension();
        dbg_println!("width {}  height {}", width, height);

        split_with_direction(
            &mut editor,
            &mut env,
            &mut view,
            width,
            height,
            LayoutDirection::Vertical,
            &layout_ops,
            &buffers,
            &modes,
        );

        // mark children as non destroyable
        for i in 0..view.children.len() {
            let vid = view.children[i].id;
            let v = get_view_by_id(editor, vid);
            v.write().destroyable = false;
        }

        // TODO(ceg): put some kind of label/name? on
        // like view.label = 'text-view'
        // like view.label = 'status-line'
        // view.children_by_label<String, (vid, index)>
        view.destroyable = false; // root view

        // set focus on text view : TODO(ceg): title mode + configure
        let title_view_id = view.children[0].id;
        let v = get_view_by_id(editor, title_view_id);
        v.write()
            .compose_content_filters
            .borrow_mut()
            .push(Box::new(BasicEditorTitle::new()));

        // set focus on text view (simple-view mode)
        let simple_view_idx = 1;
        let simple_view_id = view.children[simple_view_idx].id;
        view.focus_to = Some(simple_view_id); // TODO(ceg):

        // TODO(ceg): status mode + configure
        // setup status view
        let status_view_idx = view.children.len() - 1;
        let status_view_id = view.children[status_view_idx].id;

        // set status_view_id
        view.status_view_id = Some(status_view_id);
        env.status_view_id = Some(status_view_id);
    }
}

impl BasicEditorMode {
    pub fn new() -> Self {
        dbg_println!("BasicEditorMode");
        BasicEditorMode {}
    }

    pub fn register_input_stage_actions<'a>(_map: &'a mut InputStageActionMap<'a>) {}
}

///////////////////////////////////////////////////////////////////////////////////////////////////

struct BasicEditorTitle {
    title: String,
    width: usize,
    height: usize,
}

impl BasicEditorTitle {
    pub fn new() -> Self {
        BasicEditorTitle {
            title: String::new(),
            width: 0,
            height: 0,
        }
    }
}

use crate::core::VERSION;

impl ContentFilter<'_> for BasicEditorTitle {
    fn name(&self) -> &'static str {
        &"editor-title"
    }

    fn setup(
        &mut self,
        editor: &Editor<'static>,
        env: &mut LayoutEnv,
        view: &Rc<RwLock<View>>,
        _parent_view: Option<&View<'static>>,
    ) {
        self.width = env.screen.width();
        self.height = env.screen.height();

        let mut w = self.width;
        self.title = format!("unlimitED {} ", VERSION);
        w = w.saturating_sub(self.title.len());

        let view = view.read();
        let d = view.buffer().unwrap();
        let d = d.read();
        let mut buffer_info = format!("{}", d.name);
        let dlen = buffer_info.len();
        if w > dlen {
            let margin = 1; // w / 2 - dlen / 2;
            let margin = (0..margin).map(|_| " ").collect::<String>();
            self.title.push_str(&margin);
        }

        if d.changed {
            buffer_info.push_str("* ");
        } else {
            buffer_info.push_str("  ");
            //            buffer_info.push_str(" ❰❱❮❯  ◄ ► ▼ ▲");
        }
        if d.is_syncing {
            buffer_info.push_str("(sync)");
        }

        buffer_info.push_str(&format!(" {} bytes", d.size()));
        buffer_info.push_str(&format!(" (F1 for help)"));

        if env.focus_view_id != view::Id(0) {
            if let Some(_v) = check_view_by_id(editor, env.focus_view_id) {
                buffer_info.push_str(&format!(" (focus vid: {:?})", env.focus_view_id));
            }
        }

        self.title.push_str(&buffer_info);
    }

    fn run(
        &mut self,
        _view: &View,
        env: &mut LayoutEnv,
        _filter_in: &[FilterIo],
        _filter_out: &mut Vec<FilterIo>,
    ) {
        let color = TextStyle::title_color();
        let bg_color = TextStyle::title_bg_color();

        let width = env.screen.width();
        let mut count = 0;
        for c in self.title.chars().take(width) {
            let mut cpi = CodepointInfo::new();
            cpi.displayed_cp = c;
            cpi.style.color = color;
            cpi.style.bg_color = bg_color;
            let (b, _) = env.screen.push(cpi.clone());
            if !b {
                break;
            }
            count += 1;
        }

        let _fill = ' ' as char;
        let mut cpi = CodepointInfo::new();
        cpi.style.color = color;
        cpi.style.bg_color = bg_color;
        for _i in count..width {
            let (b, _) = env.screen.push(cpi.clone());
            if !b {
                break;
            }
        }

        env.quit = true;
    }

    fn finish(&mut self, _view: &View, _env: &mut LayoutEnv) {}
}
<|endoftext|>


<commit_before>extern crate sourcemap;

use sourcemap::SourceMap;

#[test]
fn test_basic_name_mapping() {
    let input = r#"{"version":3,"file":"test.min.js","sources":["test.js"],"names":["makeAFailure","testingStuff","Error","onSuccess","data","onFailure","invoke","cb","failed","test","value"],"mappings":"AAAA,GAAIA,cAAe,WACjB,QAASC,KACP,GAAIA,GAAe,EACnB,MAAM,IAAIC,OAAMD,GAGlB,QAASE,GAAUC,GACjBH,IAGF,QAASI,GAAUD,GACjB,KAAM,IAAIF,OAAM,WAGlB,QAASI,GAAOF,GACd,GAAIG,GAAK,IACT,IAAIH,EAAKI,OAAQ,CACfD,EAAKF,MACA,CACLE,EAAKJ,EAEPI,EAAGH,GAGL,QAASK,KACP,GAAIL,IAAQI,OAAQ,KAAME,MAAO,GACjCJ,GAAOF,GAGT,MAAOK","sourcesContent":["var makeAFailure = (function() {\n  function testingStuff() {\n    var testingStuff = 42;\n    throw new Error(testingStuff);\n  }\n\n  function onSuccess(data) {\n    testingStuff();\n  }\n\n  function onFailure(data) {\n    throw new Error('failed!');\n  }\n\n  function invoke(data) {\n    var cb = null;\n    if (data.failed) {\n      cb = onFailure;\n    } else {\n      cb = onSuccess;\n    }\n    cb(data);\n  }\n\n  function test() {\n    var data = {failed: true, value: 42};\n    invoke(data);\n  }\n\n  return test;\n})();\n"]}"#.as_bytes();
    let minified_file = r#"var makeAFailure=function(){function n(){var n=42;throw new Error(n)}function r(r){n()}function e(n){throw new Error("failed!")}function i(n){var i=null;if(n.failed){i=e}else{i=r}i(n)}function u(){var n={failed:true,value:42};i(n)}return u}();"#;
    let sm = SourceMap::from_reader(input).unwrap();

    let tok = sm.lookup_token(0, 45).unwrap();
    assert_eq!(tok.get_name(), Some("testingStuff"));
    assert_eq!(tok.get_minified_name(minified_file), Some("n"));

    let tok = sm.lookup_token(0, 66).unwrap();
    assert_eq!(tok.get_name(), Some("testingStuff"));
    assert_eq!(tok.get_minified_name(minified_file), Some("n"));

    let tok = sm.lookup_token(0, 96).unwrap();
    assert_eq!(tok.get_name(), Some("onFailure"));
    assert_eq!(tok.get_minified_name(minified_file), Some("e"));

    let name = sm.map_minified_name(0, 107, "e", minified_file);
    assert_eq!(name, Some("onFailure"));
}
<commit_msg>Added test for a complete traceback that also aliases a name<commit_after>extern crate sourcemap;

use sourcemap::SourceMap;

#[test]
fn test_basic_name_mapping() {
    let input = r#"{"version":3,"file":"test.min.js","sources":["test.js"],"names":["makeAFailure","testingStuff","Error","onSuccess","data","onFailure","invoke","cb","failed","test","value"],"mappings":"AAAA,GAAIA,cAAe,WACjB,QAASC,KACP,GAAIA,GAAe,EACnB,MAAM,IAAIC,OAAMD,GAGlB,QAASE,GAAUC,GACjBH,IAGF,QAASI,GAAUD,GACjB,KAAM,IAAIF,OAAM,WAGlB,QAASI,GAAOF,GACd,GAAIG,GAAK,IACT,IAAIH,EAAKI,OAAQ,CACfD,EAAKF,MACA,CACLE,EAAKJ,EAEPI,EAAGH,GAGL,QAASK,KACP,GAAIL,IAAQI,OAAQ,KAAME,MAAO,GACjCJ,GAAOF,GAGT,MAAOK","sourcesContent":["var makeAFailure = (function() {\n  function testingStuff() {\n    var testingStuff = 42;\n    throw new Error(testingStuff);\n  }\n\n  function onSuccess(data) {\n    testingStuff();\n  }\n\n  function onFailure(data) {\n    throw new Error('failed!');\n  }\n\n  function invoke(data) {\n    var cb = null;\n    if (data.failed) {\n      cb = onFailure;\n    } else {\n      cb = onSuccess;\n    }\n    cb(data);\n  }\n\n  function test() {\n    var data = {failed: true, value: 42};\n    invoke(data);\n  }\n\n  return test;\n})();\n"]}"#.as_bytes();
    let minified_file = r#"var makeAFailure=function(){function n(){var n=42;throw new Error(n)}function r(r){n()}function e(n){throw new Error("failed!")}function i(n){var i=null;if(n.failed){i=e}else{i=r}i(n)}function u(){var n={failed:true,value:42};i(n)}return u}();"#;
    let sm = SourceMap::from_reader(input).unwrap();

    let tok = sm.lookup_token(0, 45).unwrap();
    assert_eq!(tok.get_name(), Some("testingStuff"));
    assert_eq!(tok.get_minified_name(minified_file), Some("n"));

    let tok = sm.lookup_token(0, 66).unwrap();
    assert_eq!(tok.get_name(), Some("testingStuff"));
    assert_eq!(tok.get_minified_name(minified_file), Some("n"));

    let tok = sm.lookup_token(0, 96).unwrap();
    assert_eq!(tok.get_name(), Some("onFailure"));
    assert_eq!(tok.get_minified_name(minified_file), Some("e"));

    let name = sm.get_original_function_name(0, 107, "e", minified_file);
    assert_eq!(name, Some("onFailure"));

    // a stacktrae
    let locs = &[
        (0, 107, "e", "onFailure"),
        (0, 179, "i", "invoke"),
        (0, 226, "u", "test"),
    ];

    for &(line, col, minified_name, original_name) in locs {
        let name = sm.get_original_function_name(line, col, minified_name, minified_file);
        assert_eq!(name, Some(original_name));
    }
}
<|endoftext|>