<commit_before>use std::collections::HashMap;

pub static APRSIS_SERVERS: Vec<&'static str> = ["rotate.aprs.net", "noam.aprs2.net"].to_vec();
pub static APRSIS_SW_VERSION: &'static str = "APRS Rust Module";

lazy_static! {
    pub static ref APRSIS_HTTP_HEADERS: HashMap<&'static str, &'static str> = {
        let mut h = HashMap::new();
        h.insert("content-type", "application/octet-stream");
        h.insert("accept", "text/plain");
        h
    };
}

pub static APRSIS_FILTER_PORT: usize = 14580;
pub static APRSIS_RX_PORT: usize = 8080;
pub static APRSIS_URL: &'static str = "http://srvr.aprs-is.net:8080";

pub static RECV_BUFFER: usize = 1024;

pub static DEFAULT_TOCALL: &'static str = "APYT70";

/// AX.25 Flag - The flag field at each end of the frame is the
///              bit sequence 0x7E that separates each frame.
pub static AX25_FLAG: u8 = 0x7E;
/// AX.25 Control Field - This field is set to 0x03 (UI-frame).
pub static AX25_CONTROL_FIELD: u8 = 0x03;
/// AX.25 Protocol ID - This field is set to 0xF0 (no layer 3 protocol).
pub static AX25_PROTOCOL_ID: u8 = 0xF0;
/// A good place to split AX.25 address from information fields.
pub static ADDR_INFO_DELIM: String = format!("{}{}", &AX25_CONTROL_FIELD, &AX25_PROTOCOL_ID);

lazy_static! {
    pub static ref DATA_TYPE_MAP: HashMap<&'static str, &'static str> = {
        let mut d = HashMap::new();
        d.insert(">", "status");
        d.insert("!", "position_nots_nomsg");
        d.insert("=", "position_nots_msg");
        d.insert("T", "telemetry");
        d.insert(";", "object");
        d.insert("`", "old_mice");
        d
    };
}

/// KISS Command Codes
/// https://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes
pub static KISS_DATA_FRAME: u8 = 0x00;
<commit_msg>Fix constants/statics.<commit_after>use std::collections::HashMap;

pub static APRSIS_SERVERS: &'static [&'static str; 2] = &["rotate.aprs.net", "noam.aprs2.net"];
pub static APRSIS_SW_VERSION: &'static str = "APRS Rust Module";

lazy_static! {
    pub static ref APRSIS_HTTP_HEADERS: HashMap<&'static str, &'static str> = {
        let mut h: HashMap<&'static str, &'static str> = HashMap::new();
        h.insert("content-type", "application/octet-stream");
        h.insert("accept", "text/plain");
        h
    };
}

pub const APRSIS_FILTER_PORT: usize = 14580;
pub const APRSIS_RX_PORT: usize = 8080;
pub static APRSIS_URL: &'static str = "http://srvr.aprs-is.net:8080";

pub const RECV_BUFFER: usize = 1024;

pub static DEFAULT_TOCALL: &'static str = "APYT70";

/// AX.25 Flag - The flag field at each end of the frame is the
///              bit sequence 0x7E that separates each frame.
pub const AX25_FLAG: u8 = 0x7E;
/// AX.25 Control Field - This field is set to 0x03 (UI-frame).
pub const AX25_CONTROL_FIELD: u8 = 0x03;
/// AX.25 Protocol ID - This field is set to 0xF0 (no layer 3 protocol).
pub const AX25_PROTOCOL_ID: u8 = 0xF0;
/// A good place to split AX.25 address from information fields.
pub const ADDR_INFO_DELIM: [u8; 2] = [0x03, 0xF0];

lazy_static! {
    pub static ref DATA_TYPE_MAP: HashMap<&'static str, &'static str> = {
        let mut d: HashMap<&'static str, &'static str> = HashMap::new();
        d.insert(">", "status");
        d.insert("!", "position_nots_nomsg");
        d.insert("=", "position_nots_msg");
        d.insert("T", "telemetry");
        d.insert(";", "object");
        d.insert("`", "old_mice");
        d
    };
}

/// KISS Command Codes
/// https://en.wikipedia.org/wiki/KISS_(TNC)#Command_Codes
pub const KISS_DATA_FRAME: u8 = 0x00;
<|endoftext|>


<commit_before>// Copyright 2016-17 Alexander Reece
//
// 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.

use std::ops::Deref;

use inflections::Inflect;
use specs;

use common::{Field, DomainMapper};

#[derive(Debug, Clone)]
pub struct ClassMethod {
    method: &'static specs::ClassMethod,
    fields: Vec<Field>,
    constant_case: String,
    pascal_case: String,
    snake_case: String,
    has_lifetimes: bool,
    has_usable_fields: bool,
}

impl ClassMethod {
    pub fn new(spec: &'static specs::Spec, method: &'static specs::ClassMethod) -> Self {
        let domain_mapper = DomainMapper::from_spec(spec);
        let fields = method.fields()
            .map(|field| {
                let domain = domain_mapper.map(field.domain());
                Field::new(field, domain)
            })
            .collect::<Vec<_>>();

        let has_lifetimes = fields.iter()
            .filter(|field| !field.is_reserved())
            .any(|field| !field.ty().is_copy());

        let constant_case = method.name().to_constant_case();
        let pascal_case = method.name().to_pascal_case();
        let snake_case = method.name().to_snake_case();
        let has_usable_fields = method.fields().any(|f| !f.is_reserved());

        ClassMethod {
            method: method,
            fields: fields,
            constant_case: constant_case,
            pascal_case: pascal_case,
            snake_case: snake_case,
            has_lifetimes: has_lifetimes,
            has_usable_fields: has_usable_fields,
        }
    }

    pub fn method(&self) -> &'static specs::ClassMethod {
        self.method
    }

    pub fn name(&self) -> &'static str {
        self.method.name()
    }

    pub fn fields(&self) -> &[Field] {
        &self.fields
    }

    pub fn constant_case(&self) -> &str {
        &self.constant_case
    }

    pub fn snake_case(&self) -> &str {
        &self.snake_case
    }

    pub fn pascal_case(&self) -> &str {
        &self.pascal_case
    }

    pub fn has_lifetimes(&self) -> bool {
        self.has_lifetimes
    }

    pub fn has_usable_fields(&self) -> bool {
        self.has_usable_fields
    }
}

impl Deref for ClassMethod {
    type Target = specs::ClassMethod;

    fn deref(&self) -> &Self::Target {
        self.method
    }
}<commit_msg>[codegen] Add the field() and field_var() methods to common::ClassMethod<commit_after>// Copyright 2016-17 Alexander Reece
//
// 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.

use std::collections::BTreeMap;
use std::ops::Deref;

use inflections::Inflect;
use specs;

use common::{Field, DomainMapper};

#[derive(Debug, Clone)]
pub struct ClassMethod {
    method: &'static specs::ClassMethod,
    fields: Vec<Field>,
    field_names: BTreeMap<&'static str, usize>,
    field_vars: BTreeMap<String, usize>,
    constant_case: String,
    pascal_case: String,
    snake_case: String,
    has_lifetimes: bool,
    has_usable_fields: bool,
}

impl ClassMethod {
    pub fn new(spec: &'static specs::Spec, method: &'static specs::ClassMethod) -> Self {
        let domain_mapper = DomainMapper::from_spec(spec);
        let fields = method.fields()
            .map(|field| {
                let domain = domain_mapper.map(field.domain());
                Field::from_field(field, domain)
            })
            .collect::<Vec<_>>();

        let has_lifetimes = fields.iter()
            .filter(|field| !field.is_reserved())
            .any(|field| !field.ty().is_copy());

        let constant_case = method.name().to_constant_case();
        let pascal_case = method.name().to_pascal_case();
        let snake_case = method.name().to_snake_case();
        let has_usable_fields = method.fields().any(|f| !f.is_reserved());
        let field_names = method.fields()
            .enumerate()
            .map(|(index, field)| (field.name(), index))
            .collect();
        let field_vars = fields.iter()
            .enumerate()
            .map(|(index, field)| ((&**field.var_name()).clone(), index))
            .collect();

        ClassMethod {
            method: method,
            fields: fields,
            field_names: field_names,
            field_vars: field_vars,
            constant_case: constant_case,
            pascal_case: pascal_case,
            snake_case: snake_case,
            has_lifetimes: has_lifetimes,
            has_usable_fields: has_usable_fields,
        }
    }

