<commit_before>extern crate test;
extern crate utp;

use test::Bencher;
use std::io::test::next_test_ip4;
use utp::UtpStream;
use std::sync::Arc;
use std::thread::Thread;

macro_rules! iotry {
    ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{}", e) })
}

#[bench]
fn bench_connection_setup_and_teardown(b: &mut Bencher) {
    let server_addr = next_test_ip4();
    b.iter(|| {
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
}

#[bench]
fn bench_transfer_one_packet(b: &mut Bencher) {
    let len = 1024;
    let server_addr = next_test_ip4();
    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();
    let data_arc = Arc::new(data);

    b.iter(|| {
        let data = data_arc.clone();
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.write(data.as_slice()));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
    b.bytes = len as u64;
}

#[bench]
fn bench_transfer_one_megabyte(b: &mut Bencher) {
    let len = 1024 * 1024;
    let server_addr = next_test_ip4();
    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();
    let data_arc = Arc::new(data);

    b.iter(|| {
        let data = data_arc.clone();
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.write(data.as_slice()));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
    b.bytes = len as u64;
}
<commit_msg>Fix module import.<commit_after>extern crate test;
extern crate utp;

use test::Bencher;
use std::old_io::test::next_test_ip4;
use utp::UtpStream;
use std::sync::Arc;
use std::thread::Thread;

macro_rules! iotry {
    ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{}", e) })
}

#[bench]
fn bench_connection_setup_and_teardown(b: &mut Bencher) {
    let server_addr = next_test_ip4();
    b.iter(|| {
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
}

#[bench]
fn bench_transfer_one_packet(b: &mut Bencher) {
    let len = 1024;
    let server_addr = next_test_ip4();
    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();
    let data_arc = Arc::new(data);

    b.iter(|| {
        let data = data_arc.clone();
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.write(data.as_slice()));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
    b.bytes = len as u64;
}

#[bench]
fn bench_transfer_one_megabyte(b: &mut Bencher) {
    let len = 1024 * 1024;
    let server_addr = next_test_ip4();
    let data = (0..len).map(|x| x as u8).collect::<Vec<u8>>();
    let data_arc = Arc::new(data);

    b.iter(|| {
        let data = data_arc.clone();
        let mut server = iotry!(UtpStream::bind(server_addr));

        Thread::spawn(move || {
            let mut client = iotry!(UtpStream::connect(server_addr));
            iotry!(client.write(data.as_slice()));
            iotry!(client.close());
        });

        iotry!(server.read_to_end());
        iotry!(server.close());
    });
    b.bytes = len as u64;
}
<|endoftext|>


<commit_before>//! Contains information for keybindings.

use std::collections::{HashMap, HashSet};
use std::sync::{RwLock};
use rustwlc::xkb::Keysym;
use rustwlc::types::{KeyState, KeyboardModifiers};
use std::hash::{Hash, Hasher};

lazy_static! {
    static ref BINDINGS: RwLock<HashMap<Keypress, KeyEvent>> =
        RwLock::new(HashMap::new());
}

#[derive(Eq, PartialEq, Hash, Clone)]
struct Keypress {
    modifiers: KeyboardModifiers,
    keys: Vec<Keysym>
}

/// The type of function a key press handler is.
pub type KeyEvent = Box<FnOnce() + Send + Sync>;

pub fn get(keys: &[Keysym]) -> Option<KeyEvent> {
    let mut val: Option<KeyEvent>;
    {
        let bindings = BINDINGS.read().unwrap();
        val = bindings.get(keys).cloned();
    }
    val
}

pub fn register(values: Vec<(&[Keysym], KeyEvent)>) {
    let bindings = BINDINGS.write().unwrap();
    for value in values {
        bindings.set(value.0, value.1);
    }
}
<commit_msg>Add keymod_from_names<commit_after>//! Contains information for keybindings.

use std::collections::{HashMap, HashSet};
use std::sync::{RwLock};
use rustwlc::xkb::Keysym;
use rustwlc::types::*; // Need * for bitflags...
use std::hash::{Hash, Hasher};

lazy_static! {
    static ref BINDINGS: RwLock<HashMap<KeyPress, KeyEvent>> =
        RwLock::new(HashMap::new());
}

#[derive(Eq, PartialEq, Clone)]
pub struct KeyPress {
    modifiers: KeyMod,
    keys: Vec<Keysym>
}

/// Parses a KeyMod from key names.
pub fn keymod_from_names(keys: Vec<&str>) -> Result<KeyMod, String> {
    let mut result = KeyMod::empty();
    for key in keys {
        match key.to_lowercase().as_str() {
            "shift" => result = result | MOD_SHIFT,
            "control" | "ctrl" => result = result | MOD_CTRL,
            err => return Err(format!("Invalid character: {}", err))
        }
    }
    return Ok(result);
}

impl KeyPress {
    pub fn from_key_state() {

    }

    pub fn from_key_names(mods: Vec<String>, keys: Vec<String>) -> KeyPress {

    }
}

impl Hash for KeyPress {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        hasher.write_u32(self.modifiers.bits());
        for sym in self.keys {
            hasher.write_u32(sym.get_code());
        }
    }
}

/// The type of function a key press handler is.
pub type KeyEvent = Box<FnOnce() + Send + Sync>;

pub fn get(keys: KeyPress) -> Option<KeyEvent> {
    let mut val: Option<KeyEvent>;
    {
        let bindings = BINDINGS.read().unwrap();
        val = bindings.get(keys).cloned();
    }
    val
}

pub fn register(values: Vec<(KeyPress, KeyEvent)>) {
    let bindings = BINDINGS.write().unwrap();
    for value in values {
        bindings.set(value.0, value.1);
    }
}

pub fn register_keypress(press: KeyPress, func: KeyEvent) {

}
<|endoftext|>


<commit_before>use quote::quote;

pub fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
    if let syn::Data::Union(_) = s.ast().data {
        panic!("cannot derive on union")
    }

    s.add_bounds(synstructure::AddBounds::Generics);
    let body_fold = s.each_variant(|vi| {
        let bindings = vi.bindings();
        vi.construct(|_, index| {
            let bind = &bindings[index];
            quote! {
                ::rustc_middle::ty::fold::TypeFoldable::fold_with(#bind, __folder)
            }
        })
    });

    let body_visit = s.fold(quote!(), |acc, bind| {
        quote! {
            #acc
            ::rustc_middle::ty::fold::TypeFoldable::visit_with(#bind, __folder)?;
        }
    });

    s.bound_impl(
        quote!(::rustc_middle::ty::fold::TypeFoldable<'tcx>),
        quote! {
            fn super_fold_with<__F: ::rustc_middle::ty::fold::TypeFolder<'tcx>>(
                &self,
                __folder: &mut __F
            ) -> Self {
                match *self { #body_fold }
            }

            fn super_visit_with<__F: ::rustc_middle::ty::fold::TypeVisitor<'tcx>>(
                &self,
                __folder: &mut __F
            ) -> ::std::ops::ControlFlow<()> {
                match *self { #body_visit }
                ::std::ops::ControlFlow::CONTINUE
            }
        },
    )
}
<commit_msg>Rollup merge of #78841 - LeSeulArtichaut:foldable-derive, r=lcnr<commit_after>use quote::quote;

pub fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream {
    if let syn::Data::Union(_) = s.ast().data {
        panic!("cannot derive on union")
    }

    s.add_bounds(synstructure::AddBounds::Generics);
    let body_fold = s.each_variant(|vi| {
        let bindings = vi.bindings();
        vi.construct(|_, index| {
            let bind = &bindings[index];
            quote! {
                ::rustc_middle::ty::fold::TypeFoldable::fold_with(#bind, __folder)
            }
        })
    });

    let body_visit = s.each(|bind| {
        quote! {
            ::rustc_middle::ty::fold::TypeFoldable::visit_with(#bind, __folder)?;
        }
    });

    s.bound_impl(
        quote!(::rustc_middle::ty::fold::TypeFoldable<'tcx>),
        quote! {
            fn super_fold_with<__F: ::rustc_middle::ty::fold::TypeFolder<'tcx>>(
                &self,
                __folder: &mut __F
            ) -> Self {
                match *self { #body_fold }
            }

            fn super_visit_with<__F: ::rustc_middle::ty::fold::TypeVisitor<'tcx>>(
                &self,
                __folder: &mut __F
            ) -> ::std::ops::ControlFlow<()> {
                match *self { #body_visit }
                ::std::ops::ControlFlow::CONTINUE
            }
        },
    )
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 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.

//! This is the building block of complicated topologies which require a leader. It is
//! used when a single member of your cluster should perform additional applications
//! level initialization and/or if the other members of your cluster need to perform
//! additional initialization steps.
//!
//! We guarantee that the leader will perform it's initialization sequence before the
//! followers attempt to run thier initialization sequences.

use config::Config;
use error::{Result, SupError};
use state_machine::StateMachine;
use topology::{self, standalone, State, Worker};
use package::Package;

static LOGKEY: &'static str = "TI";

enum InitGate {
    NoLeader,
    Waiting,
    Done,
}

pub fn run(package: Package, config: &Config) -> Result<()> {
    let mut worker = try!(Worker::new(package, String::from("initializer"), config));
    let mut sm: StateMachine<State, Worker, SupError> =
        StateMachine::new(State::DetermineViability);
    sm.add_dispatch(State::DetermineViability, state_determine_viability);
    sm.add_dispatch(State::StartElection, state_start_election);
    sm.add_dispatch(State::InElection, state_in_election);
    sm.add_dispatch(State::BecomeLeader, state_become_leader);
    sm.add_dispatch(State::BecomeFollower, state_become_follower);
    sm.add_dispatch(State::Leader, state_leader);
    sm.add_dispatch(State::Follower, state_follower);
    topology::run_internal(&mut sm, &mut worker)
}

pub fn state_determine_viability(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Determining viability as a leader");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.follower(false);
        ce.leader(false);
    }
    {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if census.has_leader() {
            Ok((State::BecomeFollower, 0))
        } else {
            Ok((State::StartElection, 0))
        }
    }
}

pub fn state_start_election(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Starting an election");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.election = Some(true);
    }
    let candidate = {
        worker.census_list
            .read()
            .unwrap()
            .local_census()
            .determine_vote()
            .candidate_string()
    };
    outputln!("My candidate is {:?}", candidate);
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.vote(Some(candidate));
    }
    Ok((State::InElection, 0))
}

pub fn state_in_election(worker: &mut Worker) -> Result<(State, u64)> {
    let candidate = {
        worker.census_list
            .read()
            .unwrap()
            .local_census()
            .determine_vote()
            .candidate_string()
    };

    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        match ce.vote {
            Some(ref c) if *c == candidate => {}
            Some(_) => {
                outputln!("Switching my vote to {}", candidate);
                ce.vote(Some(candidate));
            }
            None => {
                outputln!("Switching my vote to {}", candidate);
                ce.vote(Some(candidate));
            }
        }
    }

    {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if let Some(leader_ce) = census.get_leader() {
            outputln!("{} has already been elected; becoming a follower",
                      leader_ce.candidate_string());
            return Ok((State::BecomeFollower, 0));
        }

        match census.voting_finished() {
            Some(winner) => {
                let me = census.me();
                if me == winner {
                    outputln!("The votes are in! I won! I will serve with humility.");
                    Ok((State::BecomeLeader, 0))
                } else {
                    outputln!("The votes are in! I lost! I will serve with grace.");
                    Ok((State::BecomeFollower, 0))
                }
            }
            None => Ok((State::InElection, 10)),
        }
    }
}

pub fn state_become_leader(worker: &mut Worker) -> Result<(State, u64)> {
    let mut cl = worker.census_list.write().unwrap();
    let mut census = cl.local_census_mut();
    if census.has_leader() == false {
        census.me_mut().leader(true);
    }

    if census.has_all_followers() {
        outputln!("Starting my term as leader");
        {
            let mut me = census.me_mut();
            if me.election.is_some() {
                me.election(None)
            }
            if me.vote.is_some() {
                me.vote(None)
            }
        }

        if census.in_event {
            census.in_event = false;
        }
        Ok((State::Leader, 0))
    } else {
        outputln!("Waiting for all my followers to agree");
        Ok((State::BecomeLeader, 0))
    }
}

pub fn state_become_follower(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Becoming a follower");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.follower(true);
    }

    let cl = worker.census_list.read().unwrap();
    let census = cl.local_census();
    if census.has_leader() {
        outputln!("Becoming a follower for real");
        Ok((State::Follower, 0))
    } else {
        outputln!("Waiting for a leader");
        Ok((State::BecomeFollower, 0))
    }
}

pub fn state_leader(worker: &mut Worker) -> Result<(State, u64)> {
    let is_running = {
        let supervisor = worker.supervisor.read().unwrap();
        supervisor.pid.is_some()
    };
    if !is_running {
        try!(initialize(worker));
        try!(standalone::state_starting(worker));
    }

    Ok((State::Leader, 0))
}

pub fn state_follower(worker: &mut Worker) -> Result<(State, u64)> {
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut me = cl.me_mut();
        if me.election.is_some() {
            me.election(None);
        }
        if me.vote.is_some() {
            me.vote(None);
        }
    }

    {
        let mut cl = worker.census_list.write().unwrap();
        let mut census = cl.local_census_mut();
        if census.in_event {
            census.in_event = false;
        }
    }

    let gate = {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if let Some(leader) = census.get_leader() {
            if leader.initialized {
                InitGate::Done
            } else {
                InitGate::Waiting
            }
        } else {
            InitGate::NoLeader
        }
    };

    match gate {
        InitGate::Done => {}
        InitGate::Waiting => return Ok((State::Follower, 0)),
        InitGate::NoLeader => return Ok((State::DetermineViability, 0)),
    }

    let is_running = {
        let supervisor = worker.supervisor.read().unwrap();
        supervisor.pid.is_some()
    };
    if !is_running {
        try!(initialize(worker));
        try!(standalone::state_starting(worker));
    }

    if !worker.census_list.read().unwrap().local_census().has_leader() {
        Ok((State::DetermineViability, 0))
    } else {
        Ok((State::Follower, 0))
    }
}

fn initialize(worker: &mut Worker) -> Result<()> {
    let service_config = worker.service_config.read().unwrap();
    let package = worker.package.read().unwrap();
    match package.initialize(&service_config) {
        Ok(()) => {
            let mut cl = worker.census_list.write().unwrap();
            let mut me = cl.me_mut();
            me.initialized();
            Ok(())
        }
        Err(e) => Err(e),
    }
}
<commit_msg>minor spelling fixes<commit_after>// Copyright (c) 2016 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.

//! This is the building block of complicated topologies which require a leader. It is
//! used when a single member of your cluster should perform additional application-
//! level initialization and/or if the other members of your cluster need to perform
//! additional initialization steps.
//!
//! We guarantee that the leader will perform its initialization sequence before the
//! followers attempt to run their initialization sequences.

use config::Config;
use error::{Result, SupError};
use state_machine::StateMachine;
use topology::{self, standalone, State, Worker};
use package::Package;

static LOGKEY: &'static str = "TI";

enum InitGate {
    NoLeader,
    Waiting,
    Done,
}

pub fn run(package: Package, config: &Config) -> Result<()> {
    let mut worker = try!(Worker::new(package, String::from("initializer"), config));
    let mut sm: StateMachine<State, Worker, SupError> =
        StateMachine::new(State::DetermineViability);
    sm.add_dispatch(State::DetermineViability, state_determine_viability);
    sm.add_dispatch(State::StartElection, state_start_election);
    sm.add_dispatch(State::InElection, state_in_election);
    sm.add_dispatch(State::BecomeLeader, state_become_leader);
    sm.add_dispatch(State::BecomeFollower, state_become_follower);
    sm.add_dispatch(State::Leader, state_leader);
    sm.add_dispatch(State::Follower, state_follower);
    topology::run_internal(&mut sm, &mut worker)
}

pub fn state_determine_viability(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Determining viability as a leader");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.follower(false);
        ce.leader(false);
    }
    {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if census.has_leader() {
            Ok((State::BecomeFollower, 0))
        } else {
            Ok((State::StartElection, 0))
        }
    }
}

pub fn state_start_election(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Starting an election");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.election = Some(true);
    }
    let candidate = {
        worker.census_list
            .read()
            .unwrap()
            .local_census()
            .determine_vote()
            .candidate_string()
    };
    outputln!("My candidate is {:?}", candidate);
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.vote(Some(candidate));
    }
    Ok((State::InElection, 0))
}

pub fn state_in_election(worker: &mut Worker) -> Result<(State, u64)> {
    let candidate = {
        worker.census_list
            .read()
            .unwrap()
            .local_census()
            .determine_vote()
            .candidate_string()
    };

    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        match ce.vote {
            Some(ref c) if *c == candidate => {}
            Some(_) => {
                outputln!("Switching my vote to {}", candidate);
                ce.vote(Some(candidate));
            }
            None => {
                outputln!("Switching my vote to {}", candidate);
                ce.vote(Some(candidate));
            }
        }
    }

    {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if let Some(leader_ce) = census.get_leader() {
            outputln!("{} has already been elected; becoming a follower",
                      leader_ce.candidate_string());
            return Ok((State::BecomeFollower, 0));
        }

        match census.voting_finished() {
            Some(winner) => {
                let me = census.me();
                if me == winner {
                    outputln!("The votes are in! I won! I will serve with humility.");
                    Ok((State::BecomeLeader, 0))
                } else {
                    outputln!("The votes are in! I lost! I will serve with grace.");
                    Ok((State::BecomeFollower, 0))
                }
            }
            None => Ok((State::InElection, 10)),
        }
    }
}

pub fn state_become_leader(worker: &mut Worker) -> Result<(State, u64)> {
    let mut cl = worker.census_list.write().unwrap();
    let mut census = cl.local_census_mut();
    if census.has_leader() == false {
        census.me_mut().leader(true);
    }

    if census.has_all_followers() {
        outputln!("Starting my term as leader");
        {
            let mut me = census.me_mut();
            if me.election.is_some() {
                me.election(None)
            }
            if me.vote.is_some() {
                me.vote(None)
            }
        }

        if census.in_event {
            census.in_event = false;
        }
        Ok((State::Leader, 0))
    } else {
        outputln!("Waiting for all my followers to agree");
        Ok((State::BecomeLeader, 0))
    }
}

pub fn state_become_follower(worker: &mut Worker) -> Result<(State, u64)> {
    outputln!("Becoming a follower");
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut ce = cl.me_mut();
        ce.follower(true);
    }

    let cl = worker.census_list.read().unwrap();
    let census = cl.local_census();
    if census.has_leader() {
        outputln!("Becoming a follower for real");
        Ok((State::Follower, 0))
    } else {
        outputln!("Waiting for a leader");
        Ok((State::BecomeFollower, 0))
    }
}

pub fn state_leader(worker: &mut Worker) -> Result<(State, u64)> {
    let is_running = {
        let supervisor = worker.supervisor.read().unwrap();
        supervisor.pid.is_some()
    };
    if !is_running {
        try!(initialize(worker));
        try!(standalone::state_starting(worker));
    }

    Ok((State::Leader, 0))
}

pub fn state_follower(worker: &mut Worker) -> Result<(State, u64)> {
    {
        let mut cl = worker.census_list.write().unwrap();
        let mut me = cl.me_mut();
        if me.election.is_some() {
            me.election(None);
        }
        if me.vote.is_some() {
            me.vote(None);
        }
    }

    {
        let mut cl = worker.census_list.write().unwrap();
        let mut census = cl.local_census_mut();
        if census.in_event {
            census.in_event = false;
        }
    }

    let gate = {
        let cl = worker.census_list.read().unwrap();
        let census = cl.local_census();
        if let Some(leader) = census.get_leader() {
            if leader.initialized {
                InitGate::Done
            } else {
                InitGate::Waiting
            }
        } else {
            InitGate::NoLeader
        }
    };

    match gate {
        InitGate::Done => {}
        InitGate::Waiting => return Ok((State::Follower, 0)),
        InitGate::NoLeader => return Ok((State::DetermineViability, 0)),
    }

    let is_running = {
        let supervisor = worker.supervisor.read().unwrap();
        supervisor.pid.is_some()
    };
    if !is_running {
        try!(initialize(worker));
        try!(standalone::state_starting(worker));
    }

    if !worker.census_list.read().unwrap().local_census().has_leader() {
        Ok((State::DetermineViability, 0))
    } else {
        Ok((State::Follower, 0))
    }
}

fn initialize(worker: &mut Worker) -> Result<()> {
    let service_config = worker.service_config.read().unwrap();
    let package = worker.package.read().unwrap();
    match package.initialize(&service_config) {
        Ok(()) => {
            let mut cl = worker.census_list.write().unwrap();
            let mut me = cl.me_mut();
            me.initialized();
            Ok(())
        }
        Err(e) => Err(e),
    }
}
<|endoftext|>


<commit_before>use crate::model::{GameId, Speed};
use shakmaty::san::San;
use shakmaty::fen::Fen;
use serde::Deserialize;
use serde_with::{serde_as, DisplayFromStr, StringWithSeparator, SpaceSeparator};

#[serde_as]
#[derive(Deserialize)]
struct Game {
    #[serde_as(as = "DisplayFromStr")]
    id: GameId,
    rated: bool, // TODO: mode
    variant: LilaVariant,
    players: Players,
    speed: Speed,
    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, San>")]
    moves: Vec<San>,
    #[serde(default)]
    winner: Option<WinnerColor>,
    #[serde_as(as = "Option<DisplayFromStr>")]
    #[serde(default, rename = "initialFen")]
    initial_fen: Option<Fen>
}

#[derive(Deserialize)]
struct Players {
    white: Player,
    black: Player,
}

#[derive(Deserialize)]
struct Player {
    user: User,
    rating: u16,
}

#[derive(Deserialize)]
struct User {
    name: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
enum LilaVariant {
    Antichess,
    Atomic,
    Chess960,
    Crazyhouse,
    FromPosition,
    Horde,
    KingOfTheHill,
    RacingKings,
    Standard,
    ThreeCheck,
}

#[derive(Deserialize)]
enum WinnerColor {
    #[serde(rename = "white")]
    White,
    #[serde(rename = "black")]
    Black,
}
<commit_msg>deserialize game status<commit_after>use crate::model::{GameId, Speed};
use shakmaty::san::San;
use shakmaty::fen::Fen;
use serde::Deserialize;
use serde_with::{serde_as, DisplayFromStr, StringWithSeparator, SpaceSeparator};

#[serde_as]
#[derive(Deserialize)]
struct Game {
    #[serde_as(as = "DisplayFromStr")]
    id: GameId,
    rated: bool, // TODO: mode
    status: Status,
    variant: LilaVariant,
    players: Players,
    speed: Speed,
    #[serde_as(as = "StringWithSeparator::<SpaceSeparator, San>")]
    moves: Vec<San>,
    #[serde(default)]
    winner: Option<WinnerColor>,
    #[serde_as(as = "Option<DisplayFromStr>")]
    #[serde(default, rename = "initialFen")]
    initial_fen: Option<Fen>
}

#[derive(Deserialize)]
struct Players {
    white: Player,
    black: Player,
}

#[derive(Deserialize)]
struct Player {
    user: User,
    rating: u16,
}

#[derive(Deserialize)]
struct User {
    name: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
enum LilaVariant {
    Antichess,
    Atomic,
    Chess960,
    Crazyhouse,
    FromPosition,
    Horde,
    KingOfTheHill,
    RacingKings,
    Standard,
    ThreeCheck,
}

#[derive(Deserialize)]
enum WinnerColor {
    #[serde(rename = "white")]
    White,
    #[serde(rename = "black")]
    Black,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
enum Status {
    Created,
    Started,
    Aborted,
    Mate,
    Resign,
    Stalemate,
    Timeout,
    Draw,
    #[serde(rename = "outoftime")]
    OutOfTime,
    Cheat,
    NoStart,
    UnknownFinish,
    VariantEnd,
}

impl Status {
    pub fn is_ongoing(self) -> bool {
        matches!(self, Status::Created | Status::Started)
    }

    pub fn is_unindexable(self) -> bool {
        matches!(self, Status::UnknownFinish | Status::NoStart | Status::Aborted)
    }
}
<|endoftext|>


<commit_before>use crate::{
    audio, interrupts,
    memory::io::{Interrupt, IoRegisters, Timer},
    scheduler::{EventTag, Scheduler},
    Gba,
};

pub fn started(idx: usize, ioregs: &mut IoRegisters, scheduler: &Scheduler) {
    let timer = &mut ioregs.timers[idx];
    timer.origin = ioregs.time;
    timer.counter = timer.reload;

    if timer.control.count_up_timing() {
        return;
    }

    let event_tag = EventTag::timer(idx);
    let overflow_fn = match idx {
        0 => overflow::<0>,
        1 => overflow::<1>,
        2 => overflow::<2>,
        3 => overflow::<3>,
        _ => panic!("invalid timer"),
    };

    let overflow_cycles = (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
    scheduler.unschedule(event_tag);
    scheduler.schedule(overflow_fn, overflow_cycles, event_tag);
}

pub fn stopped(timer: usize, _timers: &mut [Timer; 4], scheduler: &Scheduler) {
    scheduler.unschedule(EventTag::timer(timer));
}

pub fn reschedule(idx: usize, timers: &mut [Timer; 4], scheduler: &Scheduler) {
    let event_tag = EventTag::timer(idx);
    let timer = &mut timers[idx];
    scheduler.unschedule(event_tag);

    if !timer.control.count_up_timing() {
        let overflow_fn = match idx {
            0 => overflow::<0>,
            1 => overflow::<1>,
            2 => overflow::<2>,
            3 => overflow::<3>,
            _ => panic!("invalid timer"),
        };

        let overflow_cycles =
            (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
        scheduler.schedule(overflow_fn, overflow_cycles, event_tag);
    }
}

pub fn flush(timer: &mut Timer, now: u64) {
    if !timer.control.started() || timer.control.count_up_timing() {
        return;
    }

    // This should NEVER overflow before the overflow function is called by the scheduler, which should reset the timer's counter.
    timer.counter += ((now - timer.origin) >> timer.control.prescaler_shift()) as u16;
    timer.origin = now;
}

pub fn overflow<const TIMER: usize>(gba: &mut Gba) {
    let mut overflows = 1u32;

    {
        let timer = &mut gba.mem.ioregs.timers[TIMER];
        timer.counter = timer.reload;
        timer.origin = gba.mem.ioregs.time;

        let overflow_cycles =
            (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
        gba.scheduler
            .schedule(overflow::<TIMER>, overflow_cycles, EventTag::timer(TIMER));
    }

    for _ in 0..overflows {
        after_overflow(TIMER, gba);
    }

    let mut idx = TIMER + 1;
    while overflows > 0 && idx < 4 {
        let timer = &mut gba.mem.ioregs.timers[idx];
        if !timer.control.count_up_timing() || !timer.control.started() {
            break;
        }

        let mut rem = overflows;
        overflows = 0;
        while rem >= (0x10000u32 - timer.counter as u32) {
            overflows += 1;
            rem -= 0x10000u32 - timer.counter as u32;
            timer.counter = timer.reload;
        }
        timer.counter += rem as u16;
        idx += 1;

        for _ in 0..overflows {
            after_overflow(idx, gba);
        }
    }
}

fn after_overflow(idx: usize, gba: &mut Gba) {
    if gba.mem.ioregs.timers[idx].control.irq_enable() {
        interrupts::raise(Interrupt::timer(idx), &mut gba.mem.ioregs, &gba.scheduler);
    }

    if idx == 0 || idx == 1 {
        audio::check_fifo_timer_overflow(idx, gba);
    }
}
<commit_msg>Remove unecessary loop in timers.<commit_after>use crate::{
    audio, interrupts,
    memory::io::{Interrupt, IoRegisters, Timer},
    scheduler::{EventTag, Scheduler},
    Gba,
};

pub fn started(idx: usize, ioregs: &mut IoRegisters, scheduler: &Scheduler) {
    let timer = &mut ioregs.timers[idx];
    timer.origin = ioregs.time;
    timer.counter = timer.reload;

    if timer.control.count_up_timing() {
        return;
    }

    let event_tag = EventTag::timer(idx);
    let overflow_fn = match idx {
        0 => overflow::<0>,
        1 => overflow::<1>,
        2 => overflow::<2>,
        3 => overflow::<3>,
        _ => panic!("invalid timer"),
    };

    let overflow_cycles = (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
    scheduler.unschedule(event_tag);
    scheduler.schedule(overflow_fn, overflow_cycles, event_tag);
}

pub fn stopped(timer: usize, _timers: &mut [Timer; 4], scheduler: &Scheduler) {
    scheduler.unschedule(EventTag::timer(timer));
}

pub fn reschedule(idx: usize, timers: &mut [Timer; 4], scheduler: &Scheduler) {
    let event_tag = EventTag::timer(idx);
    let timer = &mut timers[idx];
    scheduler.unschedule(event_tag);

    if !timer.control.count_up_timing() {
        let overflow_fn = match idx {
            0 => overflow::<0>,
            1 => overflow::<1>,
            2 => overflow::<2>,
            3 => overflow::<3>,
            _ => panic!("invalid timer"),
        };

        let overflow_cycles =
            (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
        scheduler.schedule(overflow_fn, overflow_cycles, event_tag);
    }
}

pub fn flush(timer: &mut Timer, now: u64) {
    if !timer.control.started() || timer.control.count_up_timing() {
        return;
    }

    // This should NEVER overflow before the overflow function is called by the scheduler, which should reset the timer's counter.
    timer.counter += ((now - timer.origin) >> timer.control.prescaler_shift()) as u16;
    timer.origin = now;
}

pub fn overflow<const TIMER: usize>(gba: &mut Gba) {
    let mut overflows = 1u32;

    {
        let timer = &mut gba.mem.ioregs.timers[TIMER];
        timer.counter = timer.reload;
        timer.origin = gba.mem.ioregs.time;

        let overflow_cycles =
            (0x10000u32 - timer.counter as u32) << timer.control.prescaler_shift();
        gba.scheduler
            .schedule(overflow::<TIMER>, overflow_cycles, EventTag::timer(TIMER));
    }
    after_overflow(TIMER, gba);

    let mut idx = TIMER + 1;
    while overflows > 0 && idx < 4 {
        let timer = &mut gba.mem.ioregs.timers[idx];
        if !timer.control.count_up_timing() || !timer.control.started() {
            break;
        }

        let mut rem = overflows;
        overflows = 0;
        while rem >= (0x10000u32 - timer.counter as u32) {
            overflows += 1;
            rem -= 0x10000u32 - timer.counter as u32;
            timer.counter = timer.reload;
        }
        timer.counter += rem as u16;
        for _ in 0..overflows {
            after_overflow(idx, gba);
        }
        idx += 1;
    }
}

fn after_overflow(idx: usize, gba: &mut Gba) {
    if gba.mem.ioregs.timers[idx].control.irq_enable() {
        interrupts::raise(Interrupt::timer(idx), &mut gba.mem.ioregs, &gba.scheduler);
    }

    if idx == 0 || idx == 1 {
        audio::check_fifo_timer_overflow(idx, gba);
    }
}
<|endoftext|>


<commit_before>use orbtk::prelude::*;
use orbtk::theme::DEFAULT_THEME_CSS;

static DARK_EXT: &'static str = include_str!("../res/calculator-dark.css");

#[cfg(feature = "light-theme")]
static LIGHT_EXT: &'static str = include_str!("../res/calculator-light.css");

#[cfg(not(feature = "light-theme"))]
fn get_theme() -> ThemeValue {
    ThemeValue::create_from_css(DEFAULT_THEME_CSS)
        .extension_css(DARK_EXT)
        .build()
}

#[cfg(feature = "light-theme")]
fn get_theme() -> ThemeValue {
    ThemeValue::create()
        .extension_css(DARK_EXT)
        .extension_css(LIGHT_EXT)
        .build()
}

#[derive(Debug, Copy, Clone)]
enum Action {
    Digit(char),
    Operator(char),
}

#[derive(Default, AsAny)]
pub struct MainViewState {
    input: String,
    operator: Option<char>,
    left_side: Option<f64>,
    right_side: Option<f64>,
    action: Option<Action>,
}

impl MainViewState {
    fn action(&mut self, action: impl Into<Option<Action>>) {
        self.action = action.into();
    }

    fn calculate(&mut self, ctx: &mut Context) {
        let mut result = 0.0;
        if let Some(operator) = self.operator {
            if let Some(left_side) = self.left_side {
                if let Some(right_side) = self.right_side {
                    match operator {
                        '+' => {
                            result = left_side + right_side;
                        }
                        '-' => {
                            result = left_side - right_side;
                        }
                        '*' => {
                            result = left_side * right_side;
                        }
                        '/' => {
                            result = left_side / right_side;
                        }
                        _ => {}
                    }
                }
            }
        }

        ctx.widget().set("text", String16::from(result.to_string()));
        self.left_side = Some(result);
        self.right_side = None;
    }
}

impl State for MainViewState {
    fn update(&mut self, _: &mut Registry, ctx: &mut Context) {
        if let Some(action) = self.action {
            match action {
                Action::Digit(digit) => {
                    self.input.push(digit);
                    ctx.child("input").get_mut::<String16>("text").push(digit);
                }
                Action::Operator(operator) => match operator {
                    'C' => {
                        self.input.clear();
                        self.left_side = None;
                        self.operator = None;
                        self.right_side = None;
                        ctx.widget().get_mut::<String16>("text").clear();
                        ctx.child("input").get_mut::<String16>("text").clear()
                    }
                    '=' => {
                        self.right_side = Some(self.input.parse().unwrap_or(0.0));
                        self.calculate(ctx);
                        self.input.clear();
                        self.left_side = None;
                        self.operator = None;
                        self.right_side = None;
                        ctx.child("input").get_mut::<String16>("text").clear()
                    }
                    _ => {
                        if self.input.is_empty() {
                            return;
                        }
                        if self.left_side.is_none() {
                            self.left_side = Some(self.input.parse().unwrap_or(0.0));
                        } else {
                            self.right_side = Some(self.input.parse().unwrap_or(0.0));
                            self.calculate(ctx);
                        }

                        ctx.child("input")
                            .get_mut::<String16>("text")
                            .push(operator);
                        self.input.clear();
                        self.operator = Some(operator);
                    }
                },
            }

            self.action = None;
        }
    }
}

fn get_button_selector(primary: bool) -> Selector {
    let selector = Selector::from("button");

    if primary {
        selector.class("primary")
    } else {
        selector
    }
}

fn generate_digit_button(
    ctx: &mut BuildContext,
    id: Entity,
    sight: char,
    primary: bool,
    column: usize,
    column_span: usize,
    row: usize,
) -> Entity {
    Button::create()
        .min_size(48.0, 48.0)
        .text(sight.to_string())
        .selector(get_button_selector(primary))
        .on_click(move |states, _| -> bool {
            state(id, states).action(Action::Digit(sight));
            true
        })
        .attach(Grid::column(column))
        .attach(Grid::row(row))
        .attach(Grid::column_span(column_span))
        .build(ctx)
}

fn generate_operation_button(
    ctx: &mut BuildContext,
    id: Entity,
    sight: char,
    primary: bool,
    column: usize,
    column_span: usize,
    row: usize,
) -> Entity {
    Button::create()
        .min_size(48.0, 48.0)
        .text(sight.to_string())
        .selector(get_button_selector(primary).class("square"))
        .on_click(move |states, _| -> bool {
            state(id, states).action(Action::Operator(sight));
            true
        })
        .attach(Grid::column(column))
        .attach(Grid::column_span(column_span))
        .attach(Grid::row(row))
        .build(ctx)
}

widget!(MainView<MainViewState> {
    text: String16
});

impl Template for MainView {
    fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
        self.name("MainView")
            .width(212.0)
            .height(336.0)
            .text("")
            .child(
                Grid::create()
                    .rows(Rows::create().row(72.0).row("*").build())
                    .child(
                        Container::create()
                            .padding(8.0)
                            .selector(Selector::from("container").class("header"))
                            .attach(Grid::row(0))
                            .child(
                                Grid::create()
                                    .child(
                                        ScrollViewer::create()
                                            .scroll_viewer_mode(("custom", "disabled"))
                                            .child(
                                                TextBlock::create()
                                                    .width(0.0)
                                                    .height(14.0)
                                                    .text("")
                                                    .selector(
                                                        Selector::from("text-block").id("input"),
                                                    )
                                                    .vertical_alignment("start")
                                                    .build(ctx),
                                            )
                                            .build(ctx),
                                    )
                                    .child(
                                        TextBlock::create()
                                            .selector(Selector::from("text-block"))
                                            .text(id)
                                            .vertical_alignment("end")
                                            .horizontal_alignment("end")
                                            .build(ctx),
                                    )
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .child(
                        Container::create()
                            .selector(Selector::from("container").class("content"))
                            .padding(8.0)
                            .attach(Grid::row(1))
                            .child(
                                Grid::create()
                                    .columns(
                                        Columns::create()
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .build(),
                                    )
                                    .rows(
                                        Rows::create()
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .build(),
                                    )
                                    // row 0
                                    .child(generate_operation_button(ctx, id, 'C', false, 0, 5, 0))
                                    .child(generate_operation_button(ctx, id, '/', true, 6, 3, 0))
                                    // row 2
                                    .child(generate_digit_button(ctx, id, '7', false, 0, 1, 2))
                                    .child(generate_digit_button(ctx, id, '8', false, 2, 1, 2))
                                    .child(generate_digit_button(ctx, id, '9', false, 4, 1, 2))
                                    .child(generate_operation_button(ctx, id, '*', true, 6, 1, 2))
                                    // row 4
                                    .child(generate_digit_button(ctx, id, '4', false, 0, 1, 4))
                                    .child(generate_digit_button(ctx, id, '5', false, 2, 1, 4))
                                    .child(generate_digit_button(ctx, id, '6', false, 4, 1, 4))
                                    .child(generate_operation_button(ctx, id, '-', true, 6, 1, 4))
                                    // row 6
                                    .child(generate_digit_button(ctx, id, '1', false, 0, 1, 6))
                                    .child(generate_digit_button(ctx, id, '2', false, 2, 1, 6))
                                    .child(generate_digit_button(ctx, id, '3', false, 4, 1, 6))
                                    .child(generate_operation_button(ctx, id, '+', true, 6, 1, 6))
                                    // row 8
                                    .child(generate_digit_button(ctx, id, '0', false, 0, 3, 8))
                                    .child(generate_digit_button(ctx, id, '.', false, 4, 1, 8))
                                    .child(generate_operation_button(ctx, id, '=', true, 6, 1, 8))
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .build(ctx),
            )
    }
}

fn main() {
    Application::new()
        .window(|ctx| {
            Window::create()
                .title("OrbTk - Calculator example")
                .position((100.0, 100.0))
                .size(212.0, 336.0)
                .theme(get_theme())
                .child(MainView::create().build(ctx))
                .build(ctx)
        })
        .run();
}

// helper to request MainViewState
fn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {
    states.get_mut(id)
}
<commit_msg>show only 9 digits to fit in the display<commit_after>use orbtk::prelude::*;
use orbtk::theme::DEFAULT_THEME_CSS;

static DARK_EXT: &'static str = include_str!("../res/calculator-dark.css");

#[cfg(feature = "light-theme")]
static LIGHT_EXT: &'static str = include_str!("../res/calculator-light.css");

#[cfg(not(feature = "light-theme"))]
fn get_theme() -> ThemeValue {
    ThemeValue::create_from_css(DEFAULT_THEME_CSS)
        .extension_css(DARK_EXT)
        .build()
}

#[cfg(feature = "light-theme")]
fn get_theme() -> ThemeValue {
    ThemeValue::create()
        .extension_css(DARK_EXT)
        .extension_css(LIGHT_EXT)
        .build()
}

#[derive(Debug, Copy, Clone)]
enum Action {
    Digit(char),
    Operator(char),
}

#[derive(Default, AsAny)]
pub struct MainViewState {
    input: String,
    operator: Option<char>,
    left_side: Option<f64>,
    right_side: Option<f64>,
    action: Option<Action>,
}

impl MainViewState {
    fn action(&mut self, action: impl Into<Option<Action>>) {
        self.action = action.into();
    }

    fn calculate(&mut self, ctx: &mut Context) {
        let mut result = 0.0;
        if let Some(operator) = self.operator {
            if let Some(left_side) = self.left_side {
                if let Some(right_side) = self.right_side {
                    match operator {
                        '+' => {
                            result = left_side + right_side;
                        }
                        '-' => {
                            result = left_side - right_side;
                        }
                        '*' => {
                            result = left_side * right_side;
                        }
                        '/' => {
                            result = left_side / right_side;
                        }
                        _ => {}
                    }
                }
            }
        }

        ctx.widget()
            .set("text", String16::from(format!("{:.9}", result)));
        self.left_side = Some(result);
        self.right_side = None;
    }
}

impl State for MainViewState {
    fn update(&mut self, _: &mut Registry, ctx: &mut Context) {
        if let Some(action) = self.action {
            match action {
                Action::Digit(digit) => {
                    self.input.push(digit);
                    ctx.child("input").get_mut::<String16>("text").push(digit);
                }
                Action::Operator(operator) => match operator {
                    'C' => {
                        self.input.clear();
                        self.left_side = None;
                        self.operator = None;
                        self.right_side = None;
                        ctx.widget().get_mut::<String16>("text").clear();
                        ctx.child("input").get_mut::<String16>("text").clear()
                    }
                    '=' => {
                        self.right_side = Some(self.input.parse().unwrap_or(0.0));
                        self.calculate(ctx);
                        self.input.clear();
                        self.left_side = None;
                        self.operator = None;
                        self.right_side = None;
                        ctx.child("input").get_mut::<String16>("text").clear()
                    }
                    _ => {
                        if self.input.is_empty() {
                            return;
                        }
                        if self.left_side.is_none() {
                            self.left_side = Some(self.input.parse().unwrap_or(0.0));
                        } else {
                            self.right_side = Some(self.input.parse().unwrap_or(0.0));
                            self.calculate(ctx);
                        }

                        ctx.child("input")
                            .get_mut::<String16>("text")
                            .push(operator);
                        self.input.clear();
                        self.operator = Some(operator);
                    }
                },
            }

            self.action = None;
        }
    }
}

fn get_button_selector(primary: bool) -> Selector {
    let selector = Selector::from("button");

    if primary {
        selector.class("primary")
    } else {
        selector
    }
}

fn generate_digit_button(
    ctx: &mut BuildContext,
    id: Entity,
    sight: char,
    primary: bool,
    column: usize,
    column_span: usize,
    row: usize,
) -> Entity {
    Button::create()
        .min_size(48.0, 48.0)
        .text(sight.to_string())
        .selector(get_button_selector(primary))
        .on_click(move |states, _| -> bool {
            state(id, states).action(Action::Digit(sight));
            true
        })
        .attach(Grid::column(column))
        .attach(Grid::row(row))
        .attach(Grid::column_span(column_span))
        .build(ctx)
}

fn generate_operation_button(
    ctx: &mut BuildContext,
    id: Entity,
    sight: char,
    primary: bool,
    column: usize,
    column_span: usize,
    row: usize,
) -> Entity {
    Button::create()
        .min_size(48.0, 48.0)
        .text(sight.to_string())
        .selector(get_button_selector(primary).class("square"))
        .on_click(move |states, _| -> bool {
            state(id, states).action(Action::Operator(sight));
            true
        })
        .attach(Grid::column(column))
        .attach(Grid::column_span(column_span))
        .attach(Grid::row(row))
        .build(ctx)
}

widget!(MainView<MainViewState> {
    text: String16
});

impl Template for MainView {
    fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {
        self.name("MainView")
            .width(212.0)
            .height(336.0)
            .text("")
            .child(
                Grid::create()
                    .rows(Rows::create().row(72.0).row("*").build())
                    .child(
                        Container::create()
                            .padding(8.0)
                            .selector(Selector::from("container").class("header"))
                            .attach(Grid::row(0))
                            .child(
                                Grid::create()
                                    .child(
                                        ScrollViewer::create()
                                            .scroll_viewer_mode(("custom", "disabled"))
                                            .child(
                                                TextBlock::create()
                                                    .width(0.0)
                                                    .height(14.0)
                                                    .text("")
                                                    .selector(
                                                        Selector::from("text-block").id("input"),
                                                    )
                                                    .vertical_alignment("start")
                                                    .build(ctx),
                                            )
                                            .build(ctx),
                                    )
                                    .child(
                                        TextBlock::create()
                                            .selector(Selector::from("text-block"))
                                            .text(id)
                                            .vertical_alignment("end")
                                            .horizontal_alignment("end")
                                            .build(ctx),
                                    )
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .child(
                        Container::create()
                            .selector(Selector::from("container").class("content"))
                            .padding(8.0)
                            .attach(Grid::row(1))
                            .child(
                                Grid::create()
                                    .columns(
                                        Columns::create()
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .column(4.0)
                                            .column(48.0)
                                            .build(),
                                    )
                                    .rows(
                                        Rows::create()
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .row(4.0)
                                            .row(48.0)
                                            .build(),
                                    )
                                    // row 0
                                    .child(generate_operation_button(ctx, id, 'C', false, 0, 5, 0))
                                    .child(generate_operation_button(ctx, id, '/', true, 6, 3, 0))
                                    // row 2
                                    .child(generate_digit_button(ctx, id, '7', false, 0, 1, 2))
                                    .child(generate_digit_button(ctx, id, '8', false, 2, 1, 2))
                                    .child(generate_digit_button(ctx, id, '9', false, 4, 1, 2))
                                    .child(generate_operation_button(ctx, id, '*', true, 6, 1, 2))
                                    // row 4
                                    .child(generate_digit_button(ctx, id, '4', false, 0, 1, 4))
                                    .child(generate_digit_button(ctx, id, '5', false, 2, 1, 4))
                                    .child(generate_digit_button(ctx, id, '6', false, 4, 1, 4))
                                    .child(generate_operation_button(ctx, id, '-', true, 6, 1, 4))
                                    // row 6
                                    .child(generate_digit_button(ctx, id, '1', false, 0, 1, 6))
                                    .child(generate_digit_button(ctx, id, '2', false, 2, 1, 6))
                                    .child(generate_digit_button(ctx, id, '3', false, 4, 1, 6))
                                    .child(generate_operation_button(ctx, id, '+', true, 6, 1, 6))
                                    // row 8
                                    .child(generate_digit_button(ctx, id, '0', false, 0, 3, 8))
                                    .child(generate_digit_button(ctx, id, '.', false, 4, 1, 8))
                                    .child(generate_operation_button(ctx, id, '=', true, 6, 1, 8))
                                    .build(ctx),
                            )
                            .build(ctx),
                    )
                    .build(ctx),
            )
    }
}

fn main() {
    Application::new()
        .window(|ctx| {
            Window::create()
                .title("OrbTk - Calculator example")
                .position((100.0, 100.0))
                .size(212.0, 336.0)
                .theme(get_theme())
                .child(MainView::create().build(ctx))
                .build(ctx)
        })
        .run();
}

// helper to request MainViewState
fn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {
    states.get_mut(id)
}
<|endoftext|>


<commit_before>extern crate ggez;

use ggez::*;
use ggez::event::*;
use ggez::graphics::{DrawMode, Point2};

struct MainState {
    pos_x: f32,
}

impl MainState {
    fn new() -> MainState {
        MainState { pos_x: 100.0 }
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
        graphics::clear(ctx);
        graphics::circle(ctx,
                         DrawMode::Fill,
                         Point2::new(self.pos_x, 380.0),
                         100.0,
                         1.0)?;
        graphics::present(ctx);
        Ok(())
    }

    fn mouse_button_down_event(&mut self,
                               _ctx: &mut Context,
                               button: MouseButton,
                               x: i32,
                               y: i32) {
        println!("Mouse button pressed: {:?}, x: {}, y: {}", button, x, y);
    }

    fn mouse_button_up_event(&mut self, _ctx: &mut Context, button: MouseButton, x: i32, y: i32) {
        println!("Mouse button released: {:?}, x: {}, y: {}", button, x, y);
    }

    fn mouse_motion_event(&mut self,
                          _ctx: &mut Context,
                          _state: MouseState,
                          x: i32,
                          y: i32,
                          xrel: i32,
                          yrel: i32) {
        println!("Mouse motion, x: {}, y: {}, relative x: {}, relative y: {}",
                 x,
                 y,
                 xrel,
                 yrel);
    }

    fn mouse_wheel_event(&mut self, _ctx: &mut Context, x: i32, y: i32) {
        println!("Mousewheel event, x: {}, y: {}", x, y);
    }

    fn key_down_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) {
        println!("Key pressed: {:?}, modifier {:?}, repeat: {}",
                 keycode,
                 keymod,
                 repeat);
    }
    fn key_up_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) {
        println!("Key released: {:?}, modifier {:?}, repeat: {}",
                 keycode,
                 keymod,
                 repeat);
    }

    fn controller_button_down_event(&mut self, _ctx: &mut Context, btn: Button, instance_id: i32) {
        println!("Controller button pressed: {:?} Controller_Id: {}",
                 btn,
                 instance_id);
    }

    fn controller_button_up_event(&mut self, _ctx: &mut Context, btn: Button, instance_id: i32) {
        println!("Controller button released: {:?} Controller_Id: {}",
                 btn,
                 instance_id);
    }

    fn controller_axis_event(&mut self,
                             _ctx: &mut Context,
                             axis: Axis,
                             value: i16,
                             instance_id: i32) {
        println!("Axis Event: {:?} Value: {} Controller_Id: {}",
                 axis,
                 value,
                 instance_id);
    }

    fn focus_event(&mut self, _ctx: &mut Context, gained: bool) {
        if gained {
            println!("Focus gained");
        } else {
            println!("Focus lost");
        }
    }
}

pub fn main() {
    let c = conf::Conf::new();
    let ctx = &mut Context::load_from_conf("event_test", "ggez", c).unwrap();
    let state = &mut MainState::new();
    event::run(ctx, state).unwrap();
}
<commit_msg>Apply mouse input in the input_test example<commit_after>extern crate ggez;

use ggez::*;
use ggez::event::*;
use ggez::graphics::{DrawMode, Point2};

struct MainState {
    pos_x: i32,
    mouse_down: bool,
}

impl MainState {
    fn new() -> MainState {
        MainState {
            pos_x: 100,
            mouse_down: false,
        }
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult<()> {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult<()> {
        graphics::clear(ctx);
        graphics::circle(ctx,
                         DrawMode::Fill,
                         Point2::new(self.pos_x as f32, 380.0),
                         100.0,
                         1.0)?;
        graphics::present(ctx);
        Ok(())
    }

    fn mouse_button_down_event(&mut self,
                               _ctx: &mut Context,
                               button: MouseButton,
                               x: i32,
                               y: i32) {
        self.mouse_down = true;
        self.pos_x = x;
        println!("Mouse button pressed: {:?}, x: {}, y: {}", button, x, y);
    }

    fn mouse_button_up_event(&mut self, _ctx: &mut Context, button: MouseButton, x: i32, y: i32) {
        self.mouse_down = false;
        self.pos_x = x;
        println!("Mouse button released: {:?}, x: {}, y: {}", button, x, y);
    }

    fn mouse_motion_event(&mut self,
                          _ctx: &mut Context,
                          _state: MouseState,
                          x: i32,
                          y: i32,
                          xrel: i32,
                          yrel: i32) {
        if self.mouse_down {
            self.pos_x = x;
        }
        println!("Mouse motion, x: {}, y: {}, relative x: {}, relative y: {}",
                 x,
                 y,
                 xrel,
                 yrel);
    }

    fn mouse_wheel_event(&mut self, _ctx: &mut Context, x: i32, y: i32) {
        println!("Mousewheel event, x: {}, y: {}", x, y);
    }

    fn key_down_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) {
        println!("Key pressed: {:?}, modifier {:?}, repeat: {}",
                 keycode,
                 keymod,
                 repeat);
    }
    fn key_up_event(&mut self, _ctx: &mut Context, keycode: Keycode, keymod: Mod, repeat: bool) {
        println!("Key released: {:?}, modifier {:?}, repeat: {}",
                 keycode,
                 keymod,
                 repeat);
    }

    fn controller_button_down_event(&mut self, _ctx: &mut Context, btn: Button, instance_id: i32) {
        println!("Controller button pressed: {:?} Controller_Id: {}",
                 btn,
                 instance_id);
    }

    fn controller_button_up_event(&mut self, _ctx: &mut Context, btn: Button, instance_id: i32) {
        println!("Controller button released: {:?} Controller_Id: {}",
                 btn,
                 instance_id);
    }

    fn controller_axis_event(&mut self,
                             _ctx: &mut Context,
                             axis: Axis,
                             value: i16,
                             instance_id: i32) {
        println!("Axis Event: {:?} Value: {} Controller_Id: {}",
                 axis,
                 value,
                 instance_id);
    }

    fn focus_event(&mut self, _ctx: &mut Context, gained: bool) {
        if gained {
            println!("Focus gained");
        } else {
            println!("Focus lost");
        }
    }
}

pub fn main() {
    let c = conf::Conf::new();
    let ctx = &mut Context::load_from_conf("event_test", "ggez", c).unwrap();
    let state = &mut MainState::new();
    event::run(ctx, state).unwrap();
}
<|endoftext|>


<commit_before>use hyper::Client;
use hyper::client::Response;
use serde_json::StreamDeserializer;
use std::io;
use std::io::{BufRead, BufReader, Read};
use std::sync::mpsc::{Sender, channel};
use std::thread;
use super::Error;
use super::rand;
use super::serde_json;
use super::term;
use super::url;

include!(concat!(env!("OUT_DIR"), "/logs.rs"));

const PROXY_HOST: &'static str = "http://127.0.0.1:8001";

#[derive(Debug)]
struct Record {
    namespace: String,
    pod: String,
    container: String,
    color: term::color::Color,
    text: String,
}

#[derive(Default, Debug)]
pub struct Logs {
    follow: bool,
    label: Option<String>,
    namespace: Option<String>,
}

struct Pods {
    inner: Box<Iterator<Item = Pod>>,
}

impl Pods {
    pub fn new<Bytes>(follow: bool, bytes: Bytes) -> Result<Pods, Error>
        where Bytes: 'static + Iterator<Item = io::Result<u8>>
    {
        if follow {
            let s: StreamDeserializer<PodEvent, _> = StreamDeserializer::new(bytes);
            Ok(Pods { inner: Box::new(s.filter_map(|e| e.ok()).map(|e| e.object)) })
        } else {
            Ok(Pods {
                inner: Box::new(try!(serde_json::from_iter::<_, PodList>(bytes)).items.into_iter()),
            })
        }
    }
}

impl Iterator for Pods {
    type Item = Pod;
    fn next(&mut self) -> Option<Pod> {
        self.inner.next()
    }
}

struct ColorWheel {
    colors: Vec<term::color::Color>,
    rng: rand::ThreadRng,
}

impl ColorWheel {
    fn new() -> ColorWheel {
        ColorWheel {
            colors: vec![term::color::CYAN,
                         term::color::MAGENTA,
                         term::color::GREEN,
                         term::color::YELLOW,
                         term::color::BRIGHT_BLUE],
            rng: rand::thread_rng(),
        }
    }
}

impl Iterator for ColorWheel {
    type Item = term::color::Color;
    fn next(&mut self) -> Option<term::color::Color> {
        Some(rand::sample(&mut self.rng, self.colors.clone(), 1)[0])
    }
}

impl Logs {
    pub fn new(follow: bool, label: Option<String>, namespace: Option<String>) -> Logs {
        Logs {
            follow: follow,
            label: label,
            namespace: namespace,
        }
    }

    pub fn fetch(&self) -> Result<(), Error> {
        let mut colors = ColorWheel::new();
        let (tx, rx) = channel();
        let mut t = term::stdout().unwrap();
        thread::spawn(move || {
            loop {
                if let Ok(Record { namespace, pod, container, color, text }) = rx.recv() {
                    t.reset().unwrap();
                    t.fg(color).unwrap();
                    write!(t, "{}/{}/{}: ", namespace, pod, container).unwrap();
                    t.reset().unwrap();
                    writeln!(t, " {}", text).unwrap();
                }
            }
        });

        let client = Client::new();
        let mut pods_endpoint = match self.namespace {
            Some(ref ns) => {
                try!(try!(url::Url::parse(PROXY_HOST))
                    .join(&format!("/api/v1/namespaces/{}/pods", ns)))
            }
            _ => try!(try!(url::Url::parse(PROXY_HOST)).join("/api/v1/pods")),

        };
        if let Some(ref label) = self.label {
            pods_endpoint.query_pairs_mut().append_pair("labelSelector", label);
        }
        if self.follow {
            pods_endpoint.query_pairs_mut().append_pair("watch", true.to_string().as_str());
        }
        let response = try!(client.get(pods_endpoint).send());

        for pod in try!(Pods::new(self.follow, response.bytes())) {
            let color = colors.next().unwrap();
            for container in pod.spec.containers {
                let pxc = tx.clone();
                let this_namespace = pod.metadata.namespace.clone();
                let this_pod_name = pod.metadata.name.clone();
                let mut logs_endpoint = url::Url::parse(PROXY_HOST)
                    .unwrap()
                    .join(&format!("/api/v1/namespaces/{}/pods/{}/log",
                                   this_namespace,
                                   this_pod_name))
                    .unwrap();
                logs_endpoint.query_pairs_mut()
                    .extend_pairs(vec![("container", container.name.as_str()),
                                       ("follow", self.follow.to_string().as_str())]);
                let reader = BufReader::new(client.get(logs_endpoint).send().unwrap());

                thread::spawn(move || {
                    for l in reader.lines() {
                        if let Ok(text) = l {
                            let _ = pxc.send(Record {
                                namespace: this_namespace.clone(),
                                pod: this_pod_name.clone(),
                                container: container.name.clone(),
                                color: color,
                                text: text,
                            });
                        }
                    }
                });
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}
<commit_msg>better names<commit_after>use hyper::Client;
use serde_json::StreamDeserializer;
use std::io;
use std::io::{BufRead, BufReader, Read};
use std::sync::mpsc::channel;
use std::thread;
use super::Error;
use super::rand;
use super::serde_json;
use super::term;
use super::url;

include!(concat!(env!("OUT_DIR"), "/logs.rs"));

const PROXY_HOST: &'static str = "http://127.0.0.1:8001";

#[derive(Debug)]
struct Record {
    namespace: String,
    pod: String,
    container: String,
    color: term::color::Color,
    text: String,
}

#[derive(Default, Debug)]
pub struct Logs {
    follow: bool,
    label: Option<String>,
    namespace: Option<String>,
}

struct Pods {
    inner: Box<Iterator<Item = Pod>>,
}

impl Pods {
    pub fn new<Bytes>(follow: bool, bytes: Bytes) -> Result<Pods, Error>
        where Bytes: 'static + Iterator<Item = io::Result<u8>>
    {
        if follow {
            let s: StreamDeserializer<PodEvent, _> = StreamDeserializer::new(bytes);
            Ok(Pods { inner: Box::new(s.filter_map(|e| e.ok()).map(|e| e.object)) })
        } else {
            Ok(Pods {
                inner: Box::new(try!(serde_json::from_iter::<_, PodList>(bytes)).items.into_iter()),
            })
        }
    }
}

impl Iterator for Pods {
    type Item = Pod;
    fn next(&mut self) -> Option<Pod> {
        self.inner.next()
    }
}

struct ColorWheel {
    colors: Vec<term::color::Color>,
    rng: rand::ThreadRng,
}

impl ColorWheel {
    fn new() -> ColorWheel {
        ColorWheel {
            colors: vec![term::color::CYAN,
                         term::color::MAGENTA,
                         term::color::GREEN,
                         term::color::YELLOW,
                         term::color::BRIGHT_BLUE],
            rng: rand::thread_rng(),
        }
    }
}

impl Iterator for ColorWheel {
    type Item = term::color::Color;
    fn next(&mut self) -> Option<term::color::Color> {
        Some(rand::sample(&mut self.rng, self.colors.clone(), 1)[0])
    }
}

impl Logs {
    pub fn new(follow: bool, label: Option<String>, namespace: Option<String>) -> Logs {
        Logs {
            follow: follow,
            label: label,
            namespace: namespace,
        }
    }

    pub fn fetch(&self) -> Result<(), Error> {
        let mut colors = ColorWheel::new();
        let (tx, rx) = channel();
        let mut t = term::stdout().unwrap();
        thread::spawn(move || {
            loop {
                if let Ok(Record { namespace, pod, container, color, text }) = rx.recv() {
                    t.reset().unwrap();
                    t.fg(color).unwrap();
                    write!(t, "{}/{}/{}: ", namespace, pod, container).unwrap();
                    t.reset().unwrap();
                    writeln!(t, " {}", text).unwrap();
                }
            }
        });

        let client = Client::new();
        let mut pods_endpoint = match self.namespace {
            Some(ref ns) => {
                try!(try!(url::Url::parse(PROXY_HOST))
                    .join(&format!("/api/v1/namespaces/{}/pods", ns)))
            }
            _ => try!(try!(url::Url::parse(PROXY_HOST)).join("/api/v1/pods")),

        };
        if let Some(ref label) = self.label {
            pods_endpoint.query_pairs_mut().append_pair("labelSelector", label);
        }
        if self.follow {
            pods_endpoint.query_pairs_mut().append_pair("watch", true.to_string().as_str());
        }
        let response = try!(client.get(pods_endpoint).send());

        for pod in try!(Pods::new(self.follow, response.bytes())) {
            let color = colors.next().unwrap();
            for container in pod.spec.containers {
                let pxc = tx.clone();
                let namespace = pod.metadata.namespace.clone();
                let pod_name = pod.metadata.name.clone();
                let mut logs_endpoint = url::Url::parse(PROXY_HOST)
                    .unwrap()
                    .join(&format!("/api/v1/namespaces/{}/pods/{}/log", namespace, pod_name))
                    .unwrap();
                logs_endpoint.query_pairs_mut()
                    .extend_pairs(vec![("container", container.name.as_str()),
                                       ("follow", self.follow.to_string().as_str())]);
                let reader = BufReader::new(client.get(logs_endpoint).send().unwrap());

                thread::spawn(move || {
                    for l in reader.lines() {
                        if let Ok(text) = l {
                            let _ = pxc.send(Record {
                                namespace: namespace.clone(),
                                pod: pod_name.clone(),
                                container: container.name.clone(),
                                color: color,
                                text: text,
                            });
                        }
                    }
                });
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}
<|endoftext|>