<commit_before>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;

fn start(n_tasks: int, token: int) {
    let (tx, mut rx) = channel();
    tx.send(token).unwrap();
    for i in range(2, n_tasks + 1) {
        let (tx, next_rx) = channel();
        Thread::spawn(move|| roundtrip(i, tx, rx));
        rx = next_rx;
    }
    Thread::spawn(move|| roundtrip(1, tx, rx));
}

fn roundtrip(id: int, tx: Sender<int>, rx: Receiver<int>) {
    for token in rx.iter() {
        if token == 1 {
            println!("{}", id);
            break;
        }
        tx.send(token - 1).unwrap();
    }
}

fn main() {
    let args = std::os::args();
    let args = args.as_slice();
    let token = if std::os::getenv("RUST_BENCH").is_some() {
        2000000
    } else {
        args.get(1).and_then(|arg| arg.parse()).unwrap_or(1000)
    };
    let n_tasks = args.get(2)
                      .and_then(|arg| arg.parse())
                      .unwrap_or(503);

    start(n_tasks, token);
}
<commit_msg>fix shootout-threadring.rs<commit_after>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2012-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

use std::sync::mpsc::{channel, Sender, Receiver};
use std::thread::Thread;

fn start(n_tasks: i32, token: i32) {
    let (tx, mut rx) = channel();
    tx.send(token).unwrap();
    let mut guards = Vec::with_capacity(n_tasks as usize);
    for i in 2 .. n_tasks + 1 {
        let (tx, next_rx) = channel();
        let cur_rx = std::mem::replace(&mut rx, next_rx);
        guards.push(Thread::scoped(move|| roundtrip(i, tx, cur_rx)));
    }
    let guard = Thread::scoped(move|| roundtrip(1, tx, rx));
}

fn roundtrip(id: i32, tx: Sender<i32>, rx: Receiver<i32>) {
    for token in rx.iter() {
        if token == 1 {
            println!("{}", id);
            break;
        }
        tx.send(token - 1).unwrap();
    }
}

fn main() {
    let args = std::os::args();
    let token = if std::os::getenv("RUST_BENCH").is_some() {
        2000000
    } else {
        args.get(1).and_then(|arg| arg.parse()).unwrap_or(1000)
    };
    let n_tasks = args.get(2)
                      .and_then(|arg| arg.parse())
                      .unwrap_or(503);

    start(n_tasks, token);
}
<|endoftext|>


<commit_before>// -*- rust -*-

use std;
import std._str;

type t = tag(make_t(str), clam());

fn main() {
  let str s = "hi";     // ref up
  let t x = make_t(s);  // ref up

  alt (x) {
    case (make_t(y)) { log y; }  // ref up and ref down
    case (_) { log "?"; fail; }
  }

  log _str.refcount(s);
  check (_str.refcount(s) == 2u);
}
<commit_msg>Modify alt-pattern-drop.rs to also insure the slot bound in the pattern doesn't also get dropped (again) at the end of the block containing the alt.<commit_after>// -*- rust -*-

use std;
import std._str;

type t = tag(make_t(str), clam());

fn foo(str s) {
  let t x = make_t(s);  // ref up

  alt (x) {
    case (make_t(y)) { log y; }  // ref up then down
    case (_) { log "?"; fail; }
  }

  log _str.refcount(s);
  check (_str.refcount(s) == 3u);
}