    pub fn method(&self) -> &'static specs::ClassMethod {
        self.method
    }

    pub fn name(&self) -> &'static str {
        self.method.name()
    }

    pub fn field(&self, name: &str) -> Option<&Field> {
        self.field_names.get(name)
            .map(|index| &self.fields[*index])
    }

    pub fn field_by_var(&self, var_name: &str) -> Option<&Field> {
        self.field_vars.get(var_name)
            .map(|index| &self.fields[*index])
    }

    pub fn fields(&self) -> &[Field] {
        &self.fields
    }

    pub fn constant_case(&self) -> &str {
        &self.constant_case
    }

    pub fn snake_case(&self) -> &str {
        &self.snake_case
    }

    pub fn pascal_case(&self) -> &str {
        &self.pascal_case
    }

    pub fn has_lifetimes(&self) -> bool {
        self.has_lifetimes
    }

    pub fn has_usable_fields(&self) -> bool {
        self.has_usable_fields
    }
}

impl Deref for ClassMethod {
    type Target = specs::ClassMethod;

    fn deref(&self) -> &Self::Target {
        self.method
    }
}<|endoftext|>


<commit_before>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

#[macro_use]
extern crate habitat_sup as sup;
extern crate habitat_core as hcore;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate ansi_term;
extern crate libc;
#[macro_use]
extern crate clap;

use std::ffi::CString;
use std::process;
use std::ptr;
use std::result;
use std::str::FromStr;

use ansi_term::Colour::Yellow;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use hcore::package::PackageIdent;
use hcore::env as henv;
use hcore::fs;
use hcore::url::{DEFAULT_DEPOT_URL, DEPOT_URL_ENVVAR};

use sup::config::{Command, Config, UpdateStrategy};
use sup::error::{Error, Result, SupError};
use sup::command::*;
use sup::topology::Topology;

/// Our output key
static LOGKEY: &'static str = "MN";

/// The version number
const VERSION: &'static str = include_str!(concat!(env!("OUT_DIR"), "/VERSION"));

/// CLI defaults
static DEFAULT_GROUP: &'static str = "default";
static DEFAULT_GOSSIP_LISTEN: &'static str = "0.0.0.0:9634";

/// Creates a [Config](config/struct.Config.html) from global args
/// and subcommand args.
fn config_from_args(args: &ArgMatches, subcommand: &str, sub_args: &ArgMatches) -> Result<Config> {
    let mut config = Config::new();
    let command = try!(Command::from_str(subcommand));
    config.set_command(command);
    if let Some(ref strategy) = sub_args.value_of("strategy") {
        config.set_update_strategy(UpdateStrategy::from_str(strategy));
    }
    if let Some(ref archive) = sub_args.value_of("archive") {
        config.set_archive(archive.to_string());
    }
    if let Some(ref package) = sub_args.value_of("package") {
        let ident = try!(PackageIdent::from_str(package));
        config.set_package(ident);
    }
    if let Some(key) = sub_args.value_of("key") {
        config.set_key(key.to_string());
    }
    if let Some(password) = sub_args.value_of("password") {
        config.set_password(password.to_string());
    }
    if let Some(email) = sub_args.value_of("email") {
        config.set_email(email.to_string());
    }
    if let Some(user) = sub_args.value_of("user") {
        config.set_user_key(user.to_string());
    }
    if let Some(service) = sub_args.value_of("service") {
        config.set_service_key(service.to_string());
    }
    if let Some(infile) = sub_args.value_of("infile") {
        config.set_infile(infile.to_string());
    }
    if let Some(outfile) = sub_args.value_of("outfile") {
        config.set_outfile(outfile.to_string());
    }
    if let Some(topology) = sub_args.value_of("topology") {
        match topology.as_ref() {
            "standalone" => {
                config.set_topology(Topology::Standalone);
            }
            "leader" => {
                config.set_topology(Topology::Leader);
            }
            "initializer" => {
                config.set_topology(Topology::Initializer);
            }
            t => return Err(sup_error!(Error::UnknownTopology(String::from(t)))),
        }
    }
    if sub_args.value_of("expire-days").is_some() {
        let ed = value_t!(sub_args.value_of("expire-days"), u16).unwrap_or_else(|e| e.exit());
        config.set_expire_days(ed);
    }
    let env_or_default = henv::var(DEPOT_URL_ENVVAR).unwrap_or(DEFAULT_DEPOT_URL.to_string());
    let url = sub_args.value_of("url").unwrap_or(&env_or_default);
    config.set_url(url.to_string());
    config.set_group(sub_args.value_of("group").unwrap_or(DEFAULT_GROUP).to_string());
    let bindings = match sub_args.values_of("bind") {
        Some(bind) => bind.map(|s| s.to_string()).collect(),
        None => vec![],
    };
    config.set_bind(bindings);
    config.set_path(sub_args.value_of("path")
                            .unwrap_or(fs::svc_path(sup::PROGRAM_NAME.as_str())
                                           .join("data")
                                           .to_string_lossy()
                                           .as_ref())
                            .to_string());
    config.set_gossip_listen(sub_args.value_of("listen-peer")
                                     .unwrap_or(DEFAULT_GOSSIP_LISTEN)
                                     .to_string());
    let gossip_peers = match sub_args.values_of("peer") {
        Some(gp) => gp.map(|s| s.to_string()).collect(),
        None => vec![],
    };
    config.set_gossip_peer(gossip_peers);
    if sub_args.value_of("permanent-peer").is_some() {
        config.set_gossip_permanent(true);
    }
    if let Some(sg) = sub_args.value_of("service-group") {
        config.set_service_group(sg.to_string());
    }
    if let Some(fp) = sub_args.value_of("file-path") {
        config.set_file_path(fp.to_string());
    }
    config.set_version_number(value_t!(sub_args, "version-number", u64).unwrap_or(0));
    if let Some(ring) = sub_args.value_of("ring") {
        config.set_ring(ring.to_string());
    }
    if args.value_of("verbose").is_some() {
        sup::output::set_verbose(true);
    }
    if args.value_of("no-color").is_some() {
        sup::output::set_no_color(true);
    }

    if let Some(org) = sub_args.value_of("organization") {
        config.set_organization(org.to_string());
    }
    debug!("Config:\n{:?}", config);
    Ok(config)
}

type Handler = fn(&Config) -> result::Result<(), sup::error::SupError>;

/// The entrypoint for the Supervisor.
///
/// * Set up the logger
/// * Pull in the arguments from the Command Line, push through clap
/// * Dispatch to a function that handles that action called
/// * Exit cleanly, or if we return an `Error`, call `exit_with(E, 1)`
#[allow(dead_code)]
fn main() {
    env_logger::init().unwrap();

    let arg_url = || {
        Arg::with_name("url")
            .short("u")
            .long("url")
            .takes_value(true)
            .help("Use the specified package depot url")
    };
    let arg_group = || {
        Arg::with_name("group")
            .long("group")
            .takes_value(true)
            .help("The service group; shared config and topology [default: default].")
    };

    let arg_org = || {
        Arg::with_name("organization")
            .long("org")
            .takes_value(true)
            .help("The organization that a service is part of")
    };

    let arg_strategy = || {
        Arg::with_name("strategy")
            .long("strategy")
            .short("s")
            .takes_value(true)
            .possible_values(&["none", "at-once"])
            .help("The update strategy; [default: none].")
    };

    let sub_start = SubCommand::with_name("start")
                        .about("Start a Habitat-supervised service from a package")
                        .arg(Arg::with_name("package")
                                 .index(1)
                                 .required(true)
                                 .help("Name of package to start"))
                        .arg(arg_url())
                        .arg(arg_group())
                        .arg(arg_org())
                        .arg(arg_strategy())
                        .arg(Arg::with_name("topology")
                                 .short("t")
                                 .long("topology")
                                 .value_name("topology")
                                 .help("Service topology"))
                        .arg(Arg::with_name("bind")
                                 .long("bind")
                                 .value_name("bind")
                                 .multiple(true)
                                 .help("One or more service groups to bind to a configuration"))
                        .arg(Arg::with_name("ring")
                                 .short("r")
                                 .long("ring")
                                 .value_name("ring")
                                 .help("Ring key name"))
                        .arg(Arg::with_name("peer")
                                 .long("peer")
                                 .value_name("ip:port")
                                 .multiple(true)
                                 .help("The listen address of an initial peer"))
                        .arg(Arg::with_name("listen-peer")
                                 .long("listen-peer")
                                 .value_name("ip:port")
                                 .help("The listen address [default: 0.0.0.0:9634]"))
                        .arg(Arg::with_name("permanent-peer")
                                 .short("I")
                                 .long("permanent-peer")
                                 .help("If this service is a permanent peer"));
    let sub_sh = SubCommand::with_name("sh").about("Start an interactive shell");
    let sub_config = SubCommand::with_name("config")
                         .about("Print the default.toml for a given package")
                         .arg(Arg::with_name("package")
                                  .index(1)
                                  .required(true)
                                  .help("Name of package"));
    let args = App::new(sup::PROGRAM_NAME.as_str())
                   .version(VERSION)
                   .setting(AppSettings::VersionlessSubcommands)
                   .setting(AppSettings::SubcommandRequiredElseHelp)
                   .arg(Arg::with_name("verbose")
                            .short("v")
                            .global(true)
                            .help("Verbose output; shows line numbers"))
                   .arg(Arg::with_name("no-color")
                            .long("no-color")
                            .global(true)
                            .help("Turn ANSI color off :("))
                   .subcommand(sub_start)
                   .subcommand(sub_sh)
                   .subcommand(sub_config);
    let matches = args.get_matches();

    debug!("clap matches {:?}", matches);

    let subcommand_name = matches.subcommand_name().unwrap();
    let subcommand_matches = matches.subcommand_matches(subcommand_name).unwrap();

    let config = match config_from_args(&matches, subcommand_name, &subcommand_matches) {
        Ok(config) => config,
        Err(e) => return exit_with(e, 1),
    };

    let result = match config.command() {
        Command::Shell => shell(&config),
        Command::Config => configure(&config),
        Command::Start => start(&config),
    };

    match result {
        Ok(_) => std::process::exit(0),
        Err(e) => exit_with(e, 1),
    }
}