fn main() {
  let str s = "hi";     // ref up
  foo(s);               // ref up then down
  log _str.refcount(s);
  check (_str.refcount(s) == 1u);
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue-27697<commit_after>// run-pass

use std::ops::Deref;

trait MyTrait {
    fn do_something(&self);
    fn as_str(&self) -> &str;
}

impl Deref for dyn MyTrait {
    type Target = str;
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

fn trait_object_does_something(t: &dyn MyTrait) {
    t.do_something()
}

fn main() {}
<|endoftext|>


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

// This test is for Windows only.
// ignore-android
// ignore-bitrig
// ignore-macos
// ignore-dragonfly
// ignore-freebsd
// ignore-haiku
// ignore-ios
// ignore-linux
// ignore-netbsd
// ignore-openbsd
// ignore-solaris
// ignore-emscripten

// aux-build:dummy.rs
// aux-build:wrapper.rs

extern crate wrapper;

// Check that external symbols coming from foreign dylibs are adorned with 'dllimport',
// whereas symbols coming from foreign staticlibs are not. (RFC-1717)

// CHECK: @dylib_global1 = external dllimport local_unnamed_addr global i32
// CHECK: @dylib_global2 = external dllimport local_unnamed_addr global i32
// CHECK: @static_global1 = external local_unnamed_addr global i32
// CHECK: @static_global2 = external local_unnamed_addr global i32

// CHECK: declare dllimport i32 @dylib_func1(i32)
// CHECK: declare dllimport i32 @dylib_func2(i32)
// CHECK: declare i32 @static_func1(i32)
// CHECK: declare i32 @static_func2(i32)

#[link(name = "dummy", kind="dylib")]
extern "C" {
    pub fn dylib_func1(x: i32) -> i32;
    pub static dylib_global1: i32;
}

#[link(name = "dummy", kind="static")]
extern "C" {
    pub fn static_func1(x: i32) -> i32;
    pub static static_global1: i32;
}

fn main() {
    unsafe {
        dylib_func1(dylib_global1);
        wrapper::dylib_func2(wrapper::dylib_global2);

        static_func1(static_global1);
        wrapper::static_func2(wrapper::static_global2);
    }
}
<commit_msg>Ignore test on -windows-gnu.<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// This test is for *-windows-msvc only.
// ignore-gnu
// ignore-android
// ignore-bitrig
// ignore-macos
// ignore-dragonfly
// ignore-freebsd
// ignore-haiku
// ignore-ios
// ignore-linux
// ignore-netbsd
// ignore-openbsd
// ignore-solaris
// ignore-emscripten

// aux-build:dummy.rs
// aux-build:wrapper.rs

extern crate wrapper;

// Check that external symbols coming from foreign dylibs are adorned with 'dllimport',
// whereas symbols coming from foreign staticlibs are not. (RFC-1717)

// CHECK: @dylib_global1 = external dllimport local_unnamed_addr global i32
// CHECK: @dylib_global2 = external dllimport local_unnamed_addr global i32
// CHECK: @static_global1 = external local_unnamed_addr global i32
// CHECK: @static_global2 = external local_unnamed_addr global i32

// CHECK: declare dllimport i32 @dylib_func1(i32)
// CHECK: declare dllimport i32 @dylib_func2(i32)
// CHECK: declare i32 @static_func1(i32)
// CHECK: declare i32 @static_func2(i32)

#[link(name = "dummy", kind="dylib")]
extern "C" {
    pub fn dylib_func1(x: i32) -> i32;
    pub static dylib_global1: i32;
}

#[link(name = "dummy", kind="static")]
extern "C" {
    pub fn static_func1(x: i32) -> i32;
    pub static static_global1: i32;
}

fn main() {
    unsafe {
        dylib_func1(dylib_global1);
        wrapper::dylib_func2(wrapper::dylib_global2);

        static_func1(static_global1);
        wrapper::static_func2(wrapper::static_global2);
    }
}
<|endoftext|>


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

#![feature(overloaded_calls)]

// Make sure we don't ICE when making an overloaded call with the
// wrong arity.

fn _foo<F: Fn()> (f: F) {
    |t| f(t); //~ ERROR E0058
}

fn main() {}
<|endoftext|>


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

fn f<F, R>(_: F) where F: Fn() -> R {
}

fn main() {
    f(|| -> ! { () });
//~^ ERROR: computation may converge in a function marked as diverging [E0270]
}
<|endoftext|>


<commit_before><commit_msg>A simple helloworld-like example available by default<commit_after>// Эта строка является комментарием и она будет проигнорирована компилятором\n
// Протестировать код можно нажав на кнопку "Run" вот тут ->\n
// так же можно использовать клавиатуру, нажав сочетание клавиш "Ctrl + Enter"\n
\n
// Этот код можно редактировать не стесняясь, дерзайте!\n
// Всегда можно вернуть оригинальный код, нажав на кнопку "Reset" вот тут ->\n
\n
// Это главная функция. С неё начинается исполнение любой программы\n
fn main() {\n
    // Следующий код будет исполнен в момент, когда будет запущен исполняемый файл\n
    // Отображаем текст в консоли\n
    println!("Привет, мир!");\n
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue-54067<commit_after>// check-pass
// ignore-emscripten no llvm_asm! support

#![feature(llvm_asm)]

pub fn boot(addr: Option<u32>) {
    unsafe {
        llvm_asm!("mov sp, $0"::"r" (addr));
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>finish new<commit_after>pub fn is_anagram(s: String, t: String) -> bool {
    if s.len() != t.len() {
        return false;
    };

    let length = s.len();
    let mut s_bytes = s.into_bytes();
    let mut t_bytes = t.into_bytes();

    s_bytes.sort();
    t_bytes.sort();
    println!("{:?},{:?}", s_bytes, t_bytes);

    for i in 0..length {
        if s_bytes[i] != t_bytes[i] {
            return false;
        }
    }

    true
}

fn main() {
    println!(
        "{:?}",
        is_anagram(String::from("anagram"), String::from("nagaram"))
    );
}
<|endoftext|>


<commit_before><commit_msg>Add game backend engine<commit_after>pub type Row = [Player; 3];

pub type Field = [Row; 3];

pub type Coords = (usize, usize);

/// Must return `Coords` or `None` if a player chooses to surrender.
pub type PlayerController = fn(game: &Game) -> Option<Coords>;

#[derive(Copy, Clone, PartialEq)]
pub enum Player {
    Nobody,
    X,
    O,
}

pub struct Game {
    current_player: Player,
    field: Field,
    player1: PlayerController,
    player2: PlayerController,
}

impl Game {
    pub fn new(player1: PlayerController, player2: PlayerController) -> Game {
        Game {
            field: [[Player::Nobody; 3]; 3],
            current_player: Player::X,
            player1: player1,
            player2: player2,
        }
    }

    pub fn field(&self) -> &Field {
        &self.field
    }

    pub fn current_player(&self) -> Player {
        self.current_player
    }

    pub fn play(&mut self) -> Player {
        loop {
            match self.current_player_coords() {
                Some((row, col)) => {
                    if !self.cell_is_empty((row, col)) {
                        panic!("player tries to set occupied cell - cheating!")
                    }
                    self.field[row][col] = self.current_player;
                },
                _ => { self.switch_player(); return self.current_player },
            };

            match self.winner() {
                Some(winner) => return winner,
                _ => self.switch_player(),
            }
        }
    }

    pub fn cell_is_empty(&self, coords: Coords) -> bool {
        let (row, col) = coords;
        self.field[row][col] == Player::Nobody
    }

    fn current_player_coords(&self) -> Option<Coords> {
        match self.current_player {
            Player::X => (self.player1)(&self),
            Player::O => (self.player2)(&self),
            _ => panic!("current player can't be Nobody"),
        }
    }

    fn switch_player(&mut self) {
        if self.current_player == Player::X {
            self.current_player = Player::O
        } else if self.current_player == Player::O {
            self.current_player = Player::X
        }
    }

    /// Returns `Player` if it is already defined, otherwise `None`.
    fn winner(&self) -> Option<Player> {
        self.row_winner(self.row(0))
            .or( self.row_winner(self.row(1)) )
            .or( self.row_winner(self.row(2)) )
            .or( self.row_winner(self.col(0)) )
            .or( self.row_winner(self.col(1)) )
            .or( self.row_winner(self.col(2)) )
            .or( self.row_winner(self.diagonal()) )
            .or( self.row_winner(self.reverse_diagonal()) )
            .or( if self.has_empty_cell() { None } else { Some(Player::Nobody) } )
    }

    fn has_empty_cell(&self) -> bool {
        for row in &self.field {
            for col in row {
                if *col == Player::Nobody {
                    return true;
                }
            }
        }
        false
    }

    /// Returns `Player` if it is already defined, otherwise `None`.
    fn row_winner(&self, row: Vec<Player>) -> Option<Player> {
        if row[0] != Player::Nobody && row[0] == row[1] && row[1] == row[2] {
            Some(row[0])
        } else {
            None
        }
    }

    fn row(&self, number: usize) -> Vec<Player> {
        self.field[number].to_vec()
    }

    fn col(&self, number: usize) -> Vec<Player> {
        self.field.iter().map(|row| row[number]).collect()
    }

    fn diagonal(&self) -> Vec<Player> {
        self.field.iter().enumerate().map(|(i, row)| row[0 + i]).collect()
    }

    fn reverse_diagonal(&self) -> Vec<Player> {
        self.field.iter().enumerate().map(|(i, row)| row[2 - i]).collect()
    }

}
<|endoftext|>


<commit_before><commit_msg>re-added the meshbatch example<commit_after>//! An example of how to use an `InstanceArray` to draw custom `Mesh`es with instanced draws.

use ggez::event;
use ggez::graphics::{self, Color, DrawParam};
use ggez::{Context, GameResult};
use glam::*;
use oorandom::Rand32;
use std::env;
use std::f32::consts::PI;
use std::path;

const TWO_PI: f32 = 2.0 * PI;

struct MainState {
    mesh_batch: graphics::InstanceArray,
    mesh: graphics::Mesh,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let mut rng = Rand32::new(12345);
        let mesh = graphics::Mesh::from_data(
            ctx,
            graphics::MeshBuilder::new()
                .circle(
                    graphics::DrawMode::stroke(4.0),
                    Vec2::new(0.0, 0.0),
                    8.0,
                    1.0,
                    (0, 0, 255).into(),
                )?
                .line(
                    &[Vec2::new(0.0, 0.0), Vec2::new(8.0, 0.0)],
                    2.0,
                    (255, 255, 0).into(),
                )?
                .build(),
        );

        // Generate enough instances to fill the entire screen
        let size = ctx.gfx.drawable_size();
        let items_x = (size.0 / 16.0) as u32;
        let items_y = (size.1 / 16.0) as u32;
        let mut mesh_batch = graphics::InstanceArray::new(ctx, None, items_x * items_y);

        mesh_batch.set((0..items_x).flat_map(|x| {
            (0..items_y).map(move |y| {
                let x = x as f32;
                let y = y as f32;

                DrawParam::new()
                    .dest(Vec2::new(x * 16.0, y * 16.0))
                    .rotation(rng.rand_float() * TWO_PI)
            })
        }));

        let s = MainState { mesh_batch, mesh };
        Ok(s)
    }
}

impl event::EventHandler<ggez::GameError> for MainState {
    #[allow(clippy::needless_range_loop)]
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        if ctx.time.ticks() % 100 == 0 {
            println!("Delta frame time: {:?} ", ctx.time.delta());
            println!("Average FPS: {}", ctx.time.fps());
        }

        // Update first 50 instances in the mesh batch
        let delta_time = ctx.time.delta().as_secs_f32() * 1000.0;
        let instances = self.mesh_batch.instances();

        let mut updated_params = Vec::new();
        for i in 0..50 {
            let mut p = instances[i as usize];
            if let graphics::Transform::Values {
                ref mut rotation, ..
            } = p.transform
            {
                if (i % 2) == 0 {
                    *rotation += 0.001 * TWO_PI * delta_time;
                    if *rotation > TWO_PI {
                        *rotation -= TWO_PI;
                    }
                } else {
                    *rotation -= 0.001 * TWO_PI * delta_time;
                    if *rotation < 0.0 {
                        *rotation += TWO_PI;
                    }
                }
            }
            updated_params.push(p);
        }
        for i in 0..50 {
            // TODO: this is pretty inefficient and also a bit ridiculous
            //       a way to update parts of an InstanceArray would be good to have
            self.mesh_batch.update(i, updated_params[i as usize]);
        }

        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        let mut canvas = graphics::Canvas::from_frame(ctx, Color::BLACK);

        // Draw the batch
        canvas.draw_instanced_mesh(
            self.mesh.clone(),
            &self.mesh_batch,
            DrawParam::new().dest(glam::Vec2::new(5.0, 8.0)),
        );

        canvas.finish(ctx)?;
        Ok(())
    }
}

pub fn main() -> GameResult {
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let cb = ggez::ContextBuilder::new("meshbatch", "ggez").add_resource_path(resource_dir);
    let (mut ctx, event_loop) = cb.build()?;

    let state = MainState::new(&mut ctx)?;
    event::run(ctx, event_loop, state)
}
<|endoftext|>


<commit_before><commit_msg>tests: Add test case. Closes #3250<commit_after>#[auto_serialize]

type t = (uint, uint);

fn main() { }
<|endoftext|>


<commit_before><commit_msg>Construct new struct CLI for structopt<commit_after>#[derive(StructOpt, PartialEq, Debug)]
pub struct App {
  #[structopt(short="c", long = "config", help = "Sets a custom config file")]
  pub config: String,
  #[structopt(subcommand)]
  pub cmd: SubCmd,
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum SubCmd {
  #[structopt(name = "shutdown", about = "shuts down the proxy without waiting for connections to finish")]
  Shutdown {
    #[structopt(short = "h", long = "hard")]
    hard: Option<bool>
  },
  #[structopt(name = "upgrade", about = "upgrades the proxy")]
  Upgrades,
  #[structopt(name = "status", about = "gets information on the running workers")]
  Status,
  #[structopt(name = "metrics", about = "gets statistics on the master and its workers")]
  Metrics,
  #[structopt(name = "logging", about = "change logging level")]
  Logging {
    #[structopt(short = "l", long = "level", help = "change logging level")]
    level: String
  },
  #[structopt(name = "state", about = "state management")]
  State {
    #[structopt(subcommand)]
    cmd: StateCmd,
  },
  #[structopt(name = "application", about = "application management")]
  Application {
    #[structopt(subcommand)]
    cmd: ApplicationCmd,
  },
  #[structopt(name = "backend", about = "backend management")]
  Backend {
    #[structopt(subcommand)]
    cmd: BackendCmd,
  },
  #[structopt(name = "frontend", about = "frontend management")]
  Frontend {
    #[structopt(subcommand)]
    cmd: FrontendCmd,
  },
  #[structopt(name = "certificate", about = "certificate management")]
  Certificate {
    #[structopt(subcommand)]
    cmd: CertificateCmd,
  },
  #[structopt(name = "query", about = "configuration state verification")]
  Query {
    #[structopt(subcommand)]
    cmd: QueryCmd,
  }
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum StateCmd {
  #[structopt(name = "save", about = "Save state to that file")]
  Save {
    #[structopt(short = "h", long = "hard")]
    file: String,
  },
  #[structopt(name = "load", about = "Load state from that file")]
  Load {
    #[structopt(short = "h", long = "hard")]
    file: String,
  },
  #[structopt(name = "dump")]
  Dump,
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum ApplicationCmd {
  #[structopt(name = "remove")]
  Remove {
    #[structopt(short = "i", long = "id")]
    id: String,
  },
  #[structopt(name = "add")]
  Add{
    #[structopt(short = "h", long = "hard")]
    id: String,
    #[structopt(short = "s", long = "sticky session")]
    sticky_session: Option<bool>,
  },
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum BackendCmd {
  #[structopt(name = "remove")]
  Remove {
    #[structopt(short = "i", long = "id")]
    id: String,
    #[structopt(long = "instance-id")]
    instance_id: String,
    #[structopt(long = "ip")]
    ip: String,
    #[structopt(short = "p", long = "prot")]
    port: u16,
  },
  #[structopt(name = "add")]
  Add {
    #[structopt(short = "i", long = "id")]
    id: String,
    #[structopt(long = "instance-id")]
    instance_id: String,
    #[structopt(long = "ip")]
    ip: String,
    #[structopt(short = "p", long = "prot")]
    port: u16,
  },
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum FrontendCmd {
  #[structopt(name = "add")]
  Add {
    #[structopt(short = "i", long = "id", help = "app id of the frontend")]
    id: String,
    #[structopt(short = "host", long = "hostname")]
    hostname: String,
    #[structopt(short = "p", long = "path", help="URL prefix of the frontend")]
    path_begin: Option<String>,
    #[structopt(long = "certificate", help="path to a certificate file")]
    path_to_certificate: Option<String>,
  },
  #[structopt(name = "remove")]
  Remove {
    #[structopt(short = "i", long = "id", help = "app id of the frontend")]
    id: String,
    #[structopt(short = "host", long = "hostname")]
    hostname: String,
    #[structopt(short = "p", long = "path", help="URL prefix of the frontend")]
    path_begin: Option<String>,
    #[structopt(long = "certificate", help="path to a certificate file")]
    path_to_certificate: Option<String>,
  },
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum CertificateCmd {
  #[structopt(name = "add")]
  Add {
    #[structopt(long = "certificate", help = "path to the certificate")]
    certificate: String,
    #[structopt(long = "certificate-chain", help = "path to the certificate chain")]
    chain: String,
    #[structopt(long = "key", help = "path to the key")]
    key: Option<String>,
  },
  #[structopt(name = "remove")]
  Remove {
    #[structopt(short = "cert", long = "certificate", help = "path to the certificate")]
    certificate: String,
  },
}

#[derive(StructOpt, PartialEq, Debug)]
pub enum QueryCmd {
  #[structopt(name = "applications")]
  Applications {
    #[structopt(short = "i", long="id", help="application identifier")]
    id: Option<String>
  }
}<|endoftext|>


<commit_before>#![feature(asm)]
#![feature(box_syntax)]
#![feature(core_simd)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![no_std]

extern crate redox_alloc as alloc;

use core::clone::Clone;
use core::mem::size_of;
use core::result::Result;

use common::memory::*;
use common::string::*;
use common::vector::*;
use common::url::*;

use drivers::keyboard::*;
use drivers::mouse::*;

use graphics::color::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::session::*;

/* TEST { */
use core::any::Any;
use core::ops::Fn;
use core::option::Option;

use alloc::boxed::*;

use common::debug::*;
/* } TEST */

#[path="../src/common"]
mod common {
    pub mod debug;
    pub mod memory;
    pub mod pci;
    pub mod pio;
    pub mod string;
    pub mod vector;
    pub mod url;
}

#[path="../src/drivers"]
mod drivers {
    pub mod disk;
    pub mod keyboard;
    pub mod mouse;
}

#[path="../src/filesystems"]
mod filesystems {
    pub mod unfs;
}

#[path="../src/graphics"]
mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

#[path="../src/programs"]
mod programs {
    pub mod session;
}

/* TEST { */
struct EventA {
    x: isize,
    y: isize
}

struct EventB {
    txt: String
}

struct EventListener {
    fn_ptr: Box<Fn(&Box<Any>)>
}

impl EventListener {
    pub fn call(&self, event: &Box<Any>){
        (*self.fn_ptr)(event);
    }
}

fn test(){
    let mut events: Vector<Box<Any>> = Vector::new();

    events.push(box EventB {
        txt: "first test".to_string()
    });
    events.push(box EventA {
        x: 2,
        y: 3
    });
    events.push(box EventB {
        txt: "second test".to_string()
    });

    let mut listeners: Vector<Box<EventListener>> = Vector::new();

    listeners.push(box EventListener {
        fn_ptr: box |event: &Box<Any>| {
            match event.downcast_ref::<EventA>() {
                Option::Some(a) => {
                    d("Event A ");
                    dd(a.x as usize);
                    d(", ");
                    dd(a.y as usize);
                    dl();
                },
                Option::None => ()
            }
        }
    });

    listeners.push(box EventListener {
        fn_ptr: box |event: &Box<Any>| {
            match event.downcast_ref::<EventB>() {
                Option::Some(b) => {
                    d("Event B ");
                    b.txt.d();
                    dl();
                },
                Option::None => ()
            }
        }
    });

    for event in events.iter() {
        for listener in listeners.iter() {
            listener.call(event);
        }
    }
}
/* } TEST */

pub struct Application {
    window: Window,
    output: String,
    command: String,
    offset: usize,
    scroll: Point,
    wrap: bool
}

impl Application {
    fn append(&mut self, line: String) {
        self.output = self.output.clone() + line + "\n";
    }

    #[allow(unused_variables)]
    fn on_command(&mut self, session: &Session){
        let mut args: Vector<String> = Vector::<String>::new();
        for arg in self.command.split(" ".to_string()) {
            if arg.len() > 0 {
                args.push(arg);
            }
        }
        match args.get(0) {
            Result::Ok(cmd) => {
                if *cmd == "echo".to_string() {
                    let mut echo = String::new();
                    for i in 1..args.len() {
                        match args.get(i) {
                            Result::Ok(arg) => {
                                if echo.len() == 0 {
                                    echo = arg.clone();
                                }else{
                                    echo = echo + " " + arg.clone();
                                }
                            },
                            Result::Err(_) => ()
                        }
                    }
                    self.append(echo);
                }else if *cmd == "exit".to_string() {
                    self.window.closed = true;
                }else if *cmd == "test".to_string() {
                    test();
                }else if *cmd == "url".to_string() {
                    match args.get(1) {
                        Result::Ok(url_string) => {
                            let url = URL::from_string(url_string.clone());
                            self.append(url.to_string());

                            unsafe{
                                let self_ptr: *mut Application = self; // BIG NO NO
                                session.on_url(&url, box move |response|{
                                    (*self_ptr).append(response);
                                })
                            }
                        },
                        Result::Err(_) => {
                            for module in session.modules.iter() {
                                let scheme = module.scheme();
                                if scheme.len() > 0 {
                                    self.append(scheme);
                                }
                            }
                        }
                    }
                }else{
                    self.append("Commands:  echo  exit  url".to_string());
                }
            },
            Result::Err(_) => ()
        }
    }
}

impl SessionItem for Application {
    #[allow(unused_variables)]
    fn new() -> Application {
        Application {
            window: Window{
                point: Point::new(220, 100),
                size: Size::new(576, 400),
                title: String::from_str("Terminal"),
                title_color: Color::new(0, 0, 0),
                border_color: Color::new(192, 192, 255),
                content_color: Color::alpha(128, 128, 160, 192),
                shaded: false,
                closed: false,
                dragging: false,
                last_mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            output: String::new(),
            command: String::new(),
            offset: 0,
            scroll: Point::new(0, 0),
            wrap: true
        }
    }

    fn draw(&mut self, session: &Session, updates: &mut SessionUpdates) -> bool{
        let display = &session.display;
        if self.window.draw(display) {
            let scroll = self.scroll;

            let mut col = -scroll.x;
            let cols = self.window.size.width as isize / 8;
            let mut row = -scroll.y;
            let rows = self.window.size.height as isize / 16;

            for c in self.output.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '#', Color::new(255, 255, 255));
                col += 2;
            }

            let mut i = 0;
            for c in self.command.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                    let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                    display.char(point, '_', Color::new(255, 255, 255));
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(255, 255, 255));
                    }
                    col += 1;
                }

                i += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll.x;
                row += 1;
            }

            if row >= rows {
                self.scroll.y += row - rows + 1;
                updates.redraw = REDRAW_ALL;
            }

            if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '_', Color::new(255, 255, 255));
            }

            return true;
        }else{
            return false;
        }
    }

    #[allow(unused_variables)]
    fn on_key(&mut self, session: &Session, updates: &mut SessionUpdates, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x01 => self.window.closed = true,
                0x47 => self.offset = 0,
                0x4B => if self.offset > 0 {
                    self.offset -= 1;
                },
                0x4D => if self.offset < self.command.len() {
                    self.offset += 1;
                },
                0x4F => self.offset = self.command.len(),
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => {
                    if self.offset > 0 {
                        self.command = self.command.substr(0, self.offset - 1) + self.command.substr(self.offset, self.command.len() - self.offset);
                        self.offset -= 1;
                    }
                }
                '\x1B' => self.command = String::new(),
                '\n' => {
                    if self.command.len() > 0 {
                        self.output = self.output.clone() + "# ".to_string() + self.command.clone() + "\n";
                        self.on_command(session);
                        self.command = String::new();
                        self.offset = 0;
                    }
                },
                _ => {
                    self.command = self.command.substr(0, self.offset) + key_event.character + self.command.substr(self.offset, self.command.len() - self.offset);
                    self.offset += 1;
                }
            }
        }
    }

    #[allow(unused_variables)]
    fn on_mouse(&mut self, session: &Session, updates: &mut SessionUpdates, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(session.mouse_point, mouse_event, allow_catch);
    }
}

//Class wrappers

static mut application: *mut Application = 0 as *mut Application;

#[no_mangle]
pub unsafe fn entry(){
    application = alloc(size_of::<Application>()) as *mut Application;
    *application = Application::new();
}

#[no_mangle]
pub unsafe fn draw(session: &Session, updates: &mut SessionUpdates) -> bool{
    if application as usize > 0 {
        return (*application).draw(session, updates);
    }else{
        return false;
    }
}

#[no_mangle]
pub unsafe fn on_key(session: &Session, updates: &mut SessionUpdates, key_event: KeyEvent){
    if application as usize > 0{
        (*application).on_key(session, updates, key_event);
    }
}

#[no_mangle]
pub unsafe fn on_mouse(session: &Session, updates: &mut SessionUpdates, mouse_event: MouseEvent, allow_catch: bool) -> bool{
    if application as usize > 0 {
        return (*application).on_mouse(session, updates, mouse_event, allow_catch);
    }else{
        return false;
    }
}

#[no_mangle]
pub extern "C" fn memmove(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        if src < dst {
            let mut i = len;
            while i > 0 {
                i -= 1;
                *dst.offset(i) = *src.offset(i);
            }
        }else{
            let mut i = 0;
            while i < len {
                *dst.offset(i) = *src.offset(i);
                i += 1;
            }
        }
    }
}