/// Exit with an error message and the right status code
#[allow(dead_code)]
fn exit_with(e: SupError, code: i32) {
    println!("{}", e);
    process::exit(code)
}

/// Start a shell
#[allow(dead_code)]
fn shell(_config: &Config) -> Result<()> {
    outputln!("Starting your shell; enjoy!");
    let shell_arg = try!(CString::new("sh"));
    let mut argv = [shell_arg.as_ptr(), ptr::null()];
    // Yeah, you don't know any better.. but we aren't coming back from
    // what happens next.
    unsafe {
        libc::execvp(shell_arg.as_ptr(), argv.as_mut_ptr());
    }
    Ok(())
}

/// Show the configuration options for a service
#[allow(dead_code)]
fn configure(config: &Config) -> Result<()> {
    try!(configure::display(config));
    Ok(())
}

/// Start a service
#[allow(dead_code)]
fn start(config: &Config) -> Result<()> {
    outputln!("Starting {}",
              Yellow.bold().paint(config.package().to_string()));
    try!(start::package(config));
    outputln!("Finished with {}",
              Yellow.bold().paint(config.package().to_string()));
    Ok(())
}
<commit_msg>[sup] Honor `HAB_RING` for `start` subcommand.<commit_after>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

#[macro_use]
extern crate habitat_sup as sup;
extern crate habitat_core as hcore;
extern crate rustc_serialize;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate ansi_term;
extern crate libc;
#[macro_use]
extern crate clap;

use std::ffi::CString;
use std::process;
use std::ptr;
use std::result;
use std::str::FromStr;

use ansi_term::Colour::Yellow;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use hcore::package::PackageIdent;
use hcore::env as henv;
use hcore::fs;
use hcore::url::{DEFAULT_DEPOT_URL, DEPOT_URL_ENVVAR};

use sup::config::{Command, Config, UpdateStrategy};
use sup::error::{Error, Result, SupError};
use sup::command::*;
use sup::topology::Topology;

/// Our output key
static LOGKEY: &'static str = "MN";

/// The version number
const VERSION: &'static str = include_str!(concat!(env!("OUT_DIR"), "/VERSION"));

/// CLI defaults
static DEFAULT_GROUP: &'static str = "default";
static DEFAULT_GOSSIP_LISTEN: &'static str = "0.0.0.0:9634";

static RING_ENVVAR: &'static str = "HAB_RING";

/// Creates a [Config](config/struct.Config.html) from global args
/// and subcommand args.
fn config_from_args(args: &ArgMatches, subcommand: &str, sub_args: &ArgMatches) -> Result<Config> {
    let mut config = Config::new();
    let command = try!(Command::from_str(subcommand));
    config.set_command(command);
    if let Some(ref strategy) = sub_args.value_of("strategy") {
        config.set_update_strategy(UpdateStrategy::from_str(strategy));
    }
    if let Some(ref archive) = sub_args.value_of("archive") {
        config.set_archive(archive.to_string());
    }
    if let Some(ref package) = sub_args.value_of("package") {
        let ident = try!(PackageIdent::from_str(package));
        config.set_package(ident);
    }
    if let Some(key) = sub_args.value_of("key") {
        config.set_key(key.to_string());
    }
    if let Some(password) = sub_args.value_of("password") {
        config.set_password(password.to_string());
    }
    if let Some(email) = sub_args.value_of("email") {
        config.set_email(email.to_string());
    }
    if let Some(user) = sub_args.value_of("user") {
        config.set_user_key(user.to_string());
    }
    if let Some(service) = sub_args.value_of("service") {
        config.set_service_key(service.to_string());
    }
    if let Some(infile) = sub_args.value_of("infile") {
        config.set_infile(infile.to_string());
    }
    if let Some(outfile) = sub_args.value_of("outfile") {
        config.set_outfile(outfile.to_string());
    }
    if let Some(topology) = sub_args.value_of("topology") {
        match topology.as_ref() {
            "standalone" => {
                config.set_topology(Topology::Standalone);
            }
            "leader" => {
                config.set_topology(Topology::Leader);
            }
            "initializer" => {
                config.set_topology(Topology::Initializer);
            }
            t => return Err(sup_error!(Error::UnknownTopology(String::from(t)))),
        }
    }
    if sub_args.value_of("expire-days").is_some() {
        let ed = value_t!(sub_args.value_of("expire-days"), u16).unwrap_or_else(|e| e.exit());
        config.set_expire_days(ed);
    }
    let env_or_default = henv::var(DEPOT_URL_ENVVAR).unwrap_or(DEFAULT_DEPOT_URL.to_string());
    let url = sub_args.value_of("url").unwrap_or(&env_or_default);
    config.set_url(url.to_string());
    config.set_group(sub_args.value_of("group").unwrap_or(DEFAULT_GROUP).to_string());
    let bindings = match sub_args.values_of("bind") {
        Some(bind) => bind.map(|s| s.to_string()).collect(),
        None => vec![],
    };
    config.set_bind(bindings);
    config.set_path(sub_args.value_of("path")
                            .unwrap_or(fs::svc_path(sup::PROGRAM_NAME.as_str())
                                           .join("data")
                                           .to_string_lossy()
                                           .as_ref())
                            .to_string());
    config.set_gossip_listen(sub_args.value_of("listen-peer")
                                     .unwrap_or(DEFAULT_GOSSIP_LISTEN)
                                     .to_string());
    let gossip_peers = match sub_args.values_of("peer") {
        Some(gp) => gp.map(|s| s.to_string()).collect(),
        None => vec![],
    };
    config.set_gossip_peer(gossip_peers);
    if sub_args.value_of("permanent-peer").is_some() {
        config.set_gossip_permanent(true);
    }
    if let Some(sg) = sub_args.value_of("service-group") {
        config.set_service_group(sg.to_string());
    }
    if let Some(fp) = sub_args.value_of("file-path") {
        config.set_file_path(fp.to_string());
    }
    config.set_version_number(value_t!(sub_args, "version-number", u64).unwrap_or(0));
    let ring = match sub_args.value_of("ring") {
        Some(val) => Some(val.to_string()),
        None => {
            match henv::var(RING_ENVVAR) {
                Ok(val) => Some(val),
                Err(_) => None,
            }
        }
    };
    if let Some(ring) = ring {
        config.set_ring(ring);
    }
    if args.value_of("verbose").is_some() {
        sup::output::set_verbose(true);
    }
    if args.value_of("no-color").is_some() {
        sup::output::set_no_color(true);
    }

    if let Some(org) = sub_args.value_of("organization") {
        config.set_organization(org.to_string());
    }
    debug!("Config:\n{:?}", config);
    Ok(config)
}

type Handler = fn(&Config) -> result::Result<(), sup::error::SupError>;