#[no_mangle]
pub extern "C" fn memcpy(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        let mut i = 0;
        while i < len {
            *dst.offset(i) = *src.offset(i);
            i += 1;
        }
    }
}

#[no_mangle]
pub extern "C" fn memset(src: *mut u8, c: i32, len: isize) {
    unsafe {
        let mut i = 0;
        while i < len {
            *src.offset(i) = c as u8;
            i += 1;
        }
    }
}
<commit_msg>Do not do page-breaking thing in example.rs<commit_after>#![feature(asm)]
#![feature(box_syntax)]
#![feature(core_simd)]
#![feature(core_slice_ext)]
#![feature(core_str_ext)]
#![feature(fundamental)]
#![feature(lang_items)]
#![feature(no_std)]
#![feature(unboxed_closures)]
#![feature(unsafe_no_drop_flag)]
#![no_std]

extern crate redox_alloc as alloc;

use core::clone::Clone;
use core::mem::size_of;
use core::result::Result;

use common::memory::*;
use common::string::*;
use common::vector::*;
use common::url::*;

use drivers::keyboard::*;
use drivers::mouse::*;

use graphics::color::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::session::*;

/* TEST { */
use core::any::Any;
use core::ops::Fn;
use core::option::Option;

use alloc::boxed::*;

use common::debug::*;
/* } TEST */

#[path="../src/common"]
mod common {
    pub mod debug;
    pub mod memory;
    pub mod pci;
    pub mod pio;
    pub mod string;
    pub mod vector;
    pub mod url;
}

#[path="../src/drivers"]
mod drivers {
    pub mod disk;
    pub mod keyboard;
    pub mod mouse;
}

#[path="../src/filesystems"]
mod filesystems {
    pub mod unfs;
}

#[path="../src/graphics"]
mod graphics {
    pub mod bmp;
    pub mod color;
    pub mod display;
    pub mod point;
    pub mod size;
    pub mod window;
}

#[path="../src/programs"]
mod programs {
    pub mod session;
}

/* TEST { */
struct EventA {
    x: isize,
    y: isize
}

struct EventB {
    txt: String
}

struct EventListener {
    fn_ptr: Box<Fn(&Box<Any>)>
}

impl EventListener {
    pub fn call(&self, event: &Box<Any>){
        (*self.fn_ptr)(event);
    }
}

fn test(){
    let mut events: Vector<Box<Any>> = Vector::new();

    events.push(box EventB {
        txt: "first test".to_string()
    });
    events.push(box EventA {
        x: 2,
        y: 3
    });
    events.push(box EventB {
        txt: "second test".to_string()
    });

    let mut listeners: Vector<Box<EventListener>> = Vector::new();

    listeners.push(box EventListener {
        fn_ptr: box |event: &Box<Any>| {
            match event.downcast_ref::<EventA>() {
                Option::Some(a) => {
                    d("Event A ");
                    dd(a.x as usize);
                    d(", ");
                    dd(a.y as usize);
                    dl();
                },
                Option::None => ()
            }
        }
    });

    listeners.push(box EventListener {
        fn_ptr: box |event: &Box<Any>| {
            match event.downcast_ref::<EventB>() {
                Option::Some(b) => {
                    d("Event B ");
                    b.txt.d();
                    dl();
                },
                Option::None => ()
            }
        }
    });

    for event in events.iter() {
        for listener in listeners.iter() {
            listener.call(event);
        }
    }
}
/* } TEST */

pub struct Application {
    window: Window,
    output: String,
    command: String,
    offset: usize,
    scroll: Point,
    wrap: bool
}

impl Application {
    fn append(&mut self, line: String) {
        self.output = self.output.clone() + line + "\n";
    }

    #[allow(unused_variables)]
    fn on_command(&mut self, session: &Session){
        let mut args: Vector<String> = Vector::<String>::new();
        for arg in self.command.split(" ".to_string()) {
            if arg.len() > 0 {
                args.push(arg);
            }
        }
        match args.get(0) {
            Result::Ok(cmd) => {
                if *cmd == "echo".to_string() {
                    let mut echo = String::new();
                    for i in 1..args.len() {
                        match args.get(i) {
                            Result::Ok(arg) => {
                                if echo.len() == 0 {
                                    echo = arg.clone();
                                }else{
                                    echo = echo + " " + arg.clone();
                                }
                            },
                            Result::Err(_) => ()
                        }
                    }
                    self.append(echo);
                }else if *cmd == "exit".to_string() {
                    self.window.closed = true;
                }else if *cmd == "test".to_string() {
                    test();
                }else if *cmd == "url".to_string() {
                    match args.get(1) {
                        Result::Ok(url_string) => {
                            let url = URL::from_string(url_string.clone());
                            self.append(url.to_string());
                        },
                        Result::Err(_) => {
                            for module in session.modules.iter() {
                                let scheme = module.scheme();
                                if scheme.len() > 0 {
                                    self.append(scheme);
                                }
                            }
                        }
                    }
                }else{
                    self.append("Commands:  echo  exit  url".to_string());
                }
            },
            Result::Err(_) => ()
        }
    }
}

impl SessionItem for Application {
    #[allow(unused_variables)]
    fn new() -> Application {
        Application {
            window: Window{
                point: Point::new(220, 100),
                size: Size::new(576, 400),
                title: String::from_str("Terminal"),
                title_color: Color::new(0, 0, 0),
                border_color: Color::new(192, 192, 255),
                content_color: Color::alpha(128, 128, 160, 192),
                shaded: false,
                closed: false,
                dragging: false,
                last_mouse_point: Point::new(0, 0),
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            output: String::new(),
            command: String::new(),
            offset: 0,
            scroll: Point::new(0, 0),
            wrap: true
        }
    }

    fn draw(&mut self, session: &Session, updates: &mut SessionUpdates) -> bool{
        let display = &session.display;
        if self.window.draw(display) {
            let scroll = self.scroll;

            let mut col = -scroll.x;
            let cols = self.window.size.width as isize / 8;
            let mut row = -scroll.y;
            let rows = self.window.size.height as isize / 16;

            for c in self.output.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(224, 224, 224));
                    }
                    col += 1;
                }
            }

            if col > -scroll.x {
                col = -scroll.x;
                row += 1;
            }

            if col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '#', Color::new(255, 255, 255));
                col += 2;
            }

            let mut i = 0;
            for c in self.command.chars(){
                if self.wrap && col >= cols {
                    col = -scroll.x;
                    row += 1;
                }

                if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                    let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                    display.char(point, '_', Color::new(255, 255, 255));
                }

                if c == '\n' {
                    col = -scroll.x;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col >= 0 && col < cols && row >= 0 && row < rows{
                        let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                        display.char(point, c, Color::new(255, 255, 255));
                    }
                    col += 1;
                }

                i += 1;
            }

            if self.wrap && col >= cols {
                col = -scroll.x;
                row += 1;
            }

            if row >= rows {
                self.scroll.y += row - rows + 1;
                updates.redraw = REDRAW_ALL;
            }

            if self.offset == i && col >= 0 && col < cols && row >= 0 && row < rows{
                let point = Point::new(self.window.point.x + 8 * col, self.window.point.y + 16 * row);
                display.char(point, '_', Color::new(255, 255, 255));
            }

            return true;
        }else{
            return false;
        }
    }

    #[allow(unused_variables)]
    fn on_key(&mut self, session: &Session, updates: &mut SessionUpdates, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x01 => self.window.closed = true,
                0x47 => self.offset = 0,
                0x4B => if self.offset > 0 {
                    self.offset -= 1;
                },
                0x4D => if self.offset < self.command.len() {
                    self.offset += 1;
                },
                0x4F => self.offset = self.command.len(),
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => {
                    if self.offset > 0 {
                        self.command = self.command.substr(0, self.offset - 1) + self.command.substr(self.offset, self.command.len() - self.offset);
                        self.offset -= 1;
                    }
                }
                '\x1B' => self.command = String::new(),
                '\n' => {
                    if self.command.len() > 0 {
                        self.output = self.output.clone() + "# ".to_string() + self.command.clone() + "\n";
                        self.on_command(session);
                        self.command = String::new();
                        self.offset = 0;
                    }
                },
                _ => {
                    self.command = self.command.substr(0, self.offset) + key_event.character + self.command.substr(self.offset, self.command.len() - self.offset);
                    self.offset += 1;
                }
            }
        }
    }

    #[allow(unused_variables)]
    fn on_mouse(&mut self, session: &Session, updates: &mut SessionUpdates, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(session.mouse_point, mouse_event, allow_catch);
    }
}

//Class wrappers

static mut application: *mut Application = 0 as *mut Application;

#[no_mangle]
pub unsafe fn entry(){
    application = alloc(size_of::<Application>()) as *mut Application;
    *application = Application::new();
}

#[no_mangle]
pub unsafe fn draw(session: &Session, updates: &mut SessionUpdates) -> bool{
    if application as usize > 0 {
        return (*application).draw(session, updates);
    }else{
        return false;
    }
}

#[no_mangle]
pub unsafe fn on_key(session: &Session, updates: &mut SessionUpdates, key_event: KeyEvent){
    if application as usize > 0{
        (*application).on_key(session, updates, key_event);
    }
}

#[no_mangle]
pub unsafe fn on_mouse(session: &Session, updates: &mut SessionUpdates, mouse_event: MouseEvent, allow_catch: bool) -> bool{
    if application as usize > 0 {
        return (*application).on_mouse(session, updates, mouse_event, allow_catch);
    }else{
        return false;
    }
}

#[no_mangle]
pub extern "C" fn memmove(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        if src < dst {
            let mut i = len;
            while i > 0 {
                i -= 1;
                *dst.offset(i) = *src.offset(i);
            }
        }else{
            let mut i = 0;
            while i < len {
                *dst.offset(i) = *src.offset(i);
                i += 1;
            }
        }
    }
}

#[no_mangle]
pub extern "C" fn memcpy(dst: *mut u8, src: *const u8, len: isize){
    unsafe {
        let mut i = 0;
        while i < len {
            *dst.offset(i) = *src.offset(i);
            i += 1;
        }
    }
}

#[no_mangle]
pub extern "C" fn memset(src: *mut u8, c: i32, len: isize) {
    unsafe {
        let mut i = 0;
        while i < len {
            *src.offset(i) = c as u8;
            i += 1;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix: Only view entry if output is not a pipe<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Google Inc. All rights reserved.
//
// 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.

//! Structured representation of a plugin's features and capabilities.

use std::io::{BufReader, Write};
use std::env;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use std::process::{Command, Stdio};

use serde_json::Value;

use xi_rpc::RpcLoop;

use tabs::ViewIdentifier;
use syntax::SyntaxDefinition;
use super::PluginManagerRef;
use super::{Plugin, PluginRef};

// optional environment variable for debug plugin executables
static PLUGIN_DIR: &'static str = "XI_PLUGIN_DIR";

// example plugins. Eventually these should be loaded from disk.
pub fn debug_plugins() -> Vec<PluginDescription> {
    use self::PluginActivation::*;
    use self::SyntaxDefinition::*;
    let plugin_dir = match env::var(PLUGIN_DIR).map(PathBuf::from) {
        Ok(p) => p,
        Err(_) => env::current_exe().unwrap().parent().unwrap().to_owned(),
    };
    print_err!("looking for debug plugins in {:?}", plugin_dir);

    let make_path = |p: &str| -> PathBuf {
        let mut pb = plugin_dir.clone();
        pb.push(p);
        pb
    };

    vec![
        PluginDescription::new("syntect", "0.0", make_path("xi-syntect-plugin"),
        vec![Autorun]),
        PluginDescription::new("braces", "0.0", make_path("bracket_example.py"),
        Vec::new()),
        PluginDescription::new("spellcheck", "0.0", make_path("spellcheck.py"),
        vec![OnSyntax(Markdown), OnSyntax(Plaintext)]),
        PluginDescription::new("shouty", "0.0", make_path("shouty.py"),
        Vec::new()),
    ].iter()
        .filter(|desc|{
            if !desc.exec_path.exists() {
                print_err!("missing plugin {} at {:?}", desc.name, desc.exec_path);
                false
            } else {
                true
            }
        })
        .map(|desc| desc.to_owned())
        .collect::<Vec<_>>()
}

/// Describes attributes and capabilities of a plugin.
///
/// Note: - these will eventually be loaded from manifest files.
#[derive(Debug, Clone)]
pub struct PluginDescription {
    pub name: String,
    pub version: String,
    //scope: PluginScope,
    // more metadata ...
    /// path to plugin executable
    pub exec_path: PathBuf,
    /// Events that cause this plugin to run
    pub activations: Vec<PluginActivation>,
}

/// `PluginActivation`s represent events that trigger running a plugin.
#[derive(Debug, Clone)]
pub enum PluginActivation {
    /// Always run this plugin, when available.
    Autorun,
    /// Run this plugin if the provided SyntaxDefinition is active.
    OnSyntax(SyntaxDefinition),
    /// Run this plugin in response to a given command.
    #[allow(dead_code)]
    OnCommand,
}

impl PluginDescription {
    fn new<S, P>(name: S, version: S, exec_path: P,
                 activations: Vec<PluginActivation>) -> Self
        where S: Into<String>, P: Into<PathBuf>
    {
        PluginDescription {
            name: name.into(),
            version: version.into(),
            exec_path: exec_path.into(),
            activations: activations,
        }
    }

    /// Starts the executable described in this `PluginDescription`.
    //TODO: make this a free function, & move out of manifest
    pub fn launch<W, C>(&self, manager_ref: &PluginManagerRef<W>,
                        view_id: &ViewIdentifier, completion: C)
        where W: Write + Send + 'static,
              C: FnOnce(Result<PluginRef<W>, &'static str>) + Send + 'static
              // TODO: a real result type
    {
        let path = self.exec_path.clone();
        let view_id = view_id.to_owned();
        let manager_ref = manager_ref.to_weak();
        let description = self.clone();

        thread::spawn(move || {
            print_err!("starting plugin at path {:?}", path);
            let mut child = Command::new(&path)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()
                .expect("plugin failed to start");
            let child_stdin = child.stdin.take().unwrap();
            let child_stdout = child.stdout.take().unwrap();
            let mut looper = RpcLoop::new(child_stdin);
            let peer = looper.get_peer();
            peer.send_rpc_notification("ping", &Value::Array(Vec::new()));
            let plugin = Plugin {
                peer: peer,
                process: child,
                manager: manager_ref,
                description: description,
                view_id: view_id,
            };
            let mut plugin_ref = PluginRef(Arc::new(Mutex::new(plugin)));
            completion(Ok(plugin_ref.clone()));
            looper.mainloop(|| BufReader::new(child_stdout), &mut plugin_ref);
        });
    }
}

<commit_msg>Disable autoload py3 plugins<commit_after>// Copyright 2017 Google Inc. All rights reserved.
//
// 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.

//! Structured representation of a plugin's features and capabilities.

use std::io::{BufReader, Write};
use std::env;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::thread;
use std::process::{Command, Stdio};

use serde_json::Value;

use xi_rpc::RpcLoop;

use tabs::ViewIdentifier;
use syntax::SyntaxDefinition;
use super::PluginManagerRef;
use super::{Plugin, PluginRef};

// optional environment variable for debug plugin executables
static PLUGIN_DIR: &'static str = "XI_PLUGIN_DIR";

// example plugins. Eventually these should be loaded from disk.
pub fn debug_plugins() -> Vec<PluginDescription> {
    use self::PluginActivation::*;
    use self::SyntaxDefinition::*;
    let plugin_dir = match env::var(PLUGIN_DIR).map(PathBuf::from) {
        Ok(p) => p,
        Err(_) => env::current_exe().unwrap().parent().unwrap().to_owned(),
    };
    print_err!("looking for debug plugins in {:?}", plugin_dir);

    let make_path = |p: &str| -> PathBuf {
        let mut pb = plugin_dir.clone();
        pb.push(p);
        pb
    };

    vec![
        PluginDescription::new("syntect", "0.0", make_path("xi-syntect-plugin"),
        vec![Autorun]),
        PluginDescription::new("braces", "0.0", make_path("bracket_example.py"),
        Vec::new()),
        PluginDescription::new("spellcheck", "0.0", make_path("spellcheck.py"),
        Vec::new()),
        PluginDescription::new("shouty", "0.0", make_path("shouty.py"),
        Vec::new()),
    ].iter()
        .filter(|desc|{
            if !desc.exec_path.exists() {
                print_err!("missing plugin {} at {:?}", desc.name, desc.exec_path);
                false
            } else {
                true
            }
        })
        .map(|desc| desc.to_owned())
        .collect::<Vec<_>>()
}

/// Describes attributes and capabilities of a plugin.
///
/// Note: - these will eventually be loaded from manifest files.
#[derive(Debug, Clone)]
pub struct PluginDescription {
    pub name: String,
    pub version: String,
    //scope: PluginScope,
    // more metadata ...
    /// path to plugin executable
    pub exec_path: PathBuf,
    /// Events that cause this plugin to run
    pub activations: Vec<PluginActivation>,
}

/// `PluginActivation`s represent events that trigger running a plugin.
#[derive(Debug, Clone)]
pub enum PluginActivation {
    /// Always run this plugin, when available.
    Autorun,
    /// Run this plugin if the provided SyntaxDefinition is active.
    OnSyntax(SyntaxDefinition),
    /// Run this plugin in response to a given command.
    #[allow(dead_code)]
    OnCommand,
}

impl PluginDescription {
    fn new<S, P>(name: S, version: S, exec_path: P,
                 activations: Vec<PluginActivation>) -> Self
        where S: Into<String>, P: Into<PathBuf>
    {
        PluginDescription {
            name: name.into(),
            version: version.into(),
            exec_path: exec_path.into(),
            activations: activations,
        }
    }

    /// Starts the executable described in this `PluginDescription`.
    //TODO: make this a free function, & move out of manifest
    pub fn launch<W, C>(&self, manager_ref: &PluginManagerRef<W>,
                        view_id: &ViewIdentifier, completion: C)
        where W: Write + Send + 'static,
              C: FnOnce(Result<PluginRef<W>, &'static str>) + Send + 'static
              // TODO: a real result type
    {
        let path = self.exec_path.clone();
        let view_id = view_id.to_owned();
        let manager_ref = manager_ref.to_weak();
        let description = self.clone();

        thread::spawn(move || {
            print_err!("starting plugin at path {:?}", path);
            let mut child = Command::new(&path)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()
                .expect("plugin failed to start");
            let child_stdin = child.stdin.take().unwrap();
            let child_stdout = child.stdout.take().unwrap();
            let mut looper = RpcLoop::new(child_stdin);
            let peer = looper.get_peer();
            peer.send_rpc_notification("ping", &Value::Array(Vec::new()));
            let plugin = Plugin {
                peer: peer,
                process: child,
                manager: manager_ref,
                description: description,
                view_id: view_id,
            };
            let mut plugin_ref = PluginRef(Arc::new(Mutex::new(plugin)));
            completion(Ok(plugin_ref.clone()));
            looper.mainloop(|| BufReader::new(child_stdout), &mut plugin_ref);
        });
    }
}

<|endoftext|>


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

//! Report important messages to the user

use libc::c_int;
use glib::translate::ToGlibPtr;

use gtk::MessageType;
use gtk::cast::GTK_INFOBAR;
use gtk::{self, ffi};
use glib::to_gboolean;

/// InfoBar — Report important messages to the user
struct_Widget!(InfoBar);

impl InfoBar {
    pub fn new() -> Option<InfoBar> {
        let tmp_pointer = unsafe { ffi::gtk_info_bar_new() };
        check_pointer!(tmp_pointer, InfoBar)
    }

    pub fn add_action_widget<T: gtk::WidgetTrait>(&mut self, child: &T, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_add_action_widget(GTK_INFOBAR(self.pointer), child.unwrap_widget(), response_id as c_int)
        }
    }

    pub fn add_button(&mut self, button_text: &str, response_id: i32) -> gtk::Button {
        let button = unsafe {
            ffi::gtk_info_bar_add_button(GTK_INFOBAR(self.pointer), button_text.borrow_to_glib().0, response_id as c_int)
        };
        gtk::FFIWidget::wrap_widget(button)
    }

    pub fn set_response_sensitive(&mut self, response_id: i32, setting: bool) -> () {
        unsafe { ffi::gtk_info_bar_set_response_sensitive(GTK_INFOBAR(self.pointer), response_id as c_int, to_gboolean(setting)); }
    }

    pub fn set_default_response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_set_default_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn set_message_type(&mut self, message_type: MessageType) -> () {
        unsafe {
            ffi::gtk_info_bar_set_message_type(GTK_INFOBAR(self.pointer), message_type);
        }
    }

    pub fn get_message_type(&mut self) -> MessageType {
        unsafe {
            ffi::gtk_info_bar_get_message_type(GTK_INFOBAR(self.pointer))
        }
    }

    #[cfg(any(feature = "GTK_3_10",feature = "GTK_3_12", feature = "GTK_3_14"))]
    pub fn show_close_button(&mut self, show: bool) -> () {
         unsafe { ffi::gtk_info_bar_set_show_close_button(GTK_INFOBAR(self.pointer), to_gboolean(show)); }
    }

    #[cfg(any(feature = "GTK_3_10",feature = "GTK_3_12", feature = "GTK_3_14"))]
    pub fn get_show_close_button(&self) -> bool {
        unsafe { to_bool(ffi::gtk_info_bar_get_show_close_button(GTK_INFOBAR(self.pointer))) }
    }
}

impl_drop!(InfoBar);
impl_TraitWidget!(InfoBar);

impl gtk::ContainerTrait for InfoBar {}
impl gtk::BoxTrait for InfoBar {}
impl gtk::OrientableTrait for InfoBar {}

impl_widget_events!(InfoBar);
<commit_msg>Add to_bool back (removed in #239)<commit_after>// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk.  If not, see <http://www.gnu.org/licenses/>.

//! Report important messages to the user

use libc::c_int;
use glib::translate::ToGlibPtr;

use gtk::MessageType;
use gtk::cast::GTK_INFOBAR;
use gtk::{self, ffi};
use glib::{to_bool, to_gboolean};

/// InfoBar — Report important messages to the user
struct_Widget!(InfoBar);

impl InfoBar {
    pub fn new() -> Option<InfoBar> {
        let tmp_pointer = unsafe { ffi::gtk_info_bar_new() };
        check_pointer!(tmp_pointer, InfoBar)
    }

    pub fn add_action_widget<T: gtk::WidgetTrait>(&mut self, child: &T, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_add_action_widget(GTK_INFOBAR(self.pointer), child.unwrap_widget(), response_id as c_int)
        }
    }

    pub fn add_button(&mut self, button_text: &str, response_id: i32) -> gtk::Button {
        let button = unsafe {
            ffi::gtk_info_bar_add_button(GTK_INFOBAR(self.pointer), button_text.borrow_to_glib().0, response_id as c_int)
        };
        gtk::FFIWidget::wrap_widget(button)
    }

    pub fn set_response_sensitive(&mut self, response_id: i32, setting: bool) -> () {
        unsafe { ffi::gtk_info_bar_set_response_sensitive(GTK_INFOBAR(self.pointer), response_id as c_int, to_gboolean(setting)); }
    }

    pub fn set_default_response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_set_default_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn response(&mut self, response_id: i32) -> () {
        unsafe {
            ffi::gtk_info_bar_response(GTK_INFOBAR(self.pointer), response_id as c_int)
        }
    }

    pub fn set_message_type(&mut self, message_type: MessageType) -> () {
        unsafe {
            ffi::gtk_info_bar_set_message_type(GTK_INFOBAR(self.pointer), message_type);
        }
    }

    pub fn get_message_type(&mut self) -> MessageType {
        unsafe {
            ffi::gtk_info_bar_get_message_type(GTK_INFOBAR(self.pointer))
        }
    }

    #[cfg(any(feature = "GTK_3_10",feature = "GTK_3_12", feature = "GTK_3_14"))]
    pub fn show_close_button(&mut self, show: bool) -> () {
         unsafe { ffi::gtk_info_bar_set_show_close_button(GTK_INFOBAR(self.pointer), to_gboolean(show)); }
    }

    #[cfg(any(feature = "GTK_3_10",feature = "GTK_3_12", feature = "GTK_3_14"))]
    pub fn get_show_close_button(&self) -> bool {
        unsafe { to_bool(ffi::gtk_info_bar_get_show_close_button(GTK_INFOBAR(self.pointer))) }
    }
}

impl_drop!(InfoBar);
impl_TraitWidget!(InfoBar);

impl gtk::ContainerTrait for InfoBar {}
impl gtk::BoxTrait for InfoBar {}
impl gtk::OrientableTrait for InfoBar {}

impl_widget_events!(InfoBar);
<|endoftext|>


<commit_before>use redox::{Box, String, Url};
use redox::{cmp, mem, ptr};
use redox::fs::File;
use redox::get_slice::GetSlice;
use redox::io::*;
use redox::ops::DerefMut;
use redox::to_num::ToNum;
use redox::syscall::sys_clone;

use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;
use self::session::Session;
use self::window::Window;

pub mod display;
pub mod package;
pub mod scheduler;
pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Option<Box<Resource>> {
        Some(box Resource {
            window: Window::new(self.window.point, self.window.size, self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Option<String> {
        Some(format!("orbital:///{}/{}/{}/{}/{}",
                         self.window.point.x,
                         self.window.point.y,
                         self.window.size.width,
                         self.window.size.height,
                         self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        //Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Some(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize,
                              content.offscreen + self.seek,
                              size);
        }
        self.seek += size;

        return Some(size);
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end, cmp::max(0, offset)),
            SeekFrom::Current(offset) => cmp::min(end, cmp::max(0, self.seek as isize + offset) as usize),
            SeekFrom::End(offset) => cmp::min(end, cmp::max(0, end as isize + offset) as usize),
        };

        return Some(self.seek);
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> bool {
        self.window.redraw();
        true
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Box<Session>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        debugln!("- Starting Orbital");
        debugln!("    Console: Press F1");
        debugln!("    Desktop: Press F2");
        let mut ret = box Scheme {
            session: Session::new(),
            next_x: 0,
            next_y: 0,
        };
        unsafe { session_ptr = ret.session.deref_mut() };
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Option<Box<Resource>> {
        //window://host/path/path/path is the path type we're working with.
        let url = Url::from_str(url_str);

        let host = url.host();
        if host.is_empty() {
            let path = url.path_parts();
            let mut pointx = match path.get(0) {
                Some(x) => x.to_num_signed(),
                None => 0,
            };
            let mut pointy = match path.get(1) {
                Some(y) => y.to_num_signed(),
                None => 0,
            };
            let size_width = match path.get(2) {
                Some(w) => w.to_num(),
                None => 100,
            };
            let size_height = match path.get(3) {
                Some(h) => h.to_num(),
                None => 100,
            };

            let mut title = match path.get(4) {
                Some(t) => t.clone(),
                None => String::new(),
            };
            for i in 5..path.len() {
                if let Some(t) = path.get(i) {
                    title = title + "/" + t;
                }
            }

            if pointx <= 0 || pointy <= 0 {
                if self.next_x > self.session.display.width as isize - size_width as isize {
                    self.next_x = 0;
                }
                self.next_x += 32;
                pointx = self.next_x;

                if self.next_y > self.session.display.height as isize - size_height as isize {
                    self.next_y = 0;
                }
                self.next_y += 32;
                pointy = self.next_y;
            }

            Some(box Resource {
                window: Window::new(Point::new(pointx, pointy), Size::new(size_width, size_height), title),
                seek: 0,
            })
        } else if host == "launch" {
            let path = url.path();

            unsafe {
                let reenable = scheduler::start_no_ints();

                for package in self.session.packages.iter() {
                    let mut accepted = false;
                    for accept in package.accepts.iter() {
                        if (accept.starts_with('*') && path.ends_with(&accept.get_slice(Some(1), None)))
                        || (accept.ends_with('*') && path.starts_with(&accept.get_slice(None, Some(accept.len() - 1))))
                        {
                            accepted = true;
                            break;
                        }
                    }
                    if accepted {
                        let binary = package.binary.clone();
                        println!("Exec {} {}", binary, path);
                        //File::exec(&binary, &[&path]);
                        break;
                    }
                }

                scheduler::end_no_ints(reenable);
            }

            None
        } else {
            None
        }
    }

    pub fn event(&mut self, event: &Event) {
        unsafe {
            let reenable = scheduler::start_no_ints();

            self.session.event(event);

            scheduler::end_no_ints(reenable);

            self.session.redraw();
        }
    }
}

//TODO: This is a hack and it will go away
#[cold]
#[inline(never)]
#[no_mangle]
pub unsafe extern "C" fn _event(scheme: *mut Scheme, event: *const Event) {
    (*scheme).event(&*event);
}
<commit_msg>Do not clone inside of orbital<commit_after>use redox::{Box, String, Url};
use redox::{cmp, mem, ptr};
use redox::fs::File;
use redox::get_slice::GetSlice;
use redox::io::*;
use redox::ops::DerefMut;
use redox::to_num::ToNum;

use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;
use self::session::Session;
use self::window::Window;

pub mod display;
pub mod package;
pub mod scheduler;
pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Option<Box<Resource>> {
        Some(box Resource {
            window: Window::new(self.window.point, self.window.size, self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Option<String> {
        Some(format!("orbital:///{}/{}/{}/{}/{}",
                         self.window.point.x,
                         self.window.point.y,
                         self.window.size.width,
                         self.window.size.height,
                         self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        //Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Some(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize,
                              content.offscreen + self.seek,
                              size);
        }
        self.seek += size;

        return Some(size);
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end, cmp::max(0, offset)),
            SeekFrom::Current(offset) => cmp::min(end, cmp::max(0, self.seek as isize + offset) as usize),
            SeekFrom::End(offset) => cmp::min(end, cmp::max(0, end as isize + offset) as usize),
        };

        return Some(self.seek);
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> bool {
        self.window.redraw();
        true
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Box<Session>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        debugln!("- Starting Orbital");
        debugln!("    Console: Press F1");
        debugln!("    Desktop: Press F2");
        let mut ret = box Scheme {
            session: Session::new(),
            next_x: 0,
            next_y: 0,
        };
        unsafe { session_ptr = ret.session.deref_mut() };
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Option<Box<Resource>> {
        //window://host/path/path/path is the path type we're working with.
        let url = Url::from_str(url_str);

        let host = url.host();
        if host.is_empty() {
            let path = url.path_parts();
            let mut pointx = match path.get(0) {
                Some(x) => x.to_num_signed(),
                None => 0,
            };
            let mut pointy = match path.get(1) {
                Some(y) => y.to_num_signed(),
                None => 0,
            };
            let size_width = match path.get(2) {
                Some(w) => w.to_num(),
                None => 100,
            };
            let size_height = match path.get(3) {
                Some(h) => h.to_num(),
                None => 100,
            };

            let mut title = match path.get(4) {
                Some(t) => t.clone(),
                None => String::new(),
            };
            for i in 5..path.len() {
                if let Some(t) = path.get(i) {
                    title = title + "/" + t;
                }
            }

            if pointx <= 0 || pointy <= 0 {
                if self.next_x > self.session.display.width as isize - size_width as isize {
                    self.next_x = 0;
                }
                self.next_x += 32;
                pointx = self.next_x;

                if self.next_y > self.session.display.height as isize - size_height as isize {
                    self.next_y = 0;
                }
                self.next_y += 32;
                pointy = self.next_y;
            }

            Some(box Resource {
                window: Window::new(Point::new(pointx, pointy), Size::new(size_width, size_height), title),
                seek: 0,
            })
        } else if host == "launch" {
            let path = url.path();

            unsafe {
                let reenable = scheduler::start_no_ints();

                for package in self.session.packages.iter() {
                    let mut accepted = false;
                    for accept in package.accepts.iter() {
                        if (accept.starts_with('*') && path.ends_with(&accept.get_slice(Some(1), None)))
                        || (accept.ends_with('*') && path.starts_with(&accept.get_slice(None, Some(accept.len() - 1))))
                        {
                            accepted = true;
                            break;
                        }
                    }
                    if accepted {
                        let binary = package.binary.clone();
                        println!("Exec {} {}", binary, path);
                        //File::exec(&binary, &[&path]);
                        break;
                    }
                }

                scheduler::end_no_ints(reenable);
            }

            None
        } else {
            None
        }
    }

    pub fn event(&mut self, event: &Event) {
        unsafe {
            let reenable = scheduler::start_no_ints();

            self.session.event(event);

            scheduler::end_no_ints(reenable);

            self.session.redraw();
        }
    }
}

//TODO: This is a hack and it will go away
#[cold]
#[inline(never)]
#[no_mangle]
pub unsafe extern "C" fn _event(scheme: *mut Scheme, event: *const Event) {
    (*scheme).event(&*event);
}
<|endoftext|>


<commit_before>
use super::*;
mod basic_test;
<commit_msg>Fix tests of module `wplot`, test under features<commit_after>
#[ allow( unused_imports ) ]
use super::*;
#[ cfg( feature = "use_std" ) ]
mod basic_test;
<|endoftext|>


<commit_before><commit_msg>Add an example for discard server<commit_after>#[macro_use]
extern crate log;
extern crate env_logger;

extern crate num_cpus;
extern crate futures;
extern crate ruyi;

use std::thread;

use futures::{Future, Stream};

use ruyi::reactor::{IntoStream, IntoTask, Task};
use ruyi::service::tcp::{self, Handler, Session};

#[derive(Clone)]
struct Discard;

impl Handler for Discard {
    fn handle(&mut self, session: Session) -> Task {
        session
            .into_stream()
            .for_each(|data| {
                debug!("Discard:\n{}", data.as_hex_dump());
                Ok(())
            })
            .map_err(|e| error!("{}", e))
            .into_task()
    }
}

fn main() {
    // Initialize logger
    env_logger::init().unwrap();

    let n = num_cpus::get();
    match tcp::Server::with_handler(Discard)
        .port(10009)
        .num_of_workers(n)
        .start() {
        Ok(()) => thread::park(),
        Err(e) => error!("{}", e),
    }
}
<|endoftext|>


<commit_before><commit_msg>Add srandmember documentation<commit_after><|endoftext|>


<commit_before><commit_msg>Solution for cubic ufo in rust<commit_after>use std::io;
use std::f64;
use std::str::FromStr;

fn main() {
    println!("cubicUFO");

    println!("Input test cases.");

    let mut case = String::new();

    io::stdin().read_line(&mut case)
        .expect("Failed to read line"); //read input for cases

    case = case.to_string();
    let cases: Vec<&str> = case.split("\n").collect();
    let case_test = u32::from_str(cases[0]).unwrap(); //convert to integer

    for n in 1..=case_test {
        println!("\nCase #{}", n);

        println!("Input area for case #{}", n);
        let mut area_in = String::new();
        io::stdin().read_line(&mut area_in)
            .expect("Failed to read line"); //read input for desiered area

        area_in = area_in.to_string();
        let mut new_area: Vec<&str> = area_in.split("\n").collect();
        let mut area = f64::from_str(new_area[0]).unwrap(); //convert to f64

        //rotation matrix
        if area <=  f64::consts::SQRT_2 {
            let mut ar = area.powf(2.0) - 1.0;
            let mut theta = ar.asin() / 2.0;
            println!("[ {}, {}, {} ]", 0.5, 0, 0);
            println!("[ {}, {}, {} ]", 0.0, 0.5*theta.cos(), 0.5*theta.sin());
            println!("[ {}, {}, {} ]", 0.0, -0.5*theta.sin(), 0.5*theta.cos());
        } else {
            let three_f64 = 3.0_f64;
            let two_f64 = 2.0_f64;
            let eight_f64 = 8.0_f64;
            let div = two_f64.sqrt() / three_f64.sqrt();
            let thi1 = area / three_f64.sqrt();
            let mut thi = thi1.asin() - div.asin();
            println!("[ {}, {}, {} ]", thi.cos()/2.0, thi.sin()/2.0, 0);
            println!("[ {}, {}, {} ]", -thi.sin() / eight_f64.sqrt(), thi.cos() / eight_f64.sqrt(), 1.0/eight_f64.sqrt());
            println!("[ {}, {}, {} ]", thi.sin() / eight_f64.sqrt(), -thi.cos() / eight_f64.sqrt(), 1.0/eight_f64.sqrt());
        }

    }
}<|endoftext|>


<commit_before><commit_msg>day 8 solved.<commit_after>use std::io::prelude::*;
use std::fs::File;
use std::path::Path;

enum State {
    Normal,
    Backslash,
    ParseHex(bool)
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let mut chars_in_code = 0;
    let mut chars_in_memo = 0;

    for line in input.lines() {
        chars_in_code += line.len();
        chars_in_memo += line.chars()
            .fold((0, State::Normal), |(acc, st), ch| {
                match st {
                    State::Normal      => match ch {
                        '"'  => (acc, State::Normal),
                        '\\' => (acc + 1, State::Backslash),
                        _    => (acc + 1, State::Normal)
                    },
                    State::Backslash   => match ch {
                        'x'  => (acc, State::ParseHex(true)),
                        _    => (acc, State::Normal)
                    },
                    State::ParseHex(b) => if b {
                        (acc, State::ParseHex(false))
                    } else {
                        (acc, State::Normal)
                    }
                }
            }).0;
    }

    let ret = chars_in_code - chars_in_memo;

    println!("The difference in characters in code and memory is {}.", ret);

    let mut chars_encoded = 0;

    for line in input.lines() {
        chars_encoded += line.chars().fold(2, |acc, ch| { // start at 2 to entail endquotes
            match ch {
                '"'  => acc + 2,
                '\\' => acc + 2,
                _    => acc + 1
            }
        });
    }

    let ret = chars_encoded - chars_in_code;

    println!("The difference in code characters in the encoded and original version is {}.", ret);
}<|endoftext|>


<commit_before><commit_msg>implementation<commit_after>extern crate bit_vec;
extern crate farmhash;

use std::default::Default;
use std::f64::consts;
use bit_vec::BitVec;
use farmhash::hash64;

pub struct BloomFilter {
    bv: BitVec,
    hashes: usize
}

impl Default for BloomFilter {
    #[inline]
    fn default() -> BloomFilter {
        // http://hur.st/bloomfilter?n=10000&p=0.001
        BloomFilter::new(10_000, 0.001)
    }
}

impl BloomFilter {
    pub fn new(capacity: usize, error_rate: f64) -> BloomFilter {
        assert!((error_rate > 0.0 && error_rate < 1.0) && capacity > 0);

        // https://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives
        let m = BloomFilter::num_of_bits_in_vec(capacity, error_rate);

        // https://en.wikipedia.org/wiki/Bloom_filter#Optimal_number_of_hash_functions
        let k = BloomFilter::num_of_hash_funcs(m, capacity);

        BloomFilter {
            bv: BitVec::from_elem(capacity, false),
            hashes: k
        }
    }

    fn num_of_bits_in_vec(capacity: usize, error_rate: f64) -> usize {
        (-1.0 * (((capacity as f64) * error_rate.ln()) / (1.0 / consts::LN_2.powf(2.0)).ln())).ceil() as usize
    }

    fn num_of_hash_funcs(m: usize, capacity: usize) -> usize {
        (consts::LN_2 * ((m as f64) / (capacity as f64))).round().abs() as usize
    }

    pub fn insert(&mut self, value: &str) {
        for i in 0..self.hashes {
            let index = self.nth_hash(&value, i);
            self.bv.set(index, true);
        }
    }

    fn nth_hash(&self, x: &str, m: usize) -> usize {
        let hashval = x.to_string() + &m.to_string(); // meh
        (hash64(&hashval.as_bytes()) % (self.bv.capacity() as u64)) as usize
    }

    pub fn has(&self, value: &str) -> bool {
        for i in 0..self.hashes {
            let index = self.nth_hash(&value, i);
            if !self.bv[index] {
                return false;
            }
        }
        true
    }
}
<|endoftext|>