/// The entrypoint for the Supervisor.
///
/// * Set up the logger
/// * Pull in the arguments from the Command Line, push through clap
/// * Dispatch to a function that handles that action called
/// * Exit cleanly, or if we return an `Error`, call `exit_with(E, 1)`
#[allow(dead_code)]
fn main() {
    env_logger::init().unwrap();

    let arg_url = || {
        Arg::with_name("url")
            .short("u")
            .long("url")
            .takes_value(true)
            .help("Use the specified package depot url")
    };
    let arg_group = || {
        Arg::with_name("group")
            .long("group")
            .takes_value(true)
            .help("The service group; shared config and topology [default: default].")
    };

    let arg_org = || {
        Arg::with_name("organization")
            .long("org")
            .takes_value(true)
            .help("The organization that a service is part of")
    };

    let arg_strategy = || {
        Arg::with_name("strategy")
            .long("strategy")
            .short("s")
            .takes_value(true)
            .possible_values(&["none", "at-once"])
            .help("The update strategy; [default: none].")
    };

    let sub_start = SubCommand::with_name("start")
                        .about("Start a Habitat-supervised service from a package")
                        .arg(Arg::with_name("package")
                                 .index(1)
                                 .required(true)
                                 .help("Name of package to start"))
                        .arg(arg_url())
                        .arg(arg_group())
                        .arg(arg_org())
                        .arg(arg_strategy())
                        .arg(Arg::with_name("topology")
                                 .short("t")
                                 .long("topology")
                                 .value_name("topology")
                                 .help("Service topology"))
                        .arg(Arg::with_name("bind")
                                 .long("bind")
                                 .value_name("bind")
                                 .multiple(true)
                                 .help("One or more service groups to bind to a configuration"))
                        .arg(Arg::with_name("ring")
                                 .short("r")
                                 .long("ring")
                                 .value_name("ring")
                                 .help("Ring key name"))
                        .arg(Arg::with_name("peer")
                                 .long("peer")
                                 .value_name("ip:port")
                                 .multiple(true)
                                 .help("The listen address of an initial peer"))
                        .arg(Arg::with_name("listen-peer")
                                 .long("listen-peer")
                                 .value_name("ip:port")
                                 .help("The listen address [default: 0.0.0.0:9634]"))
                        .arg(Arg::with_name("permanent-peer")
                                 .short("I")
                                 .long("permanent-peer")
                                 .help("If this service is a permanent peer"));
    let sub_sh = SubCommand::with_name("sh").about("Start an interactive shell");
    let sub_config = SubCommand::with_name("config")
                         .about("Print the default.toml for a given package")
                         .arg(Arg::with_name("package")
                                  .index(1)
                                  .required(true)
                                  .help("Name of package"));
    let args = App::new(sup::PROGRAM_NAME.as_str())
                   .version(VERSION)
                   .setting(AppSettings::VersionlessSubcommands)
                   .setting(AppSettings::SubcommandRequiredElseHelp)
                   .arg(Arg::with_name("verbose")
                            .short("v")
                            .global(true)
                            .help("Verbose output; shows line numbers"))
                   .arg(Arg::with_name("no-color")
                            .long("no-color")
                            .global(true)
                            .help("Turn ANSI color off :("))
                   .subcommand(sub_start)
                   .subcommand(sub_sh)
                   .subcommand(sub_config);
    let matches = args.get_matches();

    debug!("clap matches {:?}", matches);

    let subcommand_name = matches.subcommand_name().unwrap();
    let subcommand_matches = matches.subcommand_matches(subcommand_name).unwrap();

    let config = match config_from_args(&matches, subcommand_name, &subcommand_matches) {
        Ok(config) => config,
        Err(e) => return exit_with(e, 1),
    };

    let result = match config.command() {
        Command::Shell => shell(&config),
        Command::Config => configure(&config),
        Command::Start => start(&config),
    };

    match result {
        Ok(_) => std::process::exit(0),
        Err(e) => exit_with(e, 1),
    }
}

/// Exit with an error message and the right status code
#[allow(dead_code)]
fn exit_with(e: SupError, code: i32) {
    println!("{}", e);
    process::exit(code)
}

/// Start a shell
#[allow(dead_code)]
fn shell(_config: &Config) -> Result<()> {
    outputln!("Starting your shell; enjoy!");
    let shell_arg = try!(CString::new("sh"));
    let mut argv = [shell_arg.as_ptr(), ptr::null()];
    // Yeah, you don't know any better.. but we aren't coming back from
    // what happens next.
    unsafe {
        libc::execvp(shell_arg.as_ptr(), argv.as_mut_ptr());
    }
    Ok(())
}

/// Show the configuration options for a service
#[allow(dead_code)]
fn configure(config: &Config) -> Result<()> {
    try!(configure::display(config));
    Ok(())
}

/// Start a service
#[allow(dead_code)]
fn start(config: &Config) -> Result<()> {
    outputln!("Starting {}",
              Yellow.bold().paint(config.package().to_string()));
    try!(start::package(config));
    outputln!("Finished with {}",
              Yellow.bold().paint(config.package().to_string()));
    Ok(())
}
<|endoftext|>


<commit_before>extern crate cgmath;
extern crate image;
extern crate winit;

#[cfg(windows)]
use winit::os::windows::WindowExt;

#[macro_use]
extern crate vulkano;

use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::mem;
use std::ptr;

fn main() {
    // The start of this example is exactly the same as `triangle`. You should read the
    // `triangle` example if you haven't done so yet.

    // TODO: for the moment the AMD driver crashes if you don't pass an ApplicationInfo, but in theory it's optional
    let app = vulkano::instance::ApplicationInfo { application_name: "test", application_version: 1, engine_name: "test", engine_version: 1 };
    let extensions = vulkano::instance::InstanceExtensions {
        khr_surface: true,
        khr_swapchain: true,
        khr_win32_surface: true,
        .. vulkano::instance::InstanceExtensions::none()
    };
    let instance = vulkano::instance::Instance::new(Some(&app), &[], &extensions).expect("failed to create instance");

    let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
                            .next().expect("no device available");
    println!("Using device: {} (type: {:?})", physical.name(), physical.ty());

    let window = winit::WindowBuilder::new().build().unwrap();
    let surface = unsafe { vulkano::swapchain::Surface::from_hwnd(&instance, ptr::null() as *const () /* FIXME */, window.get_hwnd()).unwrap() };

    let queue = physical.queue_families().find(|q| q.supports_graphics() &&
                                                   surface.is_supported(q).unwrap_or(false))
                                                .expect("couldn't find a graphical queue family");

    let (device, queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
                                                        [(queue, 0.5)].iter().cloned(), &[])
                                                                .expect("failed to create device");
    let queue = queues.into_iter().next().unwrap();

    let (swapchain, images) = {
        let caps = surface.get_capabilities(&physical).expect("failed to get surface capabilities");

        let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
        let present = caps.present_modes[0];
        let usage = caps.supported_usage_flags;

        vulkano::swapchain::Swapchain::new(&device, &surface, 3,
                                           vulkano::format::B8G8R8A8Srgb, dimensions, 1,
                                           &usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
                                           vulkano::swapchain::CompositeAlpha::Opaque,
                                           present, true).expect("failed to create swapchain")
    };

    let cb_pool = vulkano::command_buffer::CommandBufferPool::new(&device, &queue.family())
                                                  .expect("failed to create command buffer pool");

    let vertex_buffer = vulkano::buffer::Buffer::<[Vertex], _>
                               ::array(&device, 4, &vulkano::buffer::Usage::all(),
                                       vulkano::memory::HostVisible, &queue)
                                       .expect("failed to create buffer");

    struct Vertex { position: [f32; 2] }
    impl_vertex!(Vertex, position);

    // The buffer that we created contains uninitialized data.
    // In order to fill it with data, we have to *map* it.
    {
        // The `try_write` function would return `None` if the buffer was in use by the GPU. This
        // obviously can't happen here, since we haven't ask the GPU to do anything yet.
        let mut mapping = vertex_buffer.try_write().unwrap();
        mapping[0].position = [-0.5, -0.5];
        mapping[1].position = [-0.5,  0.5];
        mapping[2].position = [ 0.5, -0.5];
        mapping[3].position = [ 0.5,  0.5];
    }

    mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/examples/image_vs.glsl")} }
    let vs = vs::Shader::load(&device).expect("failed to create shader module");
    mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/examples/image_fs.glsl")} }
    let fs = fs::Shader::load(&device).expect("failed to create shader module");

    mod renderpass {
        single_pass_renderpass!{
            attachments: {
                color: {
                    load: Clear,
                    store: Store,
                    format: B8G8R8A8Srgb,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        }
    }

    let renderpass = vulkano::framebuffer::RenderPass::new(&device, renderpass::Layout).unwrap();

    let texture = vulkano::image::Image::<vulkano::image::Type2d, _, _>::new(&device, &vulkano::image::Usage::all(),
                                                  vulkano::memory::DeviceLocal, &queue,
                                                  vulkano::format::R8G8B8A8Unorm, [93, 93], (), 1).unwrap();
    let texture = texture.transition(vulkano::image::Layout::ShaderReadOnlyOptimal, &cb_pool, &queue).unwrap();
    let texture_view = vulkano::image::ImageView::new(&texture).expect("failed to create image view");

    let pixel_buffer = {
        let image = image::load_from_memory_with_format(include_bytes!("image_img.png"),
                                                        image::ImageFormat::PNG).unwrap().to_rgba();
        let image_data = image.into_raw().clone();

        let pixel_buffer = vulkano::buffer::Buffer::<[[u8; 4]], _>
                               ::array(&device, image_data.len(), &vulkano::buffer::Usage::all(),
                                       vulkano::memory::HostVisible, &queue)
                                       .expect("failed to create buffer");

        {
            let mut mapping = pixel_buffer.try_write().unwrap();
            for (o, i) in mapping.iter_mut().zip(image_data.chunks(4)) {
                o[0] = i[0];
                o[1] = i[1];
                o[2] = i[2];
                o[3] = i[3];
            }
        }

        pixel_buffer
    };

    let sampler = vulkano::sampler::Sampler::new(&device, vulkano::sampler::Filter::Linear,
                                                 vulkano::sampler::Filter::Linear, vulkano::sampler::MipmapMode::Nearest,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 0.0, 1.0, 0.0, 0.0).unwrap();

    let descriptor_pool = vulkano::descriptor_set::DescriptorPool::new(&device).unwrap();
    let descriptor_set_layout = {
        let desc = vulkano::descriptor_set::RuntimeDescriptorSetDesc {
            descriptors: vec![
                vulkano::descriptor_set::DescriptorDesc {
                    binding: 0,
                    ty: vulkano::descriptor_set::DescriptorType::CombinedImageSampler,
                    array_count: 1,
                    stages: vulkano::descriptor_set::ShaderStages::all_graphics(),
                }
            ]
        };

        vulkano::descriptor_set::DescriptorSetLayout::new(&device, desc).unwrap()
    };

    let pipeline_layout = vulkano::descriptor_set::PipelineLayout::new(&device, vulkano::descriptor_set::RuntimeDesc, vec![descriptor_set_layout.clone()]).unwrap();
    let set = vulkano::descriptor_set::DescriptorSet::new(&descriptor_pool, &descriptor_set_layout,
                                                          vec![(0, vulkano::descriptor_set::DescriptorBind::CombinedImageSampler(sampler.clone(), texture_view.clone(), vulkano::image::Layout::ShaderReadOnlyOptimal))]).unwrap();

    let images = images.into_iter().map(|image| {
        let image = image.transition(vulkano::image::Layout::PresentSrc, &cb_pool, &queue).unwrap();
        vulkano::image::ImageView::new(&image).expect("failed to create image view")
    }).collect::<Vec<_>>();

    let pipeline = {
        let ia = vulkano::pipeline::input_assembly::InputAssembly {
            topology: vulkano::pipeline::input_assembly::PrimitiveTopology::TriangleStrip,
            primitive_restart_enable: false,
        };

        let raster = Default::default();
        let ms = vulkano::pipeline::multisample::Multisample::disabled();
        let blend = vulkano::pipeline::blend::Blend {
            logic_op: None,
            blend_constants: Some([0.0; 4]),
        };

        let viewports = vulkano::pipeline::viewport::ViewportsState::Fixed {
            data: vec![(
                vulkano::pipeline::viewport::Viewport {
                    origin: [0.0, 0.0],
                    dimensions: [1244.0, 699.0],
                    depth_range: 0.0 .. 1.0
                },
                vulkano::pipeline::viewport::Scissor {
                    origin: [0, 0],
                    dimensions: [1244, 699],
                }
            )],
        };

        vulkano::pipeline::GraphicsPipeline::new(&device, &vs.main_entry_point(), &ia, &viewports,
                                                 &raster, &ms, &blend, &fs.main_entry_point(),
                                                 &pipeline_layout, renderpass.subpass(0).unwrap())
                                                 .unwrap()
    };

    let framebuffers = images.iter().map(|image| {
        vulkano::framebuffer::Framebuffer::new(&renderpass, (1244, 699, 1), (image.clone() as std::sync::Arc<_>,)).unwrap()
    }).collect::<Vec<_>>();

    let command_buffers = framebuffers.iter().map(|framebuffer| {
        vulkano::command_buffer::PrimaryCommandBufferBuilder::new(&cb_pool).unwrap()
            .copy_buffer_to_color_image(&pixel_buffer, &texture)
            //.clear_color_image(&texture, [0.0, 1.0, 0.0, 1.0])
            .draw_inline(&renderpass, &framebuffer, ([0.0, 0.0, 1.0, 1.0],))
            .draw(&pipeline, vertex_buffer.clone(), &vulkano::command_buffer::DynamicState::none(), set.clone())
            .draw_end()
            .build().unwrap()
    }).collect::<Vec<_>>();

    loop {
        let image_num = swapchain.acquire_next_image(1000000).unwrap();
        command_buffers[image_num].submit(&queue).unwrap();
        swapchain.present(&queue, image_num).unwrap();

        for ev in window.poll_events() {
            match ev {
                winit::Event::Closed => break,
                _ => ()
            }
        }
    }
}
<commit_msg>Image example now working again<commit_after>extern crate cgmath;
extern crate image;
extern crate winit;

#[cfg(windows)]
use winit::os::windows::WindowExt;

#[macro_use]
extern crate vulkano;

use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::mem;
use std::ptr;

fn main() {
    // The start of this example is exactly the same as `triangle`. You should read the
    // `triangle` example if you haven't done so yet.

    // TODO: for the moment the AMD driver crashes if you don't pass an ApplicationInfo, but in theory it's optional
    let app = vulkano::instance::ApplicationInfo { application_name: "test", application_version: 1, engine_name: "test", engine_version: 1 };
    let extensions = vulkano::instance::InstanceExtensions {
        khr_surface: true,
        khr_swapchain: true,
        khr_win32_surface: true,
        .. vulkano::instance::InstanceExtensions::none()
    };
    let instance = vulkano::instance::Instance::new(Some(&app), &extensions, &[]).expect("failed to create instance");

    let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
                            .next().expect("no device available");
    println!("Using device: {} (type: {:?})", physical.name(), physical.ty());

    let window = winit::WindowBuilder::new().build().unwrap();
    let surface = unsafe { vulkano::swapchain::Surface::from_hwnd(&instance, ptr::null() as *const () /* FIXME */, window.get_hwnd()).unwrap() };

    let queue = physical.queue_families().find(|q| q.supports_graphics() &&
                                                   surface.is_supported(q).unwrap_or(false))
                                                .expect("couldn't find a graphical queue family");

    let device_ext = vulkano::device::DeviceExtensions {
        khr_swapchain: true,
    };
    let (device, queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
                                                        &device_ext, &[], [(queue, 0.5)].iter().cloned())
                                                                .expect("failed to create device");
    let queue = queues.into_iter().next().unwrap();

    let (swapchain, images) = {
        let caps = surface.get_capabilities(&physical).expect("failed to get surface capabilities");

        let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
        let present = caps.present_modes[0];
        let usage = caps.supported_usage_flags;

        vulkano::swapchain::Swapchain::new(&device, &surface, 3,
                                           vulkano::format::B8G8R8A8Srgb, dimensions, 1,
                                           &usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
                                           vulkano::swapchain::CompositeAlpha::Opaque,
                                           present, true).expect("failed to create swapchain")
    };

    let cb_pool = vulkano::command_buffer::CommandBufferPool::new(&device, &queue.family())
                                                  .expect("failed to create command buffer pool");

    let vertex_buffer = vulkano::buffer::Buffer::<[Vertex], _>
                               ::array(&device, 4, &vulkano::buffer::Usage::all(),
                                       vulkano::memory::HostVisible, &queue)
                                       .expect("failed to create buffer");

    struct Vertex { position: [f32; 2] }
    impl_vertex!(Vertex, position);

    // The buffer that we created contains uninitialized data.
    // In order to fill it with data, we have to *map* it.
    {
        // The `try_write` function would return `None` if the buffer was in use by the GPU. This
        // obviously can't happen here, since we haven't ask the GPU to do anything yet.
        let mut mapping = vertex_buffer.try_write().unwrap();
        mapping[0].position = [-0.5, -0.5];
        mapping[1].position = [-0.5,  0.5];
        mapping[2].position = [ 0.5, -0.5];
        mapping[3].position = [ 0.5,  0.5];
    }

    mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/examples/image_vs.glsl")} }
    let vs = vs::Shader::load(&device).expect("failed to create shader module");
    mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/examples/image_fs.glsl")} }
    let fs = fs::Shader::load(&device).expect("failed to create shader module");

    mod renderpass {
        single_pass_renderpass!{
            attachments: {
                color: {
                    load: Clear,
                    store: Store,
                    format: B8G8R8A8Srgb,
                }
            },
            pass: {
                color: [color],
                depth_stencil: {}
            }
        }
    }

    let renderpass = vulkano::framebuffer::RenderPass::new(&device, renderpass::Layout).unwrap();

    let texture = vulkano::image::Image::<vulkano::image::Type2d, _, _>::new(&device, &vulkano::image::Usage::all(),
                                                  vulkano::memory::DeviceLocal, &queue,
                                                  vulkano::format::R8G8B8A8Unorm, [93, 93], (), 1).unwrap();
    let texture = texture.transition(vulkano::image::Layout::ShaderReadOnlyOptimal, &cb_pool, &queue).unwrap();
    let texture_view = vulkano::image::ImageView::new(&texture).expect("failed to create image view");

    let pixel_buffer = {
        let image = image::load_from_memory_with_format(include_bytes!("image_img.png"),
                                                        image::ImageFormat::PNG).unwrap().to_rgba();
        let image_data = image.into_raw().clone();

        let pixel_buffer = vulkano::buffer::Buffer::<[[u8; 4]], _>
                               ::array(&device, image_data.len(), &vulkano::buffer::Usage::all(),
                                       vulkano::memory::HostVisible, &queue)
                                       .expect("failed to create buffer");

        {
            let mut mapping = pixel_buffer.try_write().unwrap();
            for (o, i) in mapping.iter_mut().zip(image_data.chunks(4)) {
                o[0] = i[0];
                o[1] = i[1];
                o[2] = i[2];
                o[3] = i[3];
            }
        }

        pixel_buffer
    };

    let sampler = vulkano::sampler::Sampler::new(&device, vulkano::sampler::Filter::Linear,
                                                 vulkano::sampler::Filter::Linear, vulkano::sampler::MipmapMode::Nearest,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 vulkano::sampler::SamplerAddressMode::Repeat,
                                                 0.0, 1.0, 0.0, 0.0).unwrap();

    let descriptor_pool = vulkano::descriptor_set::DescriptorPool::new(&device).unwrap();
    let descriptor_set_layout = {
        let desc = vulkano::descriptor_set::RuntimeDescriptorSetDesc {
            descriptors: vec![
                vulkano::descriptor_set::DescriptorDesc {
                    binding: 0,
                    ty: vulkano::descriptor_set::DescriptorType::CombinedImageSampler,
                    array_count: 1,
                    stages: vulkano::descriptor_set::ShaderStages::all_graphics(),
                }
            ]
        };

        vulkano::descriptor_set::DescriptorSetLayout::new(&device, desc).unwrap()
    };

    let pipeline_layout = vulkano::descriptor_set::PipelineLayout::new(&device, vulkano::descriptor_set::RuntimeDesc, vec![descriptor_set_layout.clone()]).unwrap();
    let set = vulkano::descriptor_set::DescriptorSet::new(&descriptor_pool, &descriptor_set_layout,
                                                          vec![(0, vulkano::descriptor_set::DescriptorBind::CombinedImageSampler(sampler.clone(), texture_view.clone(), vulkano::image::Layout::ShaderReadOnlyOptimal))]).unwrap();

    let images = images.into_iter().map(|image| {
        let image = image.transition(vulkano::image::Layout::PresentSrc, &cb_pool, &queue).unwrap();
        vulkano::image::ImageView::new(&image).expect("failed to create image view")
    }).collect::<Vec<_>>();

    let pipeline = {
        let ia = vulkano::pipeline::input_assembly::InputAssembly {
            topology: vulkano::pipeline::input_assembly::PrimitiveTopology::TriangleStrip,
            primitive_restart_enable: false,
        };

        let raster = Default::default();
        let ms = vulkano::pipeline::multisample::Multisample::disabled();
        let blend = vulkano::pipeline::blend::Blend {
            logic_op: None,
            blend_constants: Some([0.0; 4]),
        };

        let viewports = vulkano::pipeline::viewport::ViewportsState::Fixed {
            data: vec![(
                vulkano::pipeline::viewport::Viewport {
                    origin: [0.0, 0.0],
                    dimensions: [1244.0, 699.0],
                    depth_range: 0.0 .. 1.0
                },
                vulkano::pipeline::viewport::Scissor {
                    origin: [0, 0],
                    dimensions: [1244, 699],
                }
            )],
        };

        vulkano::pipeline::GraphicsPipeline::new(&device, vulkano::pipeline::vertex::SingleBufferDefinition::new(),
                                                 &vs.main_entry_point(), &ia, &viewports,
                                                 &raster, &ms, &blend, &fs.main_entry_point(),
                                                 &pipeline_layout, vulkano::framebuffer::Subpass::from(&renderpass, 0).unwrap())
                                                 .unwrap()
    };

    let framebuffers = images.iter().map(|image| {
        vulkano::framebuffer::Framebuffer::new(&renderpass, (1244, 699, 1), (image.clone() as std::sync::Arc<_>,)).unwrap()
    }).collect::<Vec<_>>();

    let command_buffers = framebuffers.iter().map(|framebuffer| {
        vulkano::command_buffer::PrimaryCommandBufferBuilder::new(&cb_pool).unwrap()
            .copy_buffer_to_color_image(&pixel_buffer, &texture)
            //.clear_color_image(&texture, [0.0, 1.0, 0.0, 1.0])
            .draw_inline(&renderpass, &framebuffer, ([0.0, 0.0, 1.0, 1.0],))
            .draw(&pipeline, &vertex_buffer, &vulkano::command_buffer::DynamicState::none(), set.clone())
            .draw_end()
            .build().unwrap()
    }).collect::<Vec<_>>();

    loop {
        let image_num = swapchain.acquire_next_image(1000000).unwrap();
        vulkano::command_buffer::submit(&command_buffers[image_num], &queue).unwrap();
        swapchain.present(&queue, image_num).unwrap();

        for ev in window.poll_events() {
            match ev {
                winit::Event::Closed => break,
                _ => ()
            }
        }
    }
}
<|endoftext|>


<commit_before>//! Client-side Wayland connector
//!
//! ## Overview
//!
//! This crate provides the interfaces and machinnery to safely create
//! client applications for the wayland protocol. It is a rust wrapper
//! around the `libwayland-client.so` C library.
//!
//! The wayland protocol revolves around the creation of various objects
//! and the exchange of messages associated to these objects. The initial
//! object is always the `Display`, that you get at initialization of the
//! connection, exposed by this crate as `Display::connect_to_env()`.
//!
//! ## Protocol and messages handling model
//!
//! The protocol being be-directionnal, you can send and receive messages.
//! Sending messages is done via methods of `Proxy<_>` objects, receiving
//! and handling them is done by providing implementations.
//!
//! ### Proxies
//!
//! Wayland protocol objects are represented in this crate by `Proxy<I>`
//! objects, where `I` is a type representing the interface of the considered
//! object. And object's interface (think "class" in an object-oriented context)
//! defines which messages it can send and receive.
//!
//! These proxies are used to send messages to the server (in the wayland context,
//! these are called "requests"). To do so, you need to import the appropriate
//! extension trait adding these methods. For example, to use a `Proxy<WlSurface>`,
//! you need to import `protocol::wl_surface::RequestsTrait` from this crate.
//! It is also possible to directly use the `Proxy::<I>::send(..)` method, but
//! this should only be done carefully: using it improperly can mess the protocol
//! state and cause protocol errors, which are fatal to the connection (the server
//! will kill you).
//!
//! There is not a 1 to 1 mapping between `Proxy<I>` instances and protocol
//! objects. Rather, you can think of `Proxy<I>` as an `Rc`-like handle to a
//! wayland object. Multiple instances of it can exist referring to the same
//! protocol object.
//!
//! Similarly, the lifetimes of the protocol objects and the `Proxy<I>` are
//! not tighly tied. As protocol objects are created and destroyed by protocol
//! messages, it can happen that an object gets destroyed while one or more
//! `Proxy<I>` still refers to it. In such case, these proxies will be disabled
//! and their `alive()` method will start to return `false`. Trying to send messages
//! with them will also fail.
//!
//! ### Implementations
//!
//! To receive and process messages from the server to you (in wayland context they are
//! called "events"), you need to provide an `Implementation` for each wayland object
//! created in the protocol session. Whenever a new protocol object is created, you will
//! receive a `NewProxy<I>` object. Providing an implementation via its `implement()` method
//! will turn it into a regular `Rroxy<I>` object.
//!
//! **All objects must be implemented**, even if it is an implementation doing nothing.
//! Failure to do so (by dropping the `NewProxy<I>` for example) can cause future fatal
//! errors if the server tries to send an event to this object.
//!
//! An implementation is just a struct implementing the `Implementation<Proxy<I>, I::Events>`
//! trait, where `I` is the interface of the considered object:
//!
//! ```
//! // Example implementation for the wl_surface interface
//! use wayland_client::Proxy;
//! use wayland_client::protocol::wl_surface;
//! use wayland_client::commons::Implementation;
//!
//! struct MyImpl {
//!    // ...
//! }
//!
//! impl Implementation<Proxy<wl_surface::WlSurface>, wl_surface::Events> for MyImpl {
//!     fn receive(&mut self, msg: wl_surface::Events, proxy: Proxy<wl_surface::WlSurface>) {
//!         // process the message...
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! The trait is also automatically implemented for `FnMut(I::Events, Proxy<I>)` closures,
//! so you can use them for simplicity if a full struct would be too cumbersome.
//!
//! ## Event Queues
//!
//! The wayland client machinnery provides the possibility to have one or more event queues
//! handling the processing of received messages. All wayland objects are associated to an
//! event queue, which controls when its events are dispatched.
//!
//! Events received from the server are stored in an internal buffer, and processed (by calling
//! the appropriate implementations) when the associated event queue is dispatched.
//!
//! A default event queue is created at the same time as the initial `Display`, and by default
//! whenever a wayland object is created, it inherits the queue of its parent (the object that sent
//! or receive the message that created the new object). It means that if you only plan to use the
//! default event queue, you don't need to worry about assigning objects to their queues.
//!
//! See the documentation of `EventQueue` for details about dispatching and integrating the event
//! queue into the event loop of your application. See the `Proxy::make_wrapper()` method for
//! details about assigning objects to event queues.
//!
//! ## Dynamic linking with `libwayland-client.so`
//!
//! If you need to gracefully handle the case of a system on which wayland is not installed (by
//! fallbacking to X11 for example), you can do so by activating the `dlopen` cargo feature.
//!
//! When this is done, the library will be loaded a runtime rather than directly linked. And trying
//! to create a `Display` on a system that does not have this library will return a `NoWaylandLib`
//! error.
//!
//! ## Auxiliary libraries
//!
//! Two auxiliary libraries are also available behind cargo features:
//!
//! - the `cursor` feature will try to load `libwayland-cursor.so`, a library helping with loading
//!   system themed cursor textures, to integrate your app in the system theme.
//! - the `egl` feature will try to load `libwayland-egl.so`, a library allowing the creation of
//!   OpenGL surface from wayland surfaces.
//!
//! Both of them will also be loaded at runtime if the `dlopen` feature was provided. See their
//! respective submodules for details about their use.

#![warn(missing_docs)]

#[macro_use]
extern crate bitflags;
extern crate libc;

extern crate wayland_commons;
#[cfg(feature = "native_lib")]
#[macro_use]
extern crate wayland_sys;

mod display;
mod event_queue;
mod proxy;

pub use proxy::{NewProxy, Proxy};
pub use display::Display;
pub use event_queue::{EventQueue, QueueToken, ReadEventsGuard};

#[cfg(feature = "cursor")]
pub mod cursor;

#[cfg(feature = "egl")]
pub mod egl;

/// Re-export of wayland-commons
///
/// Common traits and functions to work with wayland objects
pub mod commons {
    pub use wayland_commons::*;
}

#[cfg(feature = "native_lib")]
/// C-associated types
///
/// Required for plugging wayland-scanner generated protocols
/// or interfacing with C code using wayland objects.
pub mod sys {
    pub use super::generated::c_interfaces as protocol_interfaces;
    pub use wayland_sys::{client, common};
}

/// Generated interfaces for the core wayland protocol
pub mod protocol {
    #[cfg(feature = "native_lib")]
    pub use generated::c_api::*;
}

mod generated {
    #![allow(dead_code, non_camel_case_types, unused_unsafe, unused_variables)]
    #![allow(non_upper_case_globals, non_snake_case, unused_imports)]
    #![allow(missing_docs)]

    #[cfg(feature = "native_lib")]
    pub mod c_interfaces {
        include!(concat!(env!("OUT_DIR"), "/wayland_c_interfaces.rs"));
    }
    #[cfg(feature = "native_lib")]
    pub mod c_api {
        pub(crate) use {NewProxy, Proxy};
        pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup};
        pub(crate) use wayland_sys as sys;
        include!(concat!(env!("OUT_DIR"), "/wayland_c_api.rs"));
    }
}
<commit_msg>Doc typos.<commit_after>//! Client-side Wayland connector
//!
//! ## Overview
//!
//! This crate provides the interfaces and machinery to safely create
//! client applications for the wayland protocol. It is a rust wrapper
//! around the `libwayland-client.so` C library.
//!
//! The wayland protocol revolves around the creation of various objects
//! and the exchange of messages associated to these objects. The initial
//! object is always the `Display`, that you get at initialization of the
//! connection, exposed by this crate as `Display::connect_to_env()`.
//!
//! ## Protocol and messages handling model
//!
//! The protocol being bi-directional, you can send and receive messages.
//! Sending messages is done via methods of `Proxy<_>` objects, receiving
//! and handling them is done by providing implementations.
//!
//! ### Proxies
//!
//! Wayland protocol objects are represented in this crate by `Proxy<I>`
//! objects, where `I` is a type representing the interface of the considered
//! object. And object's interface (think "class" in an object-oriented context)
//! defines which messages it can send and receive.
//!
//! These proxies are used to send messages to the server (in the wayland context,
//! these are called "requests"). To do so, you need to import the appropriate
//! extension trait adding these methods. For example, to use a `Proxy<WlSurface>`,
//! you need to import `protocol::wl_surface::RequestsTrait` from this crate.
//! It is also possible to directly use the `Proxy::<I>::send(..)` method, but
//! this should only be done carefully: using it improperly can mess the protocol
//! state and cause protocol errors, which are fatal to the connection (the server
//! will kill you).
//!
//! There is not a 1 to 1 mapping between `Proxy<I>` instances and protocol
//! objects. Rather, you can think of `Proxy<I>` as an `Rc`-like handle to a
//! wayland object. Multiple instances of it can exist referring to the same
//! protocol object.
//!
//! Similarly, the lifetimes of the protocol objects and the `Proxy<I>` are
//! not tighly tied. As protocol objects are created and destroyed by protocol
//! messages, it can happen that an object gets destroyed while one or more
//! `Proxy<I>` still refers to it. In such case, these proxies will be disabled
//! and their `alive()` method will start to return `false`. Trying to send messages
//! with them will also fail.
//!
//! ### Implementations
//!
//! To receive and process messages from the server to you (in wayland context they are
//! called "events"), you need to provide an `Implementation` for each wayland object
//! created in the protocol session. Whenever a new protocol object is created, you will
//! receive a `NewProxy<I>` object. Providing an implementation via its `implement()` method
//! will turn it into a regular `Proxy<I>` object.
//!
//! **All objects must be implemented**, even if it is an implementation doing nothing.
//! Failure to do so (by dropping the `NewProxy<I>` for example) can cause future fatal
//! errors if the server tries to send an event to this object.
//!
//! An implementation is just a struct implementing the `Implementation<Proxy<I>, I::Events>`
//! trait, where `I` is the interface of the considered object:
//!
//! ```
//! // Example implementation for the wl_surface interface
//! use wayland_client::Proxy;
//! use wayland_client::protocol::wl_surface;
//! use wayland_client::commons::Implementation;
//!
//! struct MyImpl {
//!    // ...
//! }
//!
//! impl Implementation<Proxy<wl_surface::WlSurface>, wl_surface::Events> for MyImpl {
//!     fn receive(&mut self, msg: wl_surface::Events, proxy: Proxy<wl_surface::WlSurface>) {
//!         // process the message...
//!     }
//! }
//! # fn main() {}
//! ```
//!
//! The trait is also automatically implemented for `FnMut(I::Events, Proxy<I>)` closures,
//! so you can use them for simplicity if a full struct would be too cumbersome.
//!
//! ## Event Queues
//!
//! The wayland client machinnery provides the possibility to have one or more event queues
//! handling the processing of received messages. All wayland objects are associated to an
//! event queue, which controls when its events are dispatched.
//!
//! Events received from the server are stored in an internal buffer, and processed (by calling
//! the appropriate implementations) when the associated event queue is dispatched.
//!
//! A default event queue is created at the same time as the initial `Display`, and by default
//! whenever a wayland object is created, it inherits the queue of its parent (the object that sent
//! or receive the message that created the new object). It means that if you only plan to use the
//! default event queue, you don't need to worry about assigning objects to their queues.
//!
//! See the documentation of `EventQueue` for details about dispatching and integrating the event
//! queue into the event loop of your application. See the `Proxy::make_wrapper()` method for
//! details about assigning objects to event queues.
//!
//! ## Dynamic linking with `libwayland-client.so`
//!
//! If you need to gracefully handle the case of a system on which wayland is not installed (by
//! fallbacking to X11 for example), you can do so by activating the `dlopen` cargo feature.
//!
//! When this is done, the library will be loaded a runtime rather than directly linked. And trying
//! to create a `Display` on a system that does not have this library will return a `NoWaylandLib`
//! error.
//!
//! ## Auxiliary libraries
//!
//! Two auxiliary libraries are also available behind cargo features:
//!
//! - the `cursor` feature will try to load `libwayland-cursor.so`, a library helping with loading
//!   system themed cursor textures, to integrate your app in the system theme.
//! - the `egl` feature will try to load `libwayland-egl.so`, a library allowing the creation of
//!   OpenGL surface from wayland surfaces.
//!
//! Both of them will also be loaded at runtime if the `dlopen` feature was provided. See their
//! respective submodules for details about their use.

#![warn(missing_docs)]

#[macro_use]
extern crate bitflags;
extern crate libc;

extern crate wayland_commons;
#[cfg(feature = "native_lib")]
#[macro_use]
extern crate wayland_sys;

mod display;
mod event_queue;
mod proxy;

pub use proxy::{NewProxy, Proxy};
pub use display::Display;
pub use event_queue::{EventQueue, QueueToken, ReadEventsGuard};

#[cfg(feature = "cursor")]
pub mod cursor;

#[cfg(feature = "egl")]
pub mod egl;

/// Re-export of wayland-commons
///
/// Common traits and functions to work with wayland objects
pub mod commons {
    pub use wayland_commons::*;
}

#[cfg(feature = "native_lib")]
/// C-associated types
///
/// Required for plugging wayland-scanner generated protocols
/// or interfacing with C code using wayland objects.
pub mod sys {
    pub use super::generated::c_interfaces as protocol_interfaces;
    pub use wayland_sys::{client, common};
}

/// Generated interfaces for the core wayland protocol
pub mod protocol {
    #[cfg(feature = "native_lib")]
    pub use generated::c_api::*;
}

mod generated {
    #![allow(dead_code, non_camel_case_types, unused_unsafe, unused_variables)]
    #![allow(non_upper_case_globals, non_snake_case, unused_imports)]
    #![allow(missing_docs)]

    #[cfg(feature = "native_lib")]
    pub mod c_interfaces {
        include!(concat!(env!("OUT_DIR"), "/wayland_c_interfaces.rs"));
    }
    #[cfg(feature = "native_lib")]
    pub mod c_api {
        pub(crate) use {NewProxy, Proxy};
        pub(crate) use wayland_commons::{AnonymousObject, Interface, MessageGroup};
        pub(crate) use wayland_sys as sys;
        include!(concat!(env!("OUT_DIR"), "/wayland_c_api.rs"));
    }
}
<|endoftext|>


<commit_before>//! The `CFGPrinter` utility.

use core::fmt::{Display, Formatter, Result, Write};

use crate::flowgraph::{BasicBlock, ControlFlowGraph};
use crate::ir::instructions::BranchInfo;
use crate::ir::Function;

/// A utility for pretty-printing the CFG of a `Function`.
pub struct CFGPrinter<'a> {
    func: &'a Function,
    cfg: ControlFlowGraph,
}

/// A utility for pretty-printing the CFG of a `Function`.
impl<'a> CFGPrinter<'a> {
    /// Create a new CFGPrinter.
    pub fn new(func: &'a Function) -> Self {
        Self {
            func,
            cfg: ControlFlowGraph::with_function(func),
        }
    }

    /// Write the CFG for this function to `w`.
    pub fn write(&self, w: &mut dyn Write) -> Result {
        self.header(w)?;
        self.ebb_nodes(w)?;
        self.cfg_connections(w)?;
        writeln!(w, "}}")
    }

    fn header(&self, w: &mut dyn Write) -> Result {
        writeln!(w, "digraph \"{}\" {{", self.func.name)?;
        if let Some(entry) = self.func.layout.entry_block() {
            writeln!(w, "    {{rank=min; {}}}", entry)?;
        }
        Ok(())
    }

    fn ebb_nodes(&self, w: &mut dyn Write) -> Result {
        for ebb in &self.func.layout {
            write!(w, "    {} [shape=record, label=\"{{{}", ebb, ebb)?;
            // Add all outgoing branch instructions to the label.
            for inst in self.func.layout.ebb_insts(ebb) {
                let idata = &self.func.dfg[inst];
                match idata.analyze_branch(&self.func.dfg.value_lists) {
                    BranchInfo::SingleDest(dest, _) => {
                        write!(w, " | <{}>{} {}", inst, idata.opcode(), dest)?
                    }
                    BranchInfo::Table(table, dest) => {
                        write!(w, " | <{}>{} {}", inst, idata.opcode(), table)?;
                        if let Some(dest) = dest {
                            write!(w, " {}", dest)?
                        }
                    }
                    BranchInfo::NotABranch => {}
                }
            }
            writeln!(w, "}}\"]")?
        }
        Ok(())
    }

    fn cfg_connections(&self, w: &mut dyn Write) -> Result {
        for ebb in &self.func.layout {
            for BasicBlock { ebb: parent, inst } in self.cfg.pred_iter(ebb) {
                writeln!(w, "    {}:{} -> {}", parent, inst, ebb)?;
            }
        }
        Ok(())
    }
}

impl<'a> Display for CFGPrinter<'a> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        self.write(f)
    }
}
<commit_msg>Improve graphviz rendering<commit_after>//! The `CFGPrinter` utility.

use core::fmt::{Display, Formatter, Result, Write};
use std::vec::Vec;

use crate::entity::SecondaryMap;
use crate::flowgraph::{BasicBlock, ControlFlowGraph};
use crate::ir::Function;
use crate::write::{FuncWriter, PlainWriter};

/// A utility for pretty-printing the CFG of a `Function`.
pub struct CFGPrinter<'a> {
    func: &'a Function,
    cfg: ControlFlowGraph,
}

/// A utility for pretty-printing the CFG of a `Function`.
impl<'a> CFGPrinter<'a> {
    /// Create a new CFGPrinter.
    pub fn new(func: &'a Function) -> Self {
        Self {
            func,
            cfg: ControlFlowGraph::with_function(func),
        }
    }

    /// Write the CFG for this function to `w`.
    pub fn write(&self, w: &mut dyn Write) -> Result {
        self.header(w)?;
        self.ebb_nodes(w)?;
        self.cfg_connections(w)?;
        writeln!(w, "}}")
    }

    fn header(&self, w: &mut dyn Write) -> Result {
        writeln!(w, "digraph \"{}\" {{", self.func.name)?;
        if let Some(entry) = self.func.layout.entry_block() {
            writeln!(w, "    {{rank=min; {}}}", entry)?;
        }
        Ok(())
    }

    fn ebb_nodes(&self, w: &mut dyn Write) -> Result {
        let mut aliases = SecondaryMap::<_, Vec<_>>::new();
        for v in self.func.dfg.values() {
            // VADFS returns the immediate target of an alias
            if let Some(k) = self.func.dfg.value_alias_dest_for_serialization(v) {
                aliases[k].push(v);
            }
        }

        for ebb in &self.func.layout {
            write!(w, "    {} [shape=record, label=\"{{", ebb)?;
            crate::write::write_ebb_header(w, self.func, None, ebb, 4)?;
            // Add all outgoing branch instructions to the label.
            for inst in self.func.layout.ebb_insts(ebb) {
                write!(w, " | <{}>", inst)?;
                PlainWriter.write_instruction(w, self.func, &aliases, None, inst, 0)?;
            }
            writeln!(w, "}}\"]")?
        }
        Ok(())
    }

    fn cfg_connections(&self, w: &mut dyn Write) -> Result {
        for ebb in &self.func.layout {
            for BasicBlock { ebb: parent, inst } in self.cfg.pred_iter(ebb) {
                writeln!(w, "    {}:{} -> {}", parent, inst, ebb)?;
            }
        }
        Ok(())
    }
}

impl<'a> Display for CFGPrinter<'a> {
    fn fmt(&self, f: &mut Formatter) -> Result {
        self.write(f)
    }
}
<|endoftext|>