file_name large_stringlengths 4 69 | prefix large_stringlengths 0 26.7k | suffix large_stringlengths 0 24.8k | middle large_stringlengths 0 2.12k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser as CssParser, ParserInput as CssParserInput};
use cssparser::ToCss;
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods};
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::inheritance::Castable; | use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use dom_struct::dom_struct;
use selectors::parser::SelectorList;
use servo_arc::Arc;
use std::mem;
use style::selector_parser::SelectorParser;
use style::shared_lock::{Locked, ToCssWithGuard};
use style::stylesheets::{StyleRule, Origin};
#[dom_struct]
pub struct CSSStyleRule {
cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"]
stylerule: Arc<Locked<StyleRule>>,
style_decl: MutNullableJS<CSSStyleDeclaration>,
}
impl CSSStyleRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>)
-> CSSStyleRule {
CSSStyleRule {
cssrule: CSSRule::new_inherited(parent_stylesheet),
stylerule: stylerule,
style_decl: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
stylerule: Arc<Locked<StyleRule>>) -> Root<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule),
window,
CSSStyleRuleBinding::Wrap)
}
}
impl SpecificCSSRule for CSSStyleRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssrule.shared_lock().read();
self.stylerule.read_with(&guard).to_css_string(&guard).into()
}
}
impl CSSStyleRuleMethods for CSSStyleRule {
// https://drafts.csswg.org/cssom/#dom-cssstylerule-style
fn Style(&self) -> Root<CSSStyleDeclaration> {
self.style_decl.or_init(|| {
let guard = self.cssrule.shared_lock().read();
CSSStyleDeclaration::new(
self.global().as_window(),
CSSStyleOwner::CSSRule(
JS::from_ref(self.upcast()),
self.stylerule.read_with(&guard).block.clone()
),
None,
CSSModificationAccess::ReadWrite
)
})
}
// https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext
fn SelectorText(&self) -> DOMString {
let guard = self.cssrule.shared_lock().read();
let stylerule = self.stylerule.read_with(&guard);
return DOMString::from_string(stylerule.selectors.to_css_string());
}
// https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext
fn SetSelectorText(&self, value: DOMString) {
// It's not clear from the spec if we should use the stylesheet's namespaces.
// https://github.com/w3c/csswg-drafts/issues/1511
let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read();
let parser = SelectorParser {
stylesheet_origin: Origin::Author,
namespaces: &namespaces,
url_data: None,
};
let mut css_parser = CssParserInput::new(&*value);
let mut css_parser = CssParser::new(&mut css_parser);
if let Ok(mut s) = SelectorList::parse(&parser, &mut css_parser) {
// This mirrors what we do in CSSStyleOwner::mutate_associated_block.
let mut guard = self.cssrule.shared_lock().write();
let stylerule = self.stylerule.write_with(&mut guard);
mem::swap(&mut stylerule.selectors, &mut s);
// It seems like we will want to avoid having to invalidate all
// stylesheets eventually!
self.global().as_window().Document().invalidate_stylesheets();
}
}
} | use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; | random_line_split |
cssstylerule.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::{Parser as CssParser, ParserInput as CssParserInput};
use cssparser::ToCss;
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods};
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner};
use dom::cssstylesheet::CSSStyleSheet;
use dom::window::Window;
use dom_struct::dom_struct;
use selectors::parser::SelectorList;
use servo_arc::Arc;
use std::mem;
use style::selector_parser::SelectorParser;
use style::shared_lock::{Locked, ToCssWithGuard};
use style::stylesheets::{StyleRule, Origin};
#[dom_struct]
pub struct CSSStyleRule {
cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"]
stylerule: Arc<Locked<StyleRule>>,
style_decl: MutNullableJS<CSSStyleDeclaration>,
}
impl CSSStyleRule {
fn new_inherited(parent_stylesheet: &CSSStyleSheet, stylerule: Arc<Locked<StyleRule>>)
-> CSSStyleRule {
CSSStyleRule {
cssrule: CSSRule::new_inherited(parent_stylesheet),
stylerule: stylerule,
style_decl: Default::default(),
}
}
#[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
stylerule: Arc<Locked<StyleRule>>) -> Root<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule),
window,
CSSStyleRuleBinding::Wrap)
}
}
impl SpecificCSSRule for CSSStyleRule {
fn ty(&self) -> u16 {
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants;
CSSRuleConstants::STYLE_RULE
}
fn get_css(&self) -> DOMString {
let guard = self.cssrule.shared_lock().read();
self.stylerule.read_with(&guard).to_css_string(&guard).into()
}
}
impl CSSStyleRuleMethods for CSSStyleRule {
// https://drafts.csswg.org/cssom/#dom-cssstylerule-style
fn Style(&self) -> Root<CSSStyleDeclaration> {
self.style_decl.or_init(|| {
let guard = self.cssrule.shared_lock().read();
CSSStyleDeclaration::new(
self.global().as_window(),
CSSStyleOwner::CSSRule(
JS::from_ref(self.upcast()),
self.stylerule.read_with(&guard).block.clone()
),
None,
CSSModificationAccess::ReadWrite
)
})
}
// https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext
fn SelectorText(&self) -> DOMString {
let guard = self.cssrule.shared_lock().read();
let stylerule = self.stylerule.read_with(&guard);
return DOMString::from_string(stylerule.selectors.to_css_string());
}
// https://drafts.csswg.org/cssom/#dom-cssstylerule-selectortext
fn SetSelectorText(&self, value: DOMString) {
// It's not clear from the spec if we should use the stylesheet's namespaces.
// https://github.com/w3c/csswg-drafts/issues/1511
let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read();
let parser = SelectorParser {
stylesheet_origin: Origin::Author,
namespaces: &namespaces,
url_data: None,
};
let mut css_parser = CssParserInput::new(&*value);
let mut css_parser = CssParser::new(&mut css_parser);
if let Ok(mut s) = SelectorList::parse(&parser, &mut css_parser) |
}
}
| {
// This mirrors what we do in CSSStyleOwner::mutate_associated_block.
let mut guard = self.cssrule.shared_lock().write();
let stylerule = self.stylerule.write_with(&mut guard);
mem::swap(&mut stylerule.selectors, &mut s);
// It seems like we will want to avoid having to invalidate all
// stylesheets eventually!
self.global().as_window().Document().invalidate_stylesheets();
} | conditional_block |
mod.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use devtools::http_client;
use devtools::RandomTempPath;
use rpc::ConfirmationsQueue;
use jsonrpc_core::IoHandler;
use jsonrpc_core::reactor::RpcEventLoop;
use rand;
use ServerBuilder;
use Server;
use AuthCodes;
/// Struct representing authcodes
pub struct GuardedAuthCodes {
authcodes: AuthCodes,
/// The path to the mock authcodes
pub path: RandomTempPath,
}
impl Deref for GuardedAuthCodes {
type Target = AuthCodes;
fn deref(&self) -> &Self::Target {
&self.authcodes
}
}
impl DerefMut for GuardedAuthCodes {
fn deref_mut(&mut self) -> &mut AuthCodes {
&mut self.authcodes
}
}
/// Server with event loop
pub struct ServerLoop {
/// Signer Server
pub server: Server, | }
impl Deref for ServerLoop {
type Target = Server;
fn deref(&self) -> &Self::Target {
&self.server
}
}
/// Setup a mock signer for tests
pub fn serve() -> (ServerLoop, usize, GuardedAuthCodes) {
let mut path = RandomTempPath::new();
path.panic_on_drop_failure = false;
let queue = Arc::new(ConfirmationsQueue::default());
let builder = ServerBuilder::new(queue, path.to_path_buf());
let port = 35000 + rand::random::<usize>() % 10000;
let event_loop = RpcEventLoop::spawn();
let handler = event_loop.handler(Arc::new(IoHandler::default().into()));
let server = builder.start(format!("127.0.0.1:{}", port).parse().unwrap(), handler).unwrap();
let res = ServerLoop {
server: server,
event_loop: event_loop,
};
(res, port, GuardedAuthCodes {
authcodes: AuthCodes::from_file(&path).unwrap(),
path: path,
})
}
/// Test a single request to running server
pub fn request(server: ServerLoop, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use util::Hashable;
use devtools::http_client;
use super::{serve, request};
#[test]
fn should_reject_invalid_host() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET / HTTP/1.1\r\n\
Host: test:8180\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
assert!(response.body.contains("URL Blocked"));
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_home_parity_host() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET http://home.parity/ HTTP/1.1\r\n\
Host: home.parity\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_serve_styles_even_on_disallowed_domain() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET /styles.css HTTP/1.1\r\n\
Host: test:8180\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_return_200_ok_for_connect_requests() {
// given
let server = serve().0;
// when
let response = request(server,
"\
CONNECT home.parity:8080 HTTP/1.1\r\n\
Host: home.parity\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
}
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: wrong\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_if_authorization_is_correct() {
// given
let (server, port, mut authcodes) = serve();
let code = authcodes.generate_new().unwrap().replace("-", "");
authcodes.to_file(&authcodes.path).unwrap();
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: {:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
// then
assert_eq!(response.status, "HTTP/1.1 101 Switching Protocols".to_owned());
}
#[test]
fn should_allow_initial_connection_but_only_once() {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
let response2 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
// then
assert_eq!(response1.status, "HTTP/1.1 101 Switching Protocols".to_owned());
assert_eq!(response2.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
http_client::assert_security_headers_present(&response2.headers, None);
}
} | /// RPC Event Loop
pub event_loop: RpcEventLoop, | random_line_split |
mod.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use devtools::http_client;
use devtools::RandomTempPath;
use rpc::ConfirmationsQueue;
use jsonrpc_core::IoHandler;
use jsonrpc_core::reactor::RpcEventLoop;
use rand;
use ServerBuilder;
use Server;
use AuthCodes;
/// Struct representing authcodes
pub struct GuardedAuthCodes {
authcodes: AuthCodes,
/// The path to the mock authcodes
pub path: RandomTempPath,
}
impl Deref for GuardedAuthCodes {
type Target = AuthCodes;
fn deref(&self) -> &Self::Target {
&self.authcodes
}
}
impl DerefMut for GuardedAuthCodes {
fn | (&mut self) -> &mut AuthCodes {
&mut self.authcodes
}
}
/// Server with event loop
pub struct ServerLoop {
/// Signer Server
pub server: Server,
/// RPC Event Loop
pub event_loop: RpcEventLoop,
}
impl Deref for ServerLoop {
type Target = Server;
fn deref(&self) -> &Self::Target {
&self.server
}
}
/// Setup a mock signer for tests
pub fn serve() -> (ServerLoop, usize, GuardedAuthCodes) {
let mut path = RandomTempPath::new();
path.panic_on_drop_failure = false;
let queue = Arc::new(ConfirmationsQueue::default());
let builder = ServerBuilder::new(queue, path.to_path_buf());
let port = 35000 + rand::random::<usize>() % 10000;
let event_loop = RpcEventLoop::spawn();
let handler = event_loop.handler(Arc::new(IoHandler::default().into()));
let server = builder.start(format!("127.0.0.1:{}", port).parse().unwrap(), handler).unwrap();
let res = ServerLoop {
server: server,
event_loop: event_loop,
};
(res, port, GuardedAuthCodes {
authcodes: AuthCodes::from_file(&path).unwrap(),
path: path,
})
}
/// Test a single request to running server
pub fn request(server: ServerLoop, request: &str) -> http_client::Response {
http_client::request(server.server.addr(), request)
}
#[cfg(test)]
mod testing {
use std::time;
use util::Hashable;
use devtools::http_client;
use super::{serve, request};
#[test]
fn should_reject_invalid_host() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET / HTTP/1.1\r\n\
Host: test:8180\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
assert!(response.body.contains("URL Blocked"));
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_home_parity_host() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET http://home.parity/ HTTP/1.1\r\n\
Host: home.parity\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_serve_styles_even_on_disallowed_domain() {
// given
let server = serve().0;
// when
let response = request(server,
"\
GET /styles.css HTTP/1.1\r\n\
Host: test:8180\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_return_200_ok_for_connect_requests() {
// given
let server = serve().0;
// when
let response = request(server,
"\
CONNECT home.parity:8080 HTTP/1.1\r\n\
Host: home.parity\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
}
#[test]
fn should_block_if_authorization_is_incorrect() {
// given
let (server, port, _) = serve();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Upgrade\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: wrong\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
", port)
);
// then
assert_eq!(response.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
http_client::assert_security_headers_present(&response.headers, None);
}
#[test]
fn should_allow_if_authorization_is_correct() {
// given
let (server, port, mut authcodes) = serve();
let code = authcodes.generate_new().unwrap().replace("-", "");
authcodes.to_file(&authcodes.path).unwrap();
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
// when
let response = request(server,
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol: {:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
// then
assert_eq!(response.status, "HTTP/1.1 101 Switching Protocols".to_owned());
}
#[test]
fn should_allow_initial_connection_but_only_once() {
// given
let (server, port, authcodes) = serve();
let code = "initial";
let timestamp = time::UNIX_EPOCH.elapsed().unwrap().as_secs();
assert!(authcodes.is_empty());
// when
let response1 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
let response2 = http_client::request(server.addr(),
&format!("\
GET / HTTP/1.1\r\n\
Host: 127.0.0.1:{}\r\n\
Connection: Close\r\n\
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n\
Sec-WebSocket-Protocol:{:?}_{}\r\n\
Sec-WebSocket-Version: 13\r\n\
\r\n\
{{}}
",
port,
format!("{}:{}", code, timestamp).sha3(),
timestamp,
)
);
// then
assert_eq!(response1.status, "HTTP/1.1 101 Switching Protocols".to_owned());
assert_eq!(response2.status, "HTTP/1.1 403 FORBIDDEN".to_owned());
http_client::assert_security_headers_present(&response2.headers, None);
}
}
| deref_mut | identifier_name |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
| use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule};
use error_reporting::NullReporter;
use parser::{LengthParsingMode, ParserContext, log_css_error};
use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId};
use properties::{PropertyDeclarationId, LonghandId, ParsedDeclaration};
use properties::LonghandIdSet;
use properties::animated_properties::TransitionProperty;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use std::sync::Arc;
use style_traits::ToCss;
use stylesheets::{CssRuleType, Stylesheet, VendorPrefix};
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}%", self.0 * 100.0)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = try!(input.expect_percentage());
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Debug, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.selector.percentages().iter();
try!(iter.next().unwrap().to_css(dest));
for percentage in iter {
try!(write!(dest, ", "));
try!(percentage.to_css(dest));
}
try!(dest.write_str(" { "));
try!(self.block.read_with(guard).to_css(dest));
try!(dest.write_str(" }"));
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse(css: &str, parent_stylesheet: &Stylesheet)
-> Result<Arc<Locked<Self>>, ()> {
let error_reporter = NullReporter;
let context = ParserContext::new(parent_stylesheet.origin,
&parent_stylesheet.url_data,
&error_reporter,
Some(CssRuleType::Keyframe),
LengthParsingMode::Default,
parent_stylesheet.quirks_mode);
let mut input = Parser::new(css);
let mut rule_parser = KeyframeListParser {
context: &context,
shared_lock: &parent_stylesheet.shared_lock,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let &(ref declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<TransitionProperty>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<TransitionProperty> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for &(ref declaration, importance) in block.declarations().iter() {
assert!(!importance.important());
if let Some(property) = TransitionProperty::from_declaration(declaration) {
if!seen.has_transition_property_bit(&property) {
seen.set_transition_property_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserContext<'a>,
shared_lock: &'a SharedRwLock,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock)
-> Vec<Arc<Locked<Keyframe>>> {
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
shared_lock: shared_lock,
}).filter_map(Result::ok).collect()
}
enum Void {}
impl<'a> AtRuleParser for KeyframeListParser<'a> {
type Prelude = Void;
type AtRule = Arc<Locked<Keyframe>>;
}
impl<'a> QualifiedRuleParser for KeyframeListParser<'a> {
type Prelude = KeyframeSelector;
type QualifiedRule = Arc<Locked<Keyframe>>;
fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> {
let start = input.position();
match KeyframeSelector::parse(input) {
Ok(sel) => Ok(sel),
Err(()) => {
let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start));
log_css_error(input, start, &message, self.context);
Err(())
}
}
}
fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser)
-> Result<Self::QualifiedRule, ()> {
let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe));
let parser = KeyframeDeclarationParser {
context: &context,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(parsed) => parsed.expand_push_into(&mut block, Importance::Normal),
Err(range) => {
let pos = range.start;
let message = format!("Unsupported keyframe property declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, &context);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude,
block: Arc::new(self.shared_lock.wrap(block)),
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> {
type Prelude = ();
type AtRule = ParsedDeclaration;
}
impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> {
type Declaration = ParsedDeclaration;
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<ParsedDeclaration, ()> {
let id = try!(PropertyId::parse(name.into()));
match ParsedDeclaration::parse(id, self.context, input) {
Ok(parsed) => {
// In case there is still unparsed text in the declaration, we should roll back.
if!input.is_exhausted() {
Err(())
} else {
Ok(parsed)
}
}
Err(_) => Err(())
}
}
} | random_line_split | |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule};
use error_reporting::NullReporter;
use parser::{LengthParsingMode, ParserContext, log_css_error};
use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId};
use properties::{PropertyDeclarationId, LonghandId, ParsedDeclaration};
use properties::LonghandIdSet;
use properties::animated_properties::TransitionProperty;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use std::sync::Arc;
use style_traits::ToCss;
use stylesheets::{CssRuleType, Stylesheet, VendorPrefix};
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}%", self.0 * 100.0)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = try!(input.expect_percentage());
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Debug, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.selector.percentages().iter();
try!(iter.next().unwrap().to_css(dest));
for percentage in iter {
try!(write!(dest, ", "));
try!(percentage.to_css(dest));
}
try!(dest.write_str(" { "));
try!(self.block.read_with(guard).to_css(dest));
try!(dest.write_str(" }"));
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse(css: &str, parent_stylesheet: &Stylesheet)
-> Result<Arc<Locked<Self>>, ()> {
let error_reporter = NullReporter;
let context = ParserContext::new(parent_stylesheet.origin,
&parent_stylesheet.url_data,
&error_reporter,
Some(CssRuleType::Keyframe),
LengthParsingMode::Default,
parent_stylesheet.quirks_mode);
let mut input = Parser::new(css);
let mut rule_parser = KeyframeListParser {
context: &context,
shared_lock: &parent_stylesheet.shared_lock,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let &(ref declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<TransitionProperty>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<TransitionProperty> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for &(ref declaration, importance) in block.declarations().iter() {
assert!(!importance.important());
if let Some(property) = TransitionProperty::from_declaration(declaration) {
if!seen.has_transition_property_bit(&property) {
seen.set_transition_property_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserContext<'a>,
shared_lock: &'a SharedRwLock,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock)
-> Vec<Arc<Locked<Keyframe>>> {
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
shared_lock: shared_lock,
}).filter_map(Result::ok).collect()
}
enum Void {}
impl<'a> AtRuleParser for KeyframeListParser<'a> {
type Prelude = Void;
type AtRule = Arc<Locked<Keyframe>>;
}
impl<'a> QualifiedRuleParser for KeyframeListParser<'a> {
type Prelude = KeyframeSelector;
type QualifiedRule = Arc<Locked<Keyframe>>;
fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> {
let start = input.position();
match KeyframeSelector::parse(input) {
Ok(sel) => Ok(sel),
Err(()) => |
}
}
fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser)
-> Result<Self::QualifiedRule, ()> {
let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe));
let parser = KeyframeDeclarationParser {
context: &context,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(parsed) => parsed.expand_push_into(&mut block, Importance::Normal),
Err(range) => {
let pos = range.start;
let message = format!("Unsupported keyframe property declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, &context);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude,
block: Arc::new(self.shared_lock.wrap(block)),
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> {
type Prelude = ();
type AtRule = ParsedDeclaration;
}
impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> {
type Declaration = ParsedDeclaration;
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<ParsedDeclaration, ()> {
let id = try!(PropertyId::parse(name.into()));
match ParsedDeclaration::parse(id, self.context, input) {
Ok(parsed) => {
// In case there is still unparsed text in the declaration, we should roll back.
if!input.is_exhausted() {
Err(())
} else {
Ok(parsed)
}
}
Err(_) => Err(())
}
}
}
| {
let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start));
log_css_error(input, start, &message, self.context);
Err(())
} | conditional_block |
keyframes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
#![deny(missing_docs)]
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser};
use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule};
use error_reporting::NullReporter;
use parser::{LengthParsingMode, ParserContext, log_css_error};
use properties::{Importance, PropertyDeclaration, PropertyDeclarationBlock, PropertyId};
use properties::{PropertyDeclarationId, LonghandId, ParsedDeclaration};
use properties::LonghandIdSet;
use properties::animated_properties::TransitionProperty;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use shared_lock::{SharedRwLock, SharedRwLockReadGuard, Locked, ToCssWithGuard};
use std::fmt;
use std::sync::Arc;
use style_traits::ToCss;
use stylesheets::{CssRuleType, Stylesheet, VendorPrefix};
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage { }
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
write!(dest, "{}%", self.0 * 100.0)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse(input: &mut Parser) -> Result<KeyframePercentage, ()> {
let percentage = if input.try(|input| input.expect_ident_matching("from")).is_ok() {
KeyframePercentage::new(0.)
} else if input.try(|input| input.expect_ident_matching("to")).is_ok() {
KeyframePercentage::new(1.)
} else {
let percentage = try!(input.expect_percentage());
if percentage >= 0. && percentage <= 1. {
KeyframePercentage::new(percentage)
} else {
return Err(());
}
};
Ok(percentage)
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[derive(Debug, PartialEq)]
pub struct KeyframeSelector(Vec<KeyframePercentage>);
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse(input: &mut Parser) -> Result<Self, ()> {
input.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
}
impl ToCssWithGuard for Keyframe {
fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result
where W: fmt::Write {
let mut iter = self.selector.percentages().iter();
try!(iter.next().unwrap().to_css(dest));
for percentage in iter {
try!(write!(dest, ", "));
try!(percentage.to_css(dest));
}
try!(dest.write_str(" { "));
try!(self.block.read_with(guard).to_css(dest));
try!(dest.write_str(" }"));
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse(css: &str, parent_stylesheet: &Stylesheet)
-> Result<Arc<Locked<Self>>, ()> {
let error_reporter = NullReporter;
let context = ParserContext::new(parent_stylesheet.origin,
&parent_stylesheet.url_data,
&error_reporter,
Some(CssRuleType::Keyframe),
LengthParsingMode::Default,
parent_stylesheet.quirks_mode);
let mut input = Parser::new(css);
let mut rule_parser = KeyframeListParser {
context: &context,
shared_lock: &parent_stylesheet.shared_lock,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(feature = "servo", ignore_heap_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct | {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => {
block.read_with(guard).declarations().iter().any(|&(ref prop_decl, _)| {
match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}
})
}
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(&self, guard: &SharedRwLockReadGuard)
-> Option<SpecifiedTimingFunction> {
if!self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let &(ref declaration, _) =
guard.get(PropertyDeclarationId::Longhand(LonghandId::AnimationTimingFunction)).unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: Vec<TransitionProperty>,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(keyframes: &[Arc<Locked<Keyframe>>], guard: &SharedRwLockReadGuard)
-> Vec<TransitionProperty> {
let mut ret = vec![];
let mut seen = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
for &(ref declaration, importance) in block.declarations().iter() {
assert!(!importance.important());
if let Some(property) = TransitionProperty::from_declaration(declaration) {
if!seen.has_transition_property_bit(&property) {
seen.set_transition_property_bit(&property);
ret.push(property);
}
}
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard)
-> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: vec![],
vendor_prefix: vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(*percentage, KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
}, guard));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0!= 0. {
result.steps.insert(0, KeyframesStep::new(KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard));
}
if result.steps.last().unwrap().start_percentage.0!= 1. {
result.steps.push(KeyframesStep::new(KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserContext<'a>,
shared_lock: &'a SharedRwLock,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list(context: &ParserContext, input: &mut Parser, shared_lock: &SharedRwLock)
-> Vec<Arc<Locked<Keyframe>>> {
RuleListParser::new_for_nested_rule(input, KeyframeListParser {
context: context,
shared_lock: shared_lock,
}).filter_map(Result::ok).collect()
}
enum Void {}
impl<'a> AtRuleParser for KeyframeListParser<'a> {
type Prelude = Void;
type AtRule = Arc<Locked<Keyframe>>;
}
impl<'a> QualifiedRuleParser for KeyframeListParser<'a> {
type Prelude = KeyframeSelector;
type QualifiedRule = Arc<Locked<Keyframe>>;
fn parse_prelude(&mut self, input: &mut Parser) -> Result<Self::Prelude, ()> {
let start = input.position();
match KeyframeSelector::parse(input) {
Ok(sel) => Ok(sel),
Err(()) => {
let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start));
log_css_error(input, start, &message, self.context);
Err(())
}
}
}
fn parse_block(&mut self, prelude: Self::Prelude, input: &mut Parser)
-> Result<Self::QualifiedRule, ()> {
let context = ParserContext::new_with_rule_type(self.context, Some(CssRuleType::Keyframe));
let parser = KeyframeDeclarationParser {
context: &context,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(parsed) => parsed.expand_push_into(&mut block, Importance::Normal),
Err(range) => {
let pos = range.start;
let message = format!("Unsupported keyframe property declaration: '{}'",
iter.input.slice(range));
log_css_error(iter.input, pos, &*message, &context);
}
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector: prelude,
block: Arc::new(self.shared_lock.wrap(block)),
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
}
/// Default methods reject all at rules.
impl<'a, 'b> AtRuleParser for KeyframeDeclarationParser<'a, 'b> {
type Prelude = ();
type AtRule = ParsedDeclaration;
}
impl<'a, 'b> DeclarationParser for KeyframeDeclarationParser<'a, 'b> {
type Declaration = ParsedDeclaration;
fn parse_value(&mut self, name: &str, input: &mut Parser) -> Result<ParsedDeclaration, ()> {
let id = try!(PropertyId::parse(name.into()));
match ParsedDeclaration::parse(id, self.context, input) {
Ok(parsed) => {
// In case there is still unparsed text in the declaration, we should roll back.
if!input.is_exhausted() {
Err(())
} else {
Ok(parsed)
}
}
Err(_) => Err(())
}
}
}
| KeyframesStep | identifier_name |
mod.rs |
extern crate rand;
extern crate std;
use self::rand::Rng;
use std::fmt;
#[derive(Clone,Debug)]
pub struct Vector2D
{
pub x: f64,
pub y: f64
}
impl Vector2D
{
pub fn len(&self) -> f64
{
f64::sqrt(self.x*self.x + self.y*self.y)
}
pub fn normal(&self) -> Vector2D
{
Vector2D { x:-self.y, y:self.x }
}
pub fn normalized(&self) -> Vector2D
{
let mut v = self.clone();
v.normalize();
v
}
pub fn normalize(&mut self)
{
let l = self.len();
self.x /= l;
self.y /= l;
}
pub fn scale(&mut self, s: f64)
{
self.x *= s;
self.y *= s;
}
pub fn dot(a: &Vector2D, b: &Vector2D) -> f64
{
a.x*b.x + a.y*b.y
}
pub fn det(a: &Vector2D, b: &Vector2D) -> f64
{
a.x*b.y - a.y*b.x
}
pub fn sub(a: &Vector2D, b: &Vector2D) -> Vector2D
{
Vector2D{ x: a.x - b.x, y: a.y - b.y }
}
}
/*
impl std::ops::Add for Vector2D
{
type Output = Vector2D;
fn add(mut self, _rhs: Vector2D) -> Vector2D {
self.x += _rhs.x;
self.y += _rhs.y;
self
}
} */
impl rand::Rand for Vector2D
{
fn | <R: Rng>(rng: &mut R) -> Vector2D
{
Vector2D{ x: rng.gen::<f64>(), y: rng.gen::<f64>() }
}
}
impl std::fmt::Display for Vector2D
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
| rand | identifier_name |
mod.rs | extern crate rand;
extern crate std;
use self::rand::Rng;
use std::fmt;
#[derive(Clone,Debug)]
pub struct Vector2D
{
pub x: f64,
pub y: f64
}
impl Vector2D
{
pub fn len(&self) -> f64
{
f64::sqrt(self.x*self.x + self.y*self.y)
}
pub fn normal(&self) -> Vector2D
{ | }
pub fn normalized(&self) -> Vector2D
{
let mut v = self.clone();
v.normalize();
v
}
pub fn normalize(&mut self)
{
let l = self.len();
self.x /= l;
self.y /= l;
}
pub fn scale(&mut self, s: f64)
{
self.x *= s;
self.y *= s;
}
pub fn dot(a: &Vector2D, b: &Vector2D) -> f64
{
a.x*b.x + a.y*b.y
}
pub fn det(a: &Vector2D, b: &Vector2D) -> f64
{
a.x*b.y - a.y*b.x
}
pub fn sub(a: &Vector2D, b: &Vector2D) -> Vector2D
{
Vector2D{ x: a.x - b.x, y: a.y - b.y }
}
}
/*
impl std::ops::Add for Vector2D
{
type Output = Vector2D;
fn add(mut self, _rhs: Vector2D) -> Vector2D {
self.x += _rhs.x;
self.y += _rhs.y;
self
}
} */
impl rand::Rand for Vector2D
{
fn rand<R: Rng>(rng: &mut R) -> Vector2D
{
Vector2D{ x: rng.gen::<f64>(), y: rng.gen::<f64>() }
}
}
impl std::fmt::Display for Vector2D
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
} | Vector2D { x:-self.y, y:self.x } | random_line_split |
generic-impl-less-params-with-defaults.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(default_type_params)]
struct Foo<A, B, C = (A, B)>;
impl<A, B, C = (A, B)> Foo<A, B, C> {
fn new() -> Foo<A, B, C> {Foo}
}
fn main() | {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected at least 2, found 1
} | identifier_body | |
generic-impl-less-params-with-defaults.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(default_type_params)]
struct | <A, B, C = (A, B)>;
impl<A, B, C = (A, B)> Foo<A, B, C> {
fn new() -> Foo<A, B, C> {Foo}
}
fn main() {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected at least 2, found 1
}
| Foo | identifier_name |
generic-impl-less-params-with-defaults.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | struct Foo<A, B, C = (A, B)>;
impl<A, B, C = (A, B)> Foo<A, B, C> {
fn new() -> Foo<A, B, C> {Foo}
}
fn main() {
Foo::<int>::new();
//~^ ERROR the impl referenced by this path needs at least 2 type parameters,
// but 1 was supplied
//~^^^ ERROR not enough type parameters provided: expected at least 2, found 1
} | // except according to those terms.
#![feature(default_type_params)]
| random_line_split |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use futures::stream::{self, StreamExt};
use maplit::btreeset;
use serde_derive::Serialize;
use source_control::types as thrift;
use crate::args::commit_id::{
add_multiple_commit_id_args, add_scheme_args, get_commit_ids, get_request_schemes, get_schemes,
map_commit_id, map_commit_ids, resolve_commit_ids,
};
use crate::args::pushvars::{add_pushvar_args, get_pushvars};
use crate::args::repo::{add_repo_args, get_repo_specifier};
use crate::args::service_id::{add_service_id_args, get_service_id};
use crate::connection::Connection;
use crate::lib::commit_id::render_commit_id;
use crate::render::{Render, RenderStream};
pub(super) const NAME: &str = "land-stack";
const ARG_NAME: &str = "BOOKMARK_NAME";
pub(super) fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
let cmd = SubCommand::with_name(NAME)
.about("Land a stack of commits")
.long_about(concat!(
"Land a stack of commits\n\n",
"Provide two commits: the first is the head of a stack, and the second is ",
"public commit the stack is based on. The stack of commits between these ",
"two commits will be landed onto the named bookmark via pushrebase.",
))
.setting(AppSettings::ColoredHelp);
let cmd = add_repo_args(cmd);
let cmd = add_scheme_args(cmd);
let cmd = add_multiple_commit_id_args(cmd);
let cmd = add_service_id_args(cmd);
let cmd = add_pushvar_args(cmd);
cmd.arg(
Arg::with_name(ARG_NAME)
.short("n")
.long("name")
.takes_value(true)
.help("Name of the bookmark to land to")
.required(true),
)
}
#[derive(Serialize)]
struct PushrebaseRebasedCommit {
old_bonsai_id: String,
new_ids: BTreeMap<String, String>,
}
#[derive(Serialize)]
struct PushrebaseOutcomeOutput {
bookmark: String,
head: BTreeMap<String, String>,
rebased_commits: Vec<PushrebaseRebasedCommit>,
}
impl Render for PushrebaseOutcomeOutput {
fn render(&self, matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
let schemes = get_schemes(matches);
write!(w, "{} updated to", self.bookmark)?;
render_commit_id(
Some(("", " ")),
"\n",
&self.bookmark,
&self.head,
&schemes,
w,
)?;
write!(w, "\n")?;
for rebase in self.rebased_commits.iter() {
write!(w, "{} => ", rebase.old_bonsai_id)?;
render_commit_id(None, ", ", "new commit", &rebase.new_ids, &schemes, w)?;
write!(w, "\n")?;
}
Ok(())
}
fn render_json(&self, _matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
Ok(serde_json::to_writer(w, self)?)
}
}
pub(super) async fn run(matches: &ArgMatches<'_>, connection: Connection) -> Result<RenderStream> {
let repo = get_repo_specifier(matches).expect("repository is required"); | let bookmark: String = matches.value_of(ARG_NAME).expect("name is required").into();
let service_identity = get_service_id(matches).map(String::from);
let pushvars = get_pushvars(&matches)?;
let (head, base) = match ids.as_slice() {
[head_id, base_id] => (head_id.clone(), base_id.clone()),
_ => bail!("expected 1 or 2 commit_ids (got {})", ids.len()),
};
let params = thrift::RepoLandStackParams {
bookmark: bookmark.clone(),
head,
base,
identity_schemes: get_request_schemes(&matches),
old_identity_schemes: Some(btreeset! { thrift::CommitIdentityScheme::BONSAI }),
service_identity,
pushvars,
..Default::default()
};
let response = connection.repo_land_stack(&repo, ¶ms).await?;
let head = map_commit_ids(response.pushrebase_outcome.head.values());
let mut rebased_commits = response
.pushrebase_outcome
.rebased_commits
.into_iter()
.map(|rebase| {
let (_, old_bonsai_id) = map_commit_id(
rebase
.old_ids
.get(&thrift::CommitIdentityScheme::BONSAI)
.ok_or_else(|| anyhow!("bonsai id missing from response"))?,
)
.ok_or_else(|| anyhow!("bonsai id should be mappable"))?;
let new_ids = map_commit_ids(rebase.new_ids.values());
Ok(PushrebaseRebasedCommit {
old_bonsai_id,
new_ids,
})
})
.collect::<Result<Vec<_>>>()?;
rebased_commits.sort_unstable_by(|a, b| a.old_bonsai_id.cmp(&b.old_bonsai_id));
let output = Box::new(PushrebaseOutcomeOutput {
bookmark,
head,
rebased_commits,
});
Ok(stream::once(async move { Ok(output as Box<dyn Render>) }).boxed())
} | let commit_ids = get_commit_ids(matches)?;
if commit_ids.len() != 2 {
bail!("expected 2 commit_ids (got {})", commit_ids.len())
}
let ids = resolve_commit_ids(&connection, &repo, &commit_ids).await?; | random_line_split |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use futures::stream::{self, StreamExt};
use maplit::btreeset;
use serde_derive::Serialize;
use source_control::types as thrift;
use crate::args::commit_id::{
add_multiple_commit_id_args, add_scheme_args, get_commit_ids, get_request_schemes, get_schemes,
map_commit_id, map_commit_ids, resolve_commit_ids,
};
use crate::args::pushvars::{add_pushvar_args, get_pushvars};
use crate::args::repo::{add_repo_args, get_repo_specifier};
use crate::args::service_id::{add_service_id_args, get_service_id};
use crate::connection::Connection;
use crate::lib::commit_id::render_commit_id;
use crate::render::{Render, RenderStream};
pub(super) const NAME: &str = "land-stack";
const ARG_NAME: &str = "BOOKMARK_NAME";
pub(super) fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
let cmd = SubCommand::with_name(NAME)
.about("Land a stack of commits")
.long_about(concat!(
"Land a stack of commits\n\n",
"Provide two commits: the first is the head of a stack, and the second is ",
"public commit the stack is based on. The stack of commits between these ",
"two commits will be landed onto the named bookmark via pushrebase.",
))
.setting(AppSettings::ColoredHelp);
let cmd = add_repo_args(cmd);
let cmd = add_scheme_args(cmd);
let cmd = add_multiple_commit_id_args(cmd);
let cmd = add_service_id_args(cmd);
let cmd = add_pushvar_args(cmd);
cmd.arg(
Arg::with_name(ARG_NAME)
.short("n")
.long("name")
.takes_value(true)
.help("Name of the bookmark to land to")
.required(true),
)
}
#[derive(Serialize)]
struct PushrebaseRebasedCommit {
old_bonsai_id: String,
new_ids: BTreeMap<String, String>,
}
#[derive(Serialize)]
struct PushrebaseOutcomeOutput {
bookmark: String,
head: BTreeMap<String, String>,
rebased_commits: Vec<PushrebaseRebasedCommit>,
}
impl Render for PushrebaseOutcomeOutput {
fn render(&self, matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
let schemes = get_schemes(matches);
write!(w, "{} updated to", self.bookmark)?;
render_commit_id(
Some(("", " ")),
"\n",
&self.bookmark,
&self.head,
&schemes,
w,
)?;
write!(w, "\n")?;
for rebase in self.rebased_commits.iter() {
write!(w, "{} => ", rebase.old_bonsai_id)?;
render_commit_id(None, ", ", "new commit", &rebase.new_ids, &schemes, w)?;
write!(w, "\n")?;
}
Ok(())
}
fn render_json(&self, _matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> |
}
pub(super) async fn run(matches: &ArgMatches<'_>, connection: Connection) -> Result<RenderStream> {
let repo = get_repo_specifier(matches).expect("repository is required");
let commit_ids = get_commit_ids(matches)?;
if commit_ids.len()!= 2 {
bail!("expected 2 commit_ids (got {})", commit_ids.len())
}
let ids = resolve_commit_ids(&connection, &repo, &commit_ids).await?;
let bookmark: String = matches.value_of(ARG_NAME).expect("name is required").into();
let service_identity = get_service_id(matches).map(String::from);
let pushvars = get_pushvars(&matches)?;
let (head, base) = match ids.as_slice() {
[head_id, base_id] => (head_id.clone(), base_id.clone()),
_ => bail!("expected 1 or 2 commit_ids (got {})", ids.len()),
};
let params = thrift::RepoLandStackParams {
bookmark: bookmark.clone(),
head,
base,
identity_schemes: get_request_schemes(&matches),
old_identity_schemes: Some(btreeset! { thrift::CommitIdentityScheme::BONSAI }),
service_identity,
pushvars,
..Default::default()
};
let response = connection.repo_land_stack(&repo, ¶ms).await?;
let head = map_commit_ids(response.pushrebase_outcome.head.values());
let mut rebased_commits = response
.pushrebase_outcome
.rebased_commits
.into_iter()
.map(|rebase| {
let (_, old_bonsai_id) = map_commit_id(
rebase
.old_ids
.get(&thrift::CommitIdentityScheme::BONSAI)
.ok_or_else(|| anyhow!("bonsai id missing from response"))?,
)
.ok_or_else(|| anyhow!("bonsai id should be mappable"))?;
let new_ids = map_commit_ids(rebase.new_ids.values());
Ok(PushrebaseRebasedCommit {
old_bonsai_id,
new_ids,
})
})
.collect::<Result<Vec<_>>>()?;
rebased_commits.sort_unstable_by(|a, b| a.old_bonsai_id.cmp(&b.old_bonsai_id));
let output = Box::new(PushrebaseOutcomeOutput {
bookmark,
head,
rebased_commits,
});
Ok(stream::once(async move { Ok(output as Box<dyn Render>) }).boxed())
}
| {
Ok(serde_json::to_writer(w, self)?)
} | identifier_body |
land_stack.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::collections::BTreeMap;
use std::io::Write;
use anyhow::{anyhow, bail, Error, Result};
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use futures::stream::{self, StreamExt};
use maplit::btreeset;
use serde_derive::Serialize;
use source_control::types as thrift;
use crate::args::commit_id::{
add_multiple_commit_id_args, add_scheme_args, get_commit_ids, get_request_schemes, get_schemes,
map_commit_id, map_commit_ids, resolve_commit_ids,
};
use crate::args::pushvars::{add_pushvar_args, get_pushvars};
use crate::args::repo::{add_repo_args, get_repo_specifier};
use crate::args::service_id::{add_service_id_args, get_service_id};
use crate::connection::Connection;
use crate::lib::commit_id::render_commit_id;
use crate::render::{Render, RenderStream};
pub(super) const NAME: &str = "land-stack";
const ARG_NAME: &str = "BOOKMARK_NAME";
pub(super) fn make_subcommand<'a, 'b>() -> App<'a, 'b> {
let cmd = SubCommand::with_name(NAME)
.about("Land a stack of commits")
.long_about(concat!(
"Land a stack of commits\n\n",
"Provide two commits: the first is the head of a stack, and the second is ",
"public commit the stack is based on. The stack of commits between these ",
"two commits will be landed onto the named bookmark via pushrebase.",
))
.setting(AppSettings::ColoredHelp);
let cmd = add_repo_args(cmd);
let cmd = add_scheme_args(cmd);
let cmd = add_multiple_commit_id_args(cmd);
let cmd = add_service_id_args(cmd);
let cmd = add_pushvar_args(cmd);
cmd.arg(
Arg::with_name(ARG_NAME)
.short("n")
.long("name")
.takes_value(true)
.help("Name of the bookmark to land to")
.required(true),
)
}
#[derive(Serialize)]
struct PushrebaseRebasedCommit {
old_bonsai_id: String,
new_ids: BTreeMap<String, String>,
}
#[derive(Serialize)]
struct PushrebaseOutcomeOutput {
bookmark: String,
head: BTreeMap<String, String>,
rebased_commits: Vec<PushrebaseRebasedCommit>,
}
impl Render for PushrebaseOutcomeOutput {
fn render(&self, matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
let schemes = get_schemes(matches);
write!(w, "{} updated to", self.bookmark)?;
render_commit_id(
Some(("", " ")),
"\n",
&self.bookmark,
&self.head,
&schemes,
w,
)?;
write!(w, "\n")?;
for rebase in self.rebased_commits.iter() {
write!(w, "{} => ", rebase.old_bonsai_id)?;
render_commit_id(None, ", ", "new commit", &rebase.new_ids, &schemes, w)?;
write!(w, "\n")?;
}
Ok(())
}
fn | (&self, _matches: &ArgMatches, w: &mut dyn Write) -> Result<(), Error> {
Ok(serde_json::to_writer(w, self)?)
}
}
pub(super) async fn run(matches: &ArgMatches<'_>, connection: Connection) -> Result<RenderStream> {
let repo = get_repo_specifier(matches).expect("repository is required");
let commit_ids = get_commit_ids(matches)?;
if commit_ids.len()!= 2 {
bail!("expected 2 commit_ids (got {})", commit_ids.len())
}
let ids = resolve_commit_ids(&connection, &repo, &commit_ids).await?;
let bookmark: String = matches.value_of(ARG_NAME).expect("name is required").into();
let service_identity = get_service_id(matches).map(String::from);
let pushvars = get_pushvars(&matches)?;
let (head, base) = match ids.as_slice() {
[head_id, base_id] => (head_id.clone(), base_id.clone()),
_ => bail!("expected 1 or 2 commit_ids (got {})", ids.len()),
};
let params = thrift::RepoLandStackParams {
bookmark: bookmark.clone(),
head,
base,
identity_schemes: get_request_schemes(&matches),
old_identity_schemes: Some(btreeset! { thrift::CommitIdentityScheme::BONSAI }),
service_identity,
pushvars,
..Default::default()
};
let response = connection.repo_land_stack(&repo, ¶ms).await?;
let head = map_commit_ids(response.pushrebase_outcome.head.values());
let mut rebased_commits = response
.pushrebase_outcome
.rebased_commits
.into_iter()
.map(|rebase| {
let (_, old_bonsai_id) = map_commit_id(
rebase
.old_ids
.get(&thrift::CommitIdentityScheme::BONSAI)
.ok_or_else(|| anyhow!("bonsai id missing from response"))?,
)
.ok_or_else(|| anyhow!("bonsai id should be mappable"))?;
let new_ids = map_commit_ids(rebase.new_ids.values());
Ok(PushrebaseRebasedCommit {
old_bonsai_id,
new_ids,
})
})
.collect::<Result<Vec<_>>>()?;
rebased_commits.sort_unstable_by(|a, b| a.old_bonsai_id.cmp(&b.old_bonsai_id));
let output = Box::new(PushrebaseOutcomeOutput {
bookmark,
head,
rebased_commits,
});
Ok(stream::once(async move { Ok(output as Box<dyn Render>) }).boxed())
}
| render_json | identifier_name |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod codesend;
mod dpaste_de;
mod glot_io;
mod hastebin;
mod heypasteit;
mod ix_io;
mod lpaste;
mod mibpaste;
mod mozilla;
mod paste_rs;
mod pastebin;
mod sprunge;
mod thepasteb_in;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use super::gist::{self, Gist};
/// Represents a gists' host: a (web) service that hosts gists (code snippets).
/// Examples include gist.github.com.
pub trait Host : Send + Sync {
/// Returns a unique identifier of the gist Host.
fn id(&self) -> &'static str;
/// Returns a user-visible name of the gists' host.
fn name(&self) -> &str;
/// Fetch a current version of the gist if necessary.
///
/// The `mode` parameter specifies in what circumstances the gist will be fetched
/// from the remote host: always, only if new, or when needed.
///
/// If the gist has been downloaded previously,
/// it can also be updated instead (e.g. via pull rather than clone
/// if its a Git repo).
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()>;
/// Return a URL to a HTML page that can display the gist.
/// This may involve talking to the remote host.
fn gist_url(&self, gist: &Gist) -> io::Result<String>;
/// Return a structure with information/metadata about the gist.
///
/// Note: The return type for this method is io::Result<Option<Info>>
/// rather than Option<io::Result<Info>> because the availability of
/// gist metadata may be gist-specific (i.e. some gists have it,
/// some don't).
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
// This default indicates the host cannot fetch any additional gist metadata
// (beyond what may already have been fetched when resolving gist URL).
Ok(gist.info.clone())
}
/// Return a gist corresponding to the given URL.
/// The URL will typically point to a user-facing HTML page of the gist.
///
/// Note: The return type of this method is an Option (Option<io::Result<Gist>>)
/// because the URL may not be recognized as belonging to this host.
fn resolve_url(&self, _: &str) -> Option<io::Result<Gist>> {
// This default indicates that the URL wasn't recognized
// as pointing to any gist hosted by this host.
None
}
}
// TODO: remove this boilerplate impl when `impl Trait` is stable
// and we can use it in create() methods of specific hosts
impl<H: Host +?Sized> Host for Box<H> {
fn id(&self) -> &'static str { (&**self).id() }
fn name(&self) -> &str { (&**self).name() }
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()> {
(&**self).fetch_gist(gist, mode)
}
fn gist_url(&self, gist: &Gist) -> io::Result<String> {
(&**self).gist_url(gist)
}
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
(&**self).gist_info(gist)
}
fn resolve_url(&self, url: &str) -> Option<io::Result<Gist>> {
(&**self).resolve_url(url)
}
}
macro_attr! {
#[derive(Clone, Debug, PartialEq, Eq, Hash,
IterVariants!(FetchModes))]
pub enum FetchMode {
/// Automatically decide how & whether to fetch the gist.
///
/// This is host-specific, but should typically mean that the gist
/// is only updated periodically, or when it's necessary to do so.
Auto,
/// Always fetch the gist from the remote host.
Always,
/// Only fetch the gist if necessary
/// (i.e. when it hasn't been downloaded before).
New,
}
}
impl Default for FetchMode {
#[inline]
fn default() -> Self { FetchMode::Auto }
}
/// Mapping of gist host identifiers to Host structs.
lazy_static! {
static ref BUILTIN_HOSTS: HashMap<&'static str, Arc<Host>> = hashmap!{
github::ID => Arc::new(github::GitHub::new()) as Arc<Host>,
pastebin::ID => Arc::new(pastebin::create()) as Arc<Host>,
lpaste::ID => Arc::new(lpaste::create()) as Arc<Host>,
heypasteit::ID => Arc::new(heypasteit::create()) as Arc<Host>,
bpaste::ID => Arc::new(bpaste::create()) as Arc<Host>,
mozilla::ID => Arc::new(mozilla::create()) as Arc<Host>,
paste_rs::ID => Arc::new(paste_rs::create()) as Arc<Host>,
hastebin::ID => Arc::new(hastebin::Hastebin::new()) as Arc<Host>,
mibpaste::ID => Arc::new(mibpaste::create()) as Arc<Host>,
sprunge::ID => Arc::new(sprunge::Sprunge::new()) as Arc<Host>,
dpaste_de::ID => Arc::new(dpaste_de::create()) as Arc<Host>,
thepasteb_in::ID => Arc::new(thepasteb_in::create()) as Arc<Host>,
ix_io::ID => Arc::new(ix_io::Ix::new()) as Arc<Host>,
codesend::ID => Arc::new(codesend::create()) as Arc<Host>,
glot_io::ID => Arc::new(glot_io::Glot::new()) as Arc<Host>,
};
}
#[cfg(not(test))]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = BUILTIN_HOSTS.clone();
}
#[cfg(test)]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = {
use testing::{INMEMORY_HOST_DEFAULT_ID, InMemoryHost};
let mut hosts = BUILTIN_HOSTS.clone();
hosts.insert(INMEMORY_HOST_DEFAULT_ID, Arc::new(InMemoryHost::new()) as Arc<Host>);
hosts
};
}
pub const DEFAULT_HOST_ID: &'static str = github::ID;
#[cfg(test)]
mod tests {
use testing::INMEMORY_HOST_DEFAULT_ID;
use super::{DEFAULT_HOST_ID, HOSTS};
#[test]
fn | () {
for (&id, host) in &*HOSTS {
assert_eq!(id, host.id());
}
}
#[test]
fn default_host_id() {
assert!(HOSTS.contains_key(DEFAULT_HOST_ID),
"Default host ID `{}` doesn't occur among known gist hosts", DEFAULT_HOST_ID);
}
#[test]
fn inmemory_host_for_testing() {
assert!(HOSTS.contains_key(INMEMORY_HOST_DEFAULT_ID),
"Test in-memory host ID `{}` doesn't occur among known gist hosts", INMEMORY_HOST_DEFAULT_ID);
}
}
| consistent_hosts | identifier_name |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod codesend;
mod dpaste_de;
mod glot_io;
mod hastebin;
mod heypasteit;
mod ix_io;
mod lpaste;
mod mibpaste;
mod mozilla;
mod paste_rs;
mod pastebin;
mod sprunge;
mod thepasteb_in;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use super::gist::{self, Gist};
/// Represents a gists' host: a (web) service that hosts gists (code snippets).
/// Examples include gist.github.com.
pub trait Host : Send + Sync {
/// Returns a unique identifier of the gist Host.
fn id(&self) -> &'static str;
/// Returns a user-visible name of the gists' host.
fn name(&self) -> &str;
/// Fetch a current version of the gist if necessary.
///
/// The `mode` parameter specifies in what circumstances the gist will be fetched
/// from the remote host: always, only if new, or when needed.
///
/// If the gist has been downloaded previously,
/// it can also be updated instead (e.g. via pull rather than clone
/// if its a Git repo).
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()>;
/// Return a URL to a HTML page that can display the gist.
/// This may involve talking to the remote host.
fn gist_url(&self, gist: &Gist) -> io::Result<String>;
/// Return a structure with information/metadata about the gist.
///
/// Note: The return type for this method is io::Result<Option<Info>>
/// rather than Option<io::Result<Info>> because the availability of
/// gist metadata may be gist-specific (i.e. some gists have it,
/// some don't).
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
// This default indicates the host cannot fetch any additional gist metadata
// (beyond what may already have been fetched when resolving gist URL).
Ok(gist.info.clone())
}
/// Return a gist corresponding to the given URL.
/// The URL will typically point to a user-facing HTML page of the gist.
///
/// Note: The return type of this method is an Option (Option<io::Result<Gist>>)
/// because the URL may not be recognized as belonging to this host.
fn resolve_url(&self, _: &str) -> Option<io::Result<Gist>> {
// This default indicates that the URL wasn't recognized
// as pointing to any gist hosted by this host.
None
}
}
// TODO: remove this boilerplate impl when `impl Trait` is stable
// and we can use it in create() methods of specific hosts
impl<H: Host +?Sized> Host for Box<H> {
fn id(&self) -> &'static str { (&**self).id() }
fn name(&self) -> &str |
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()> {
(&**self).fetch_gist(gist, mode)
}
fn gist_url(&self, gist: &Gist) -> io::Result<String> {
(&**self).gist_url(gist)
}
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
(&**self).gist_info(gist)
}
fn resolve_url(&self, url: &str) -> Option<io::Result<Gist>> {
(&**self).resolve_url(url)
}
}
macro_attr! {
#[derive(Clone, Debug, PartialEq, Eq, Hash,
IterVariants!(FetchModes))]
pub enum FetchMode {
/// Automatically decide how & whether to fetch the gist.
///
/// This is host-specific, but should typically mean that the gist
/// is only updated periodically, or when it's necessary to do so.
Auto,
/// Always fetch the gist from the remote host.
Always,
/// Only fetch the gist if necessary
/// (i.e. when it hasn't been downloaded before).
New,
}
}
impl Default for FetchMode {
#[inline]
fn default() -> Self { FetchMode::Auto }
}
/// Mapping of gist host identifiers to Host structs.
lazy_static! {
static ref BUILTIN_HOSTS: HashMap<&'static str, Arc<Host>> = hashmap!{
github::ID => Arc::new(github::GitHub::new()) as Arc<Host>,
pastebin::ID => Arc::new(pastebin::create()) as Arc<Host>,
lpaste::ID => Arc::new(lpaste::create()) as Arc<Host>,
heypasteit::ID => Arc::new(heypasteit::create()) as Arc<Host>,
bpaste::ID => Arc::new(bpaste::create()) as Arc<Host>,
mozilla::ID => Arc::new(mozilla::create()) as Arc<Host>,
paste_rs::ID => Arc::new(paste_rs::create()) as Arc<Host>,
hastebin::ID => Arc::new(hastebin::Hastebin::new()) as Arc<Host>,
mibpaste::ID => Arc::new(mibpaste::create()) as Arc<Host>,
sprunge::ID => Arc::new(sprunge::Sprunge::new()) as Arc<Host>,
dpaste_de::ID => Arc::new(dpaste_de::create()) as Arc<Host>,
thepasteb_in::ID => Arc::new(thepasteb_in::create()) as Arc<Host>,
ix_io::ID => Arc::new(ix_io::Ix::new()) as Arc<Host>,
codesend::ID => Arc::new(codesend::create()) as Arc<Host>,
glot_io::ID => Arc::new(glot_io::Glot::new()) as Arc<Host>,
};
}
#[cfg(not(test))]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = BUILTIN_HOSTS.clone();
}
#[cfg(test)]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = {
use testing::{INMEMORY_HOST_DEFAULT_ID, InMemoryHost};
let mut hosts = BUILTIN_HOSTS.clone();
hosts.insert(INMEMORY_HOST_DEFAULT_ID, Arc::new(InMemoryHost::new()) as Arc<Host>);
hosts
};
}
pub const DEFAULT_HOST_ID: &'static str = github::ID;
#[cfg(test)]
mod tests {
use testing::INMEMORY_HOST_DEFAULT_ID;
use super::{DEFAULT_HOST_ID, HOSTS};
#[test]
fn consistent_hosts() {
for (&id, host) in &*HOSTS {
assert_eq!(id, host.id());
}
}
#[test]
fn default_host_id() {
assert!(HOSTS.contains_key(DEFAULT_HOST_ID),
"Default host ID `{}` doesn't occur among known gist hosts", DEFAULT_HOST_ID);
}
#[test]
fn inmemory_host_for_testing() {
assert!(HOSTS.contains_key(INMEMORY_HOST_DEFAULT_ID),
"Test in-memory host ID `{}` doesn't occur among known gist hosts", INMEMORY_HOST_DEFAULT_ID);
}
}
| { (&**self).name() } | identifier_body |
mod.rs | //! Module defining gist hosts.
//!
//! A host is an external (web) service that hosts gists, and allows users to paste snippets
//! of code to share with others. gist.github.com is a prime example; others are the various
//! "pastebins", including the pastebin.com namesake.
mod common;
mod github;
mod bpaste;
mod codesend;
mod dpaste_de;
mod glot_io;
mod hastebin;
mod heypasteit;
mod ix_io;
mod lpaste;
mod mibpaste;
mod mozilla;
mod paste_rs;
mod pastebin;
mod sprunge;
mod thepasteb_in;
use std::collections::HashMap;
use std::io;
use std::sync::Arc;
use super::gist::{self, Gist};
/// Represents a gists' host: a (web) service that hosts gists (code snippets).
/// Examples include gist.github.com.
pub trait Host : Send + Sync {
/// Returns a unique identifier of the gist Host.
fn id(&self) -> &'static str;
/// Returns a user-visible name of the gists' host.
fn name(&self) -> &str;
/// Fetch a current version of the gist if necessary.
///
/// The `mode` parameter specifies in what circumstances the gist will be fetched
/// from the remote host: always, only if new, or when needed.
///
/// If the gist has been downloaded previously,
/// it can also be updated instead (e.g. via pull rather than clone
/// if its a Git repo).
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()>;
/// Return a URL to a HTML page that can display the gist.
/// This may involve talking to the remote host.
fn gist_url(&self, gist: &Gist) -> io::Result<String>;
/// Return a structure with information/metadata about the gist.
///
/// Note: The return type for this method is io::Result<Option<Info>>
/// rather than Option<io::Result<Info>> because the availability of
/// gist metadata may be gist-specific (i.e. some gists have it,
/// some don't).
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
// This default indicates the host cannot fetch any additional gist metadata
// (beyond what may already have been fetched when resolving gist URL).
Ok(gist.info.clone())
}
/// Return a gist corresponding to the given URL.
/// The URL will typically point to a user-facing HTML page of the gist.
///
/// Note: The return type of this method is an Option (Option<io::Result<Gist>>)
/// because the URL may not be recognized as belonging to this host.
fn resolve_url(&self, _: &str) -> Option<io::Result<Gist>> {
// This default indicates that the URL wasn't recognized
// as pointing to any gist hosted by this host.
None
}
}
// TODO: remove this boilerplate impl when `impl Trait` is stable
// and we can use it in create() methods of specific hosts
impl<H: Host +?Sized> Host for Box<H> {
fn id(&self) -> &'static str { (&**self).id() }
fn name(&self) -> &str { (&**self).name() }
fn fetch_gist(&self, gist: &Gist, mode: FetchMode) -> io::Result<()> {
(&**self).fetch_gist(gist, mode)
}
fn gist_url(&self, gist: &Gist) -> io::Result<String> {
(&**self).gist_url(gist)
}
fn gist_info(&self, gist: &Gist) -> io::Result<Option<gist::Info>> {
(&**self).gist_info(gist)
}
fn resolve_url(&self, url: &str) -> Option<io::Result<Gist>> {
(&**self).resolve_url(url)
}
}
macro_attr! {
#[derive(Clone, Debug, PartialEq, Eq, Hash,
IterVariants!(FetchModes))]
pub enum FetchMode {
/// Automatically decide how & whether to fetch the gist.
///
/// This is host-specific, but should typically mean that the gist
/// is only updated periodically, or when it's necessary to do so.
Auto,
/// Always fetch the gist from the remote host.
Always,
/// Only fetch the gist if necessary
/// (i.e. when it hasn't been downloaded before).
New,
}
}
impl Default for FetchMode {
#[inline]
fn default() -> Self { FetchMode::Auto }
}
/// Mapping of gist host identifiers to Host structs.
lazy_static! {
static ref BUILTIN_HOSTS: HashMap<&'static str, Arc<Host>> = hashmap!{
github::ID => Arc::new(github::GitHub::new()) as Arc<Host>,
pastebin::ID => Arc::new(pastebin::create()) as Arc<Host>,
lpaste::ID => Arc::new(lpaste::create()) as Arc<Host>, | mozilla::ID => Arc::new(mozilla::create()) as Arc<Host>,
paste_rs::ID => Arc::new(paste_rs::create()) as Arc<Host>,
hastebin::ID => Arc::new(hastebin::Hastebin::new()) as Arc<Host>,
mibpaste::ID => Arc::new(mibpaste::create()) as Arc<Host>,
sprunge::ID => Arc::new(sprunge::Sprunge::new()) as Arc<Host>,
dpaste_de::ID => Arc::new(dpaste_de::create()) as Arc<Host>,
thepasteb_in::ID => Arc::new(thepasteb_in::create()) as Arc<Host>,
ix_io::ID => Arc::new(ix_io::Ix::new()) as Arc<Host>,
codesend::ID => Arc::new(codesend::create()) as Arc<Host>,
glot_io::ID => Arc::new(glot_io::Glot::new()) as Arc<Host>,
};
}
#[cfg(not(test))]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = BUILTIN_HOSTS.clone();
}
#[cfg(test)]
lazy_static! {
pub static ref HOSTS: HashMap<&'static str, Arc<Host>> = {
use testing::{INMEMORY_HOST_DEFAULT_ID, InMemoryHost};
let mut hosts = BUILTIN_HOSTS.clone();
hosts.insert(INMEMORY_HOST_DEFAULT_ID, Arc::new(InMemoryHost::new()) as Arc<Host>);
hosts
};
}
pub const DEFAULT_HOST_ID: &'static str = github::ID;
#[cfg(test)]
mod tests {
use testing::INMEMORY_HOST_DEFAULT_ID;
use super::{DEFAULT_HOST_ID, HOSTS};
#[test]
fn consistent_hosts() {
for (&id, host) in &*HOSTS {
assert_eq!(id, host.id());
}
}
#[test]
fn default_host_id() {
assert!(HOSTS.contains_key(DEFAULT_HOST_ID),
"Default host ID `{}` doesn't occur among known gist hosts", DEFAULT_HOST_ID);
}
#[test]
fn inmemory_host_for_testing() {
assert!(HOSTS.contains_key(INMEMORY_HOST_DEFAULT_ID),
"Test in-memory host ID `{}` doesn't occur among known gist hosts", INMEMORY_HOST_DEFAULT_ID);
}
} | heypasteit::ID => Arc::new(heypasteit::create()) as Arc<Host>,
bpaste::ID => Arc::new(bpaste::create()) as Arc<Host>, | random_line_split |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
use crate::geometry::Rotation;
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator: Allocator<N, D, D>,
{
/// Creates a new square identity rotation of the given `dimension`.
///
/// # Example
/// ```
/// # use nalgebra::Quaternion;
/// let rot1 = Quaternion::identity();
/// let rot2 = Quaternion::new(1.0, 2.0, 3.0, 4.0);
///
/// assert_eq!(rot1 * rot2, rot2);
/// assert_eq!(rot2 * rot1, rot2);
/// ```
#[inline]
pub fn identity() -> Rotation<N, D> {
Self::from_matrix_unchecked(MatrixN::<N, D>::identity())
}
}
impl<N, D: DimName> One for Rotation<N, D>
where
N: Scalar + Zero + One + ClosedAdd + ClosedMul,
DefaultAllocator: Allocator<N, D, D>,
{
#[inline]
fn | () -> Self {
Self::identity()
}
}
| one | identifier_name |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
|
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator: Allocator<N, D, D>,
{
/// Creates a new square identity rotation of the given `dimension`.
///
/// # Example
/// ```
/// # use nalgebra::Quaternion;
/// let rot1 = Quaternion::identity();
/// let rot2 = Quaternion::new(1.0, 2.0, 3.0, 4.0);
///
/// assert_eq!(rot1 * rot2, rot2);
/// assert_eq!(rot2 * rot1, rot2);
/// ```
#[inline]
pub fn identity() -> Rotation<N, D> {
Self::from_matrix_unchecked(MatrixN::<N, D>::identity())
}
}
impl<N, D: DimName> One for Rotation<N, D>
where
N: Scalar + Zero + One + ClosedAdd + ClosedMul,
DefaultAllocator: Allocator<N, D, D>,
{
#[inline]
fn one() -> Self {
Self::identity()
}
} | use crate::geometry::Rotation; | random_line_split |
rotation_construction.rs | use num::{One, Zero};
use simba::scalar::{ClosedAdd, ClosedMul};
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, MatrixN, Scalar};
use crate::geometry::Rotation;
impl<N, D: DimName> Rotation<N, D>
where
N: Scalar + Zero + One,
DefaultAllocator: Allocator<N, D, D>,
{
/// Creates a new square identity rotation of the given `dimension`.
///
/// # Example
/// ```
/// # use nalgebra::Quaternion;
/// let rot1 = Quaternion::identity();
/// let rot2 = Quaternion::new(1.0, 2.0, 3.0, 4.0);
///
/// assert_eq!(rot1 * rot2, rot2);
/// assert_eq!(rot2 * rot1, rot2);
/// ```
#[inline]
pub fn identity() -> Rotation<N, D> {
Self::from_matrix_unchecked(MatrixN::<N, D>::identity())
}
}
impl<N, D: DimName> One for Rotation<N, D>
where
N: Scalar + Zero + One + ClosedAdd + ClosedMul,
DefaultAllocator: Allocator<N, D, D>,
{
#[inline]
fn one() -> Self |
}
| {
Self::identity()
} | identifier_body |
json2mod.rs | use std::fs::File;
use std::io::BufWriter;
use std::io::BufReader;
use anyhow::{Context, Result, anyhow};
// Command line
use docopt::Docopt;
// JSON
use serde::Deserialize;
// ProTracker and ThePlayer
use modfile::ptmf;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
static USAGE: &'static str = "
json2mod.
Usage:
json2mod (-h | --help)
json2mod (-V | --version)
json2mod <source> <destination>
| -h, --help Show this text.
<source> Input file.
<destination> Output file.
";
#[derive(Debug, Deserialize)]
struct Args {
arg_source: String,
arg_destination: String,
flag_help: bool,
flag_version: bool,
}
fn main() -> Result<()> {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if args.flag_version {
println!("Version: {}", VERSION);
return Ok(());
}
// Open json file
let ref first_filename = args.arg_source;
let file = File::open(first_filename)
.with_context(|| format!("Failed to open file: '{}'", first_filename))?;
let reader = BufReader::new(&file);
let mut module: ptmf::PTModule = serde_json::from_reader(reader)
.with_context(|| format!("Failed to parse file: '{}'", first_filename))?;
let ref filename = args.arg_destination;
let file = File::create(&filename)
.with_context(|| format!("Failed to open file: '{}'", filename))?;
let mut writer = BufWriter::new(&file);
match ptmf::write_mod(&mut writer,&mut module) {
Ok(_) => (),
Err(e) => {
return Err(anyhow!("Failed to write module {}. Error: '{:?}'", filename, e))
}
}
Ok(())
} | Options:
-V, --version Show version info. | random_line_split |
json2mod.rs | use std::fs::File;
use std::io::BufWriter;
use std::io::BufReader;
use anyhow::{Context, Result, anyhow};
// Command line
use docopt::Docopt;
// JSON
use serde::Deserialize;
// ProTracker and ThePlayer
use modfile::ptmf;
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
static USAGE: &'static str = "
json2mod.
Usage:
json2mod (-h | --help)
json2mod (-V | --version)
json2mod <source> <destination>
Options:
-V, --version Show version info.
-h, --help Show this text.
<source> Input file.
<destination> Output file.
";
#[derive(Debug, Deserialize)]
struct | {
arg_source: String,
arg_destination: String,
flag_help: bool,
flag_version: bool,
}
fn main() -> Result<()> {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
if args.flag_version {
println!("Version: {}", VERSION);
return Ok(());
}
// Open json file
let ref first_filename = args.arg_source;
let file = File::open(first_filename)
.with_context(|| format!("Failed to open file: '{}'", first_filename))?;
let reader = BufReader::new(&file);
let mut module: ptmf::PTModule = serde_json::from_reader(reader)
.with_context(|| format!("Failed to parse file: '{}'", first_filename))?;
let ref filename = args.arg_destination;
let file = File::create(&filename)
.with_context(|| format!("Failed to open file: '{}'", filename))?;
let mut writer = BufWriter::new(&file);
match ptmf::write_mod(&mut writer,&mut module) {
Ok(_) => (),
Err(e) => {
return Err(anyhow!("Failed to write module {}. Error: '{:?}'", filename, e))
}
}
Ok(())
}
| Args | identifier_name |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLContext {
let window = window::Window::new(width, height, title);
window.make_context_current();
window.exec(proc() {
::gl::load_with(|s| unsafe { std::mem::transmute(libglfw3::glfwGetProcAddress(s.to_c_str().unwrap())) });
}).get();
GLContext {
window: Mutex::new(window)
}
}
pub fn recv(&self) -> Option<super::WindowEvent> {
let mut lock = self.window.lock(); |
pub fn exec<T:Send>(&self, f: proc(): Send -> T) -> Future<T> {
let mut lock = self.window.lock();
lock.exec(f)
}
pub fn swap_buffers(&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
} | lock.recv()
} | random_line_split |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLContext {
let window = window::Window::new(width, height, title);
window.make_context_current();
window.exec(proc() {
::gl::load_with(|s| unsafe { std::mem::transmute(libglfw3::glfwGetProcAddress(s.to_c_str().unwrap())) });
}).get();
GLContext {
window: Mutex::new(window)
}
}
pub fn recv(&self) -> Option<super::WindowEvent> |
pub fn exec<T:Send>(&self, f: proc(): Send -> T) -> Future<T> {
let mut lock = self.window.lock();
lock.exec(f)
}
pub fn swap_buffers(&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
}
| {
let mut lock = self.window.lock();
lock.recv()
} | identifier_body |
mod.rs | extern crate std;
use std::sync::{ Arc, Future, Mutex };
use std::rc::Rc;
use threaded_executer::CommandsThread;
use std::string::String;
#[allow(dead_code)]
mod libglfw3;
mod window;
pub struct GLContext {
window: Mutex<window::Window>
}
impl GLContext {
pub fn new(width: uint, height: uint, title: &str) -> GLContext {
let window = window::Window::new(width, height, title);
window.make_context_current();
window.exec(proc() {
::gl::load_with(|s| unsafe { std::mem::transmute(libglfw3::glfwGetProcAddress(s.to_c_str().unwrap())) });
}).get();
GLContext {
window: Mutex::new(window)
}
}
pub fn recv(&self) -> Option<super::WindowEvent> {
let mut lock = self.window.lock();
lock.recv()
}
pub fn exec<T:Send>(&self, f: proc(): Send -> T) -> Future<T> {
let mut lock = self.window.lock();
lock.exec(f)
}
pub fn | (&self) {
let mut lock = self.window.lock();
lock.swap_buffers()
}
}
| swap_buffers | identifier_name |
imgui_demo.rs | extern crate glutin;
extern crate gl;
extern crate time;
#[macro_use] extern crate rust_imgui;
use rust_imgui as imgui;
pub fn imgui_example_draw() {
let mut opened = true;
imgui::begin(imstr!("Not A Window"), &mut opened, imgui::ImGuiWindowFlags_None);
imgui::text(imstr!("Hello World"));
imgui::text(imstr!("Application average {:.3} ms/frame ({:.1} FPS)",
1000.0 / imgui::get_io().framerate,
imgui::get_io().framerate));
imgui::end();
opened = true;
imgui::show_test_window(&mut opened);
}
/// The main rendering function of ImGui. Can also be wrapped in an extern "C" and used as a callback.
/// but you will need a way to pass around your open GL state.
pub unsafe fn | (state: &DemoGLState, draw_data: &mut imgui::ImDrawData) {
use std::mem;
let io = imgui::get_io();
let fb_width = io.display_size.x * io.display_framebuffer_scale.x;
let fb_height = io.display_size.y * io.display_framebuffer_scale.y;
if fb_width == 0.0 || fb_height == 0.0 { return; }
// draw_data.scale_clip_rects(io.display_framebuffer_scale);
placeholder_scale_clip_rects(draw_data, &io.display_framebuffer_scale);
// Backup GL state.
let mut last_program = 0; gl::GetIntegerv(gl::CURRENT_PROGRAM, &mut last_program);
let mut last_texture = 0; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
let mut last_active_texture = 0; gl::GetIntegerv(gl::ACTIVE_TEXTURE, &mut last_active_texture);
let mut last_array_buffer = 0; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
let mut last_element_array_buffer = 0; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &mut last_element_array_buffer);
let mut last_vertex_array = 0; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let mut last_blend_src = 0; gl::GetIntegerv(gl::BLEND_SRC, &mut last_blend_src);
let mut last_blend_dst = 0; gl::GetIntegerv(gl::BLEND_DST, &mut last_blend_dst);
let mut last_blend_equation_rgb = 0; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &mut last_blend_equation_rgb);
let mut last_blend_equation_alpha = 0; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &mut last_blend_equation_alpha);
let mut last_viewport = [0i32; 4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport[0..4].as_mut_ptr());
let last_enable_blend = gl::IsEnabled(gl::BLEND);
let last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
let last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
let last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, fb_width as i32, fb_height as i32);
let ortho_projection: [[f32; 4]; 4] = [
[ 2.0/io.display_size.x, 0.0, 0.0, 0.0 ],
[ 0.0, 2.0/-io.display_size.y, 0.0, 0.0 ],
[ 0.0, 0.0, -1.0, 0.0 ],
[-1.0, 1.0, 0.0, 1.0 ]
];
gl::UseProgram(state.shader_handle);
gl::Uniform1i(state.attrib_location_tex as i32, 0);
gl::UniformMatrix4fv(state.attrib_location_proj_mtx as i32, 1, gl::FALSE, &ortho_projection[0][0]);
gl::BindVertexArray(state.vao_handle);
for i in 0..draw_data.cmd_lists_count {
let cmd_list = (*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD List in imgui_render_draw_lists");
let mut idx_buffer_offset: *const imgui::ImDrawIdx = mem::transmute(0usize);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::BufferData(
gl::ARRAY_BUFFER,
(cmd_list.vtx_buffer.size * mem::size_of::<imgui::ImDrawVert>() as i32) as isize,
mem::transmute(&cmd_list.vtx_buffer[0]),
gl::STREAM_DRAW
);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize,
mem::transmute(&cmd_list.idx_buffer[0]),
gl::STREAM_DRAW
);
for pcmd_idx in 0..cmd_list.cmd_buffer.size {
let pcmd = &cmd_list.cmd_buffer[pcmd_idx as usize];
if pcmd.user_callback.is_some() {
let _callback = pcmd.user_callback.expect("Failed to get command list user callback.");
_callback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (mem::transmute::<_, usize>(pcmd.texture_id)) as u32);
gl::Scissor(pcmd.clip_rect.x as i32, (fb_height - pcmd.clip_rect.w) as i32, (pcmd.clip_rect.z - pcmd.clip_rect.x) as i32, (pcmd.clip_rect.w - pcmd.clip_rect.y) as i32);
let _s = if mem::size_of::<imgui::ImDrawIdx>() == 2 {gl::UNSIGNED_SHORT} else {gl::UNSIGNED_INT};
gl::DrawElements(gl::TRIANGLES, pcmd.elem_count as i32, _s, mem::transmute(idx_buffer_offset));
}
idx_buffer_offset = idx_buffer_offset.offset(pcmd.elem_count as isize);
}
}
// Restore GL state
gl::UseProgram(last_program as u32);
gl::ActiveTexture(last_active_texture as u32);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindVertexArray(last_vertex_array as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer as u32);
gl::BlendEquationSeparate(last_blend_equation_rgb as u32, last_blend_equation_alpha as u32);
gl::BlendFunc(last_blend_src as u32, last_blend_dst as u32);
if last_enable_blend!= 0 { gl::Enable(gl::BLEND); }
else { gl::Disable(gl::BLEND); }
if last_enable_cull_face!= 0 { gl::Enable(gl::CULL_FACE); }
else { gl::Disable(gl::CULL_FACE) }
if last_enable_depth_test!= 0 { gl::Enable(gl::DEPTH_TEST); }
else { gl::Disable(gl::DEPTH_TEST); }
if last_enable_scissor_test!= 0 { gl::Enable(gl::SCISSOR_TEST); }
else { gl::Disable(gl::SCISSOR_TEST); }
gl::Viewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]);
}
// #NOTE Placeholder functions until cimgui implements the ScaleClipRects
// function in ImGui.
pub fn placeholder_scale_clip_rects(draw_data: &mut imgui::ImDrawData, scale: &imgui::ImVec2) {
for i in 0..draw_data.cmd_lists_count {
let cmd_list = unsafe {
(*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD list in placeholder_scale_clip_rects")
};
for cmd_i in 0..cmd_list.cmd_buffer.size {
let imgui::ImVec4 {x, y, z, w} = cmd_list.cmd_buffer[cmd_i as usize].clip_rect;
cmd_list.cmd_buffer[cmd_i as usize].clip_rect = imgui::vec4(
x * scale.x,
y * scale.y,
z * scale.x,
w * scale.y
);
}
}
}
pub fn imgui_new_frame(state: &mut DemoGLState, window_size: (u32, u32), hidpi_factor: f32) {
if state.font_texture == 0 {
unsafe { imgui_create_device_objects(state) };
}
let io = imgui::get_io();
let (w, h) = window_size;
let hidpi_factor = hidpi_factor;
io.display_size = imgui::vec2(w as f32, h as f32);
io.display_framebuffer_scale = imgui::vec2(hidpi_factor, hidpi_factor); // for hidpi displays (e.g. Macs with retina displays)
// Setup time step:
let current_time = time::precise_time_ns();
io.delta_time = if state.time > 0{
((current_time - state.time) as f64 / 1000000000.0) as f32
} else {
1.0 / 60.0
};
state.time = current_time;
// Update Mouse:
io.mouse_pos = imgui::vec2(state.mouse_position.0 as f32 / hidpi_factor, state.mouse_position.1 as f32 / hidpi_factor);
io.mouse_down[0] = imgui::cbool(state.mouse_pressed[0]);
io.mouse_down[1] = imgui::cbool(state.mouse_pressed[1]);
io.mouse_down[2] = imgui::cbool(state.mouse_pressed[2]);
io.mouse_wheel = state.mouse_wheel;
state.mouse_wheel = 0.0;
imgui::new_frame();
}
pub unsafe fn imgui_create_device_objects(state: &mut DemoGLState) {
use std::mem;
// Backing up the GL state.
let mut last_texture = 0;
let mut last_array_buffer = 0;
let mut last_vertex_array = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let vertex_shader = "
#version 330\n
uniform mat4 ProjMtx;\n
in vec2 Position;\n
in vec2 UV;\n
in vec4 Color;\n
out vec2 Frag_UV;\n
out vec4 Frag_Color;\n
void main()\n
{\n
Frag_UV = UV;\n
Frag_Color = Color;\n
gl_Position = ProjMtx * vec4(Position.xy,0,1);\n
}\n
";
let fragment_shader = "
#version 330\n
uniform sampler2D Texture;\n
in vec2 Frag_UV;\n
in vec4 Frag_Color;\n
out vec4 Out_Color;\n
void main()\n
{\n
Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n
}\n
";
state.shader_handle = gl::CreateProgram();
state.vert_handle = gl::CreateShader(gl::VERTEX_SHADER);
state.frag_handle = gl::CreateShader(gl::FRAGMENT_SHADER);
let vertex_shader_ptr = mem::transmute(vertex_shader.as_ptr());
let fragment_shader_ptr = mem::transmute(fragment_shader.as_ptr());
let vertex_shader_len = vertex_shader.len() as i32;
let fragment_shader_len = fragment_shader.len() as i32;
gl::ShaderSource(state.vert_handle, 1, &vertex_shader_ptr, &vertex_shader_len);
gl::ShaderSource(state.frag_handle, 1, &fragment_shader_ptr, &fragment_shader_len);
gl::CompileShader(state.vert_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.vert_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling vertex shader.");
}
}
gl::CompileShader(state.frag_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.frag_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling fragment shader.");
}
}
// #NOTE you should probably make sure that your shaders compiled successfully here.
gl::AttachShader(state.shader_handle, state.vert_handle);
gl::AttachShader(state.shader_handle, state.frag_handle);
gl::LinkProgram(state.shader_handle);
state.attrib_location_tex = gl::GetUniformLocation(state.shader_handle, imstr!("Texture").as_ptr()) as u32;
state.attrib_location_proj_mtx = gl::GetUniformLocation(state.shader_handle, imstr!("ProjMtx").as_ptr()) as u32;
state.attrib_location_position = gl::GetAttribLocation(state.shader_handle, imstr!("Position").as_ptr()) as u32;
state.attrib_location_uv = gl::GetAttribLocation(state.shader_handle, imstr!("UV").as_ptr()) as u32;
state.attrib_location_color = gl::GetAttribLocation(state.shader_handle, imstr!("Color").as_ptr()) as u32;
gl::GenBuffers(1, &mut state.vbo_handle);
gl::GenBuffers(1, &mut state.elements_handle);
gl::GenVertexArrays(1, &mut state.vao_handle);
gl::BindVertexArray(state.vao_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::EnableVertexAttribArray(state.attrib_location_position);
gl::EnableVertexAttribArray(state.attrib_location_uv);
gl::EnableVertexAttribArray(state.attrib_location_color);
let dv_size = mem::size_of::<imgui::ImDrawVert>() as i32;
gl::VertexAttribPointer(state.attrib_location_position, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(0usize));
gl::VertexAttribPointer(state.attrib_location_uv, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(8usize));
gl::VertexAttribPointer(state.attrib_location_color, 4, gl::UNSIGNED_BYTE, gl::TRUE, dv_size, mem::transmute(16usize));
imgui_create_fonts_texture(state);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindVertexArray(last_vertex_array as u32);
}
pub unsafe fn imgui_create_fonts_texture(state: &mut DemoGLState) {
use std::ptr;
use std::mem;
let io = imgui::get_io();
let mut pixels: *mut u8 = ptr::null_mut();
let mut width = 0;
let mut height = 0;
let mut bytes_per_pixel = 0;
io.fonts.get_tex_data_as_rgba32(&mut pixels, &mut width, &mut height, &mut bytes_per_pixel);
let mut last_texture = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GenTextures(1, &mut state.font_texture);
gl::BindTexture(gl::TEXTURE_2D, state.font_texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, mem::transmute(pixels));
io.fonts.tex_id = mem::transmute(state.font_texture as usize);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
}
/// Setup the ImGui bindings.
pub fn imgui_init() {
let io = imgui::get_io();
io.key_map[imgui::ImGuiKey::Tab as usize] = 0;
io.key_map[imgui::ImGuiKey::LeftArrow as usize] = 1;
io.key_map[imgui::ImGuiKey::RightArrow as usize] = 2;
io.key_map[imgui::ImGuiKey::UpArrow as usize] = 3;
io.key_map[imgui::ImGuiKey::DownArrow as usize] = 4;
io.key_map[imgui::ImGuiKey::PageUp as usize] = 5;
io.key_map[imgui::ImGuiKey::PageDown as usize] = 6;
io.key_map[imgui::ImGuiKey::Home as usize] = 7;
io.key_map[imgui::ImGuiKey::End as usize] = 8;
io.key_map[imgui::ImGuiKey::Delete as usize] = 9;
io.key_map[imgui::ImGuiKey::Backspace as usize] = 10;
io.key_map[imgui::ImGuiKey::Enter as usize] = 11;
io.key_map[imgui::ImGuiKey::Escape as usize] = 12;
io.key_map[imgui::ImGuiKey::A as usize] = 13;
io.key_map[imgui::ImGuiKey::C as usize] = 14;
io.key_map[imgui::ImGuiKey::V as usize] = 15;
io.key_map[imgui::ImGuiKey::X as usize] = 16;
io.key_map[imgui::ImGuiKey::Y as usize] = 17;
io.key_map[imgui::ImGuiKey::Z as usize] = 18;
}
pub fn imgui_shutdown(state: &mut DemoGLState) {
unsafe {
if state.vao_handle!= 0 { gl::DeleteVertexArrays(1, &state.vao_handle); }
if state.vbo_handle!= 0 { gl::DeleteBuffers(1, &state.vbo_handle); }
if state.elements_handle!= 0 { gl::DeleteBuffers(1, &state.elements_handle); }
state.vao_handle = 0;
state.vbo_handle = 0;
state.elements_handle = 0;
gl::DetachShader(state.shader_handle, state.vert_handle);
gl::DeleteShader(state.vert_handle);
state.vert_handle = 0;
gl::DetachShader(state.shader_handle, state.frag_handle);
gl::DeleteShader(state.frag_handle);
state.frag_handle = 0;
gl::DeleteProgram(state.shader_handle);
state.shader_handle = 0;
if state.font_texture!= 0 {
use std::ptr;
gl::DeleteTextures(1, &state.font_texture);
imgui::get_io().fonts.tex_id = ptr::null_mut();
state.font_texture = 0;
}
}
imgui::shutdown();
}
// You can also use a callback by wrapping imgui_render_draw_lists
// in an extern C function.
pub fn imgui_render(state: &DemoGLState) {
imgui::render();
let draw_data = imgui::get_draw_data().expect("null imgui draw data.");
unsafe { imgui_render_draw_lists(state, draw_data) };
}
pub fn imgui_check_event(ui_state: &mut DemoGLState, event: &glutin::Event) {
use glutin::{VirtualKeyCode, Event, ElementState,
MouseButton, MouseScrollDelta, TouchPhase};
let io = imgui::get_io();
match *event {
Event::KeyboardInput(state, _, code) => {
let pressed = imgui::cbool(state == ElementState::Pressed);
match code {
Some(VirtualKeyCode::Tab) => io.keys_down[0] = pressed,
Some(VirtualKeyCode::Left) => io.keys_down[1] = pressed,
Some(VirtualKeyCode::Right) => io.keys_down[2] = pressed,
Some(VirtualKeyCode::Up) => io.keys_down[3] = pressed,
Some(VirtualKeyCode::Down) => io.keys_down[4] = pressed,
Some(VirtualKeyCode::PageUp) => io.keys_down[5] = pressed,
Some(VirtualKeyCode::PageDown) => io.keys_down[6] = pressed,
Some(VirtualKeyCode::Home) => io.keys_down[7] = pressed,
Some(VirtualKeyCode::End) => io.keys_down[8] = pressed,
Some(VirtualKeyCode::Delete) => io.keys_down[9] = pressed,
Some(VirtualKeyCode::Back) => io.keys_down[10] = pressed,
Some(VirtualKeyCode::Return) => io.keys_down[11] = pressed,
Some(VirtualKeyCode::Escape) => io.keys_down[12] = pressed,
Some(VirtualKeyCode::A) => io.keys_down[13] = pressed,
Some(VirtualKeyCode::C) => io.keys_down[14] = pressed,
Some(VirtualKeyCode::V) => io.keys_down[15] = pressed,
Some(VirtualKeyCode::X) => io.keys_down[16] = pressed,
Some(VirtualKeyCode::Y) => io.keys_down[17] = pressed,
Some(VirtualKeyCode::Z) => io.keys_down[18] = pressed,
Some(VirtualKeyCode::LControl) | Some(VirtualKeyCode::RControl) => {
io.key_ctrl = pressed;
},
Some(VirtualKeyCode::LShift) | Some(VirtualKeyCode::RShift) => {
io.key_shift = pressed;
},
Some(VirtualKeyCode::LAlt) | Some(VirtualKeyCode::RAlt) => {
io.key_alt = pressed;
}, // #TODO super key.
_ => {}
}
},
Event::MouseMoved(x, y) => ui_state.mouse_position = (x, y),
Event::MouseInput(state, MouseButton::Left) => ui_state.mouse_pressed[0] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Right) => ui_state.mouse_pressed[1] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Middle) => ui_state.mouse_pressed[2] = state == ElementState::Pressed,
Event::MouseWheel(MouseScrollDelta::LineDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::MouseWheel(MouseScrollDelta::PixelDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::ReceivedCharacter(c) => {
io.add_input_character(c as u16);
},
_ => {}
}
}
pub struct DemoGLState {
pub time: u64,
pub mouse_position: (i32, i32),
pub mouse_pressed: [bool; 3],
pub mouse_wheel: f32,
pub font_texture: u32,
pub shader_handle: u32,
pub vert_handle: u32,
pub frag_handle: u32,
pub attrib_location_tex: u32,
pub attrib_location_proj_mtx: u32,
pub attrib_location_position: u32,
pub attrib_location_uv: u32,
pub attrib_location_color: u32,
pub vbo_handle: u32,
pub vao_handle: u32,
pub elements_handle: u32,
}
pub fn main() {
let builder = glutin::WindowBuilder::new()
.with_dimensions(800, 600)
.with_vsync();
let window = builder.build().unwrap();
let mut demo_state = DemoGLState {
time: 0,
mouse_position: (0, 0),
mouse_pressed: [false; 3],
mouse_wheel: 0.0,
font_texture: 0,
shader_handle: 0,
vert_handle: 0,
frag_handle: 0,
attrib_location_tex: 0,
attrib_location_proj_mtx: 0,
attrib_location_position: 0,
attrib_location_uv: 0,
attrib_location_color: 0,
vbo_handle: 0,
vao_handle: 0,
elements_handle: 0
};
unsafe { window.make_current().unwrap() };
window.set_title("ImGUI-rs Demo");
unsafe {
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
gl::ClearColor(0.1, 0.08, 0.7, 1.0);
}
imgui_init();
'main_loop: loop {
// Poll for events first or you're going to have a bad time.
for event in window.poll_events() {
imgui_check_event(&mut demo_state, &event);
match event {
glutin::Event::Closed => break'main_loop,
_ => ()
}
}
let window_size = window.get_inner_size().expect("Unable to retrieve glutin window size.");
let hidpi_factor = window.hidpi_factor();
// #WARNING calling imgui functions that try to draw widgets
// before new frame will cause a segfault.
imgui_new_frame(&mut demo_state, window_size, hidpi_factor);
imgui_example_draw();
let (w, h) = window.get_inner_size().expect("Unable to retrieve window dimensions.");
unsafe { gl::Viewport(0, 0, w as i32, h as i32) };
unsafe { gl::Clear(gl::COLOR_BUFFER_BIT) };
// #WARINING calling imgui functions that try to draw widgets
// after here (really imgui::render) will cause a segfault.
imgui_render(&demo_state);
window.swap_buffers().expect("Swapping glutin window buffers.");
}
imgui_shutdown(&mut demo_state);
} | imgui_render_draw_lists | identifier_name |
imgui_demo.rs | extern crate glutin;
extern crate gl;
extern crate time;
#[macro_use] extern crate rust_imgui;
use rust_imgui as imgui;
pub fn imgui_example_draw() {
let mut opened = true;
imgui::begin(imstr!("Not A Window"), &mut opened, imgui::ImGuiWindowFlags_None);
imgui::text(imstr!("Hello World"));
imgui::text(imstr!("Application average {:.3} ms/frame ({:.1} FPS)",
1000.0 / imgui::get_io().framerate,
imgui::get_io().framerate));
imgui::end();
opened = true;
imgui::show_test_window(&mut opened);
}
/// The main rendering function of ImGui. Can also be wrapped in an extern "C" and used as a callback.
/// but you will need a way to pass around your open GL state.
pub unsafe fn imgui_render_draw_lists(state: &DemoGLState, draw_data: &mut imgui::ImDrawData) {
use std::mem;
let io = imgui::get_io();
let fb_width = io.display_size.x * io.display_framebuffer_scale.x;
let fb_height = io.display_size.y * io.display_framebuffer_scale.y;
if fb_width == 0.0 || fb_height == 0.0 { return; }
// draw_data.scale_clip_rects(io.display_framebuffer_scale);
placeholder_scale_clip_rects(draw_data, &io.display_framebuffer_scale);
// Backup GL state.
let mut last_program = 0; gl::GetIntegerv(gl::CURRENT_PROGRAM, &mut last_program);
let mut last_texture = 0; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
let mut last_active_texture = 0; gl::GetIntegerv(gl::ACTIVE_TEXTURE, &mut last_active_texture);
let mut last_array_buffer = 0; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
let mut last_element_array_buffer = 0; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &mut last_element_array_buffer);
let mut last_vertex_array = 0; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let mut last_blend_src = 0; gl::GetIntegerv(gl::BLEND_SRC, &mut last_blend_src);
let mut last_blend_dst = 0; gl::GetIntegerv(gl::BLEND_DST, &mut last_blend_dst);
let mut last_blend_equation_rgb = 0; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &mut last_blend_equation_rgb);
let mut last_blend_equation_alpha = 0; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &mut last_blend_equation_alpha);
let mut last_viewport = [0i32; 4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport[0..4].as_mut_ptr());
let last_enable_blend = gl::IsEnabled(gl::BLEND);
let last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
let last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
let last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, fb_width as i32, fb_height as i32);
let ortho_projection: [[f32; 4]; 4] = [
[ 2.0/io.display_size.x, 0.0, 0.0, 0.0 ],
[ 0.0, 2.0/-io.display_size.y, 0.0, 0.0 ],
[ 0.0, 0.0, -1.0, 0.0 ],
[-1.0, 1.0, 0.0, 1.0 ]
];
gl::UseProgram(state.shader_handle);
gl::Uniform1i(state.attrib_location_tex as i32, 0);
gl::UniformMatrix4fv(state.attrib_location_proj_mtx as i32, 1, gl::FALSE, &ortho_projection[0][0]);
gl::BindVertexArray(state.vao_handle);
for i in 0..draw_data.cmd_lists_count {
let cmd_list = (*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD List in imgui_render_draw_lists");
let mut idx_buffer_offset: *const imgui::ImDrawIdx = mem::transmute(0usize);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::BufferData(
gl::ARRAY_BUFFER,
(cmd_list.vtx_buffer.size * mem::size_of::<imgui::ImDrawVert>() as i32) as isize,
mem::transmute(&cmd_list.vtx_buffer[0]),
gl::STREAM_DRAW
);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize,
mem::transmute(&cmd_list.idx_buffer[0]),
gl::STREAM_DRAW
);
for pcmd_idx in 0..cmd_list.cmd_buffer.size {
let pcmd = &cmd_list.cmd_buffer[pcmd_idx as usize];
if pcmd.user_callback.is_some() {
let _callback = pcmd.user_callback.expect("Failed to get command list user callback.");
_callback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (mem::transmute::<_, usize>(pcmd.texture_id)) as u32);
gl::Scissor(pcmd.clip_rect.x as i32, (fb_height - pcmd.clip_rect.w) as i32, (pcmd.clip_rect.z - pcmd.clip_rect.x) as i32, (pcmd.clip_rect.w - pcmd.clip_rect.y) as i32);
let _s = if mem::size_of::<imgui::ImDrawIdx>() == 2 {gl::UNSIGNED_SHORT} else {gl::UNSIGNED_INT};
gl::DrawElements(gl::TRIANGLES, pcmd.elem_count as i32, _s, mem::transmute(idx_buffer_offset));
}
idx_buffer_offset = idx_buffer_offset.offset(pcmd.elem_count as isize);
}
}
// Restore GL state
gl::UseProgram(last_program as u32);
gl::ActiveTexture(last_active_texture as u32);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindVertexArray(last_vertex_array as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer as u32);
gl::BlendEquationSeparate(last_blend_equation_rgb as u32, last_blend_equation_alpha as u32);
gl::BlendFunc(last_blend_src as u32, last_blend_dst as u32);
if last_enable_blend!= 0 { gl::Enable(gl::BLEND); }
else { gl::Disable(gl::BLEND); }
if last_enable_cull_face!= 0 { gl::Enable(gl::CULL_FACE); }
else { gl::Disable(gl::CULL_FACE) }
if last_enable_depth_test!= 0 { gl::Enable(gl::DEPTH_TEST); }
else { gl::Disable(gl::DEPTH_TEST); }
if last_enable_scissor_test!= 0 { gl::Enable(gl::SCISSOR_TEST); }
else { gl::Disable(gl::SCISSOR_TEST); }
gl::Viewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]);
}
// #NOTE Placeholder functions until cimgui implements the ScaleClipRects
// function in ImGui.
pub fn placeholder_scale_clip_rects(draw_data: &mut imgui::ImDrawData, scale: &imgui::ImVec2) |
pub fn imgui_new_frame(state: &mut DemoGLState, window_size: (u32, u32), hidpi_factor: f32) {
if state.font_texture == 0 {
unsafe { imgui_create_device_objects(state) };
}
let io = imgui::get_io();
let (w, h) = window_size;
let hidpi_factor = hidpi_factor;
io.display_size = imgui::vec2(w as f32, h as f32);
io.display_framebuffer_scale = imgui::vec2(hidpi_factor, hidpi_factor); // for hidpi displays (e.g. Macs with retina displays)
// Setup time step:
let current_time = time::precise_time_ns();
io.delta_time = if state.time > 0{
((current_time - state.time) as f64 / 1000000000.0) as f32
} else {
1.0 / 60.0
};
state.time = current_time;
// Update Mouse:
io.mouse_pos = imgui::vec2(state.mouse_position.0 as f32 / hidpi_factor, state.mouse_position.1 as f32 / hidpi_factor);
io.mouse_down[0] = imgui::cbool(state.mouse_pressed[0]);
io.mouse_down[1] = imgui::cbool(state.mouse_pressed[1]);
io.mouse_down[2] = imgui::cbool(state.mouse_pressed[2]);
io.mouse_wheel = state.mouse_wheel;
state.mouse_wheel = 0.0;
imgui::new_frame();
}
pub unsafe fn imgui_create_device_objects(state: &mut DemoGLState) {
use std::mem;
// Backing up the GL state.
let mut last_texture = 0;
let mut last_array_buffer = 0;
let mut last_vertex_array = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let vertex_shader = "
#version 330\n
uniform mat4 ProjMtx;\n
in vec2 Position;\n
in vec2 UV;\n
in vec4 Color;\n
out vec2 Frag_UV;\n
out vec4 Frag_Color;\n
void main()\n
{\n
Frag_UV = UV;\n
Frag_Color = Color;\n
gl_Position = ProjMtx * vec4(Position.xy,0,1);\n
}\n
";
let fragment_shader = "
#version 330\n
uniform sampler2D Texture;\n
in vec2 Frag_UV;\n
in vec4 Frag_Color;\n
out vec4 Out_Color;\n
void main()\n
{\n
Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n
}\n
";
state.shader_handle = gl::CreateProgram();
state.vert_handle = gl::CreateShader(gl::VERTEX_SHADER);
state.frag_handle = gl::CreateShader(gl::FRAGMENT_SHADER);
let vertex_shader_ptr = mem::transmute(vertex_shader.as_ptr());
let fragment_shader_ptr = mem::transmute(fragment_shader.as_ptr());
let vertex_shader_len = vertex_shader.len() as i32;
let fragment_shader_len = fragment_shader.len() as i32;
gl::ShaderSource(state.vert_handle, 1, &vertex_shader_ptr, &vertex_shader_len);
gl::ShaderSource(state.frag_handle, 1, &fragment_shader_ptr, &fragment_shader_len);
gl::CompileShader(state.vert_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.vert_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling vertex shader.");
}
}
gl::CompileShader(state.frag_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.frag_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling fragment shader.");
}
}
// #NOTE you should probably make sure that your shaders compiled successfully here.
gl::AttachShader(state.shader_handle, state.vert_handle);
gl::AttachShader(state.shader_handle, state.frag_handle);
gl::LinkProgram(state.shader_handle);
state.attrib_location_tex = gl::GetUniformLocation(state.shader_handle, imstr!("Texture").as_ptr()) as u32;
state.attrib_location_proj_mtx = gl::GetUniformLocation(state.shader_handle, imstr!("ProjMtx").as_ptr()) as u32;
state.attrib_location_position = gl::GetAttribLocation(state.shader_handle, imstr!("Position").as_ptr()) as u32;
state.attrib_location_uv = gl::GetAttribLocation(state.shader_handle, imstr!("UV").as_ptr()) as u32;
state.attrib_location_color = gl::GetAttribLocation(state.shader_handle, imstr!("Color").as_ptr()) as u32;
gl::GenBuffers(1, &mut state.vbo_handle);
gl::GenBuffers(1, &mut state.elements_handle);
gl::GenVertexArrays(1, &mut state.vao_handle);
gl::BindVertexArray(state.vao_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::EnableVertexAttribArray(state.attrib_location_position);
gl::EnableVertexAttribArray(state.attrib_location_uv);
gl::EnableVertexAttribArray(state.attrib_location_color);
let dv_size = mem::size_of::<imgui::ImDrawVert>() as i32;
gl::VertexAttribPointer(state.attrib_location_position, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(0usize));
gl::VertexAttribPointer(state.attrib_location_uv, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(8usize));
gl::VertexAttribPointer(state.attrib_location_color, 4, gl::UNSIGNED_BYTE, gl::TRUE, dv_size, mem::transmute(16usize));
imgui_create_fonts_texture(state);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindVertexArray(last_vertex_array as u32);
}
pub unsafe fn imgui_create_fonts_texture(state: &mut DemoGLState) {
use std::ptr;
use std::mem;
let io = imgui::get_io();
let mut pixels: *mut u8 = ptr::null_mut();
let mut width = 0;
let mut height = 0;
let mut bytes_per_pixel = 0;
io.fonts.get_tex_data_as_rgba32(&mut pixels, &mut width, &mut height, &mut bytes_per_pixel);
let mut last_texture = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GenTextures(1, &mut state.font_texture);
gl::BindTexture(gl::TEXTURE_2D, state.font_texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, mem::transmute(pixels));
io.fonts.tex_id = mem::transmute(state.font_texture as usize);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
}
/// Setup the ImGui bindings.
pub fn imgui_init() {
let io = imgui::get_io();
io.key_map[imgui::ImGuiKey::Tab as usize] = 0;
io.key_map[imgui::ImGuiKey::LeftArrow as usize] = 1;
io.key_map[imgui::ImGuiKey::RightArrow as usize] = 2;
io.key_map[imgui::ImGuiKey::UpArrow as usize] = 3;
io.key_map[imgui::ImGuiKey::DownArrow as usize] = 4;
io.key_map[imgui::ImGuiKey::PageUp as usize] = 5;
io.key_map[imgui::ImGuiKey::PageDown as usize] = 6;
io.key_map[imgui::ImGuiKey::Home as usize] = 7;
io.key_map[imgui::ImGuiKey::End as usize] = 8;
io.key_map[imgui::ImGuiKey::Delete as usize] = 9;
io.key_map[imgui::ImGuiKey::Backspace as usize] = 10;
io.key_map[imgui::ImGuiKey::Enter as usize] = 11;
io.key_map[imgui::ImGuiKey::Escape as usize] = 12;
io.key_map[imgui::ImGuiKey::A as usize] = 13;
io.key_map[imgui::ImGuiKey::C as usize] = 14;
io.key_map[imgui::ImGuiKey::V as usize] = 15;
io.key_map[imgui::ImGuiKey::X as usize] = 16;
io.key_map[imgui::ImGuiKey::Y as usize] = 17;
io.key_map[imgui::ImGuiKey::Z as usize] = 18;
}
pub fn imgui_shutdown(state: &mut DemoGLState) {
unsafe {
if state.vao_handle!= 0 { gl::DeleteVertexArrays(1, &state.vao_handle); }
if state.vbo_handle!= 0 { gl::DeleteBuffers(1, &state.vbo_handle); }
if state.elements_handle!= 0 { gl::DeleteBuffers(1, &state.elements_handle); }
state.vao_handle = 0;
state.vbo_handle = 0;
state.elements_handle = 0;
gl::DetachShader(state.shader_handle, state.vert_handle);
gl::DeleteShader(state.vert_handle);
state.vert_handle = 0;
gl::DetachShader(state.shader_handle, state.frag_handle);
gl::DeleteShader(state.frag_handle);
state.frag_handle = 0;
gl::DeleteProgram(state.shader_handle);
state.shader_handle = 0;
if state.font_texture!= 0 {
use std::ptr;
gl::DeleteTextures(1, &state.font_texture);
imgui::get_io().fonts.tex_id = ptr::null_mut();
state.font_texture = 0;
}
}
imgui::shutdown();
}
// You can also use a callback by wrapping imgui_render_draw_lists
// in an extern C function.
pub fn imgui_render(state: &DemoGLState) {
imgui::render();
let draw_data = imgui::get_draw_data().expect("null imgui draw data.");
unsafe { imgui_render_draw_lists(state, draw_data) };
}
pub fn imgui_check_event(ui_state: &mut DemoGLState, event: &glutin::Event) {
use glutin::{VirtualKeyCode, Event, ElementState,
MouseButton, MouseScrollDelta, TouchPhase};
let io = imgui::get_io();
match *event {
Event::KeyboardInput(state, _, code) => {
let pressed = imgui::cbool(state == ElementState::Pressed);
match code {
Some(VirtualKeyCode::Tab) => io.keys_down[0] = pressed,
Some(VirtualKeyCode::Left) => io.keys_down[1] = pressed,
Some(VirtualKeyCode::Right) => io.keys_down[2] = pressed,
Some(VirtualKeyCode::Up) => io.keys_down[3] = pressed,
Some(VirtualKeyCode::Down) => io.keys_down[4] = pressed,
Some(VirtualKeyCode::PageUp) => io.keys_down[5] = pressed,
Some(VirtualKeyCode::PageDown) => io.keys_down[6] = pressed,
Some(VirtualKeyCode::Home) => io.keys_down[7] = pressed,
Some(VirtualKeyCode::End) => io.keys_down[8] = pressed,
Some(VirtualKeyCode::Delete) => io.keys_down[9] = pressed,
Some(VirtualKeyCode::Back) => io.keys_down[10] = pressed,
Some(VirtualKeyCode::Return) => io.keys_down[11] = pressed,
Some(VirtualKeyCode::Escape) => io.keys_down[12] = pressed,
Some(VirtualKeyCode::A) => io.keys_down[13] = pressed,
Some(VirtualKeyCode::C) => io.keys_down[14] = pressed,
Some(VirtualKeyCode::V) => io.keys_down[15] = pressed,
Some(VirtualKeyCode::X) => io.keys_down[16] = pressed,
Some(VirtualKeyCode::Y) => io.keys_down[17] = pressed,
Some(VirtualKeyCode::Z) => io.keys_down[18] = pressed,
Some(VirtualKeyCode::LControl) | Some(VirtualKeyCode::RControl) => {
io.key_ctrl = pressed;
},
Some(VirtualKeyCode::LShift) | Some(VirtualKeyCode::RShift) => {
io.key_shift = pressed;
},
Some(VirtualKeyCode::LAlt) | Some(VirtualKeyCode::RAlt) => {
io.key_alt = pressed;
}, // #TODO super key.
_ => {}
}
},
Event::MouseMoved(x, y) => ui_state.mouse_position = (x, y),
Event::MouseInput(state, MouseButton::Left) => ui_state.mouse_pressed[0] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Right) => ui_state.mouse_pressed[1] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Middle) => ui_state.mouse_pressed[2] = state == ElementState::Pressed,
Event::MouseWheel(MouseScrollDelta::LineDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::MouseWheel(MouseScrollDelta::PixelDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::ReceivedCharacter(c) => {
io.add_input_character(c as u16);
},
_ => {}
}
}
pub struct DemoGLState {
pub time: u64,
pub mouse_position: (i32, i32),
pub mouse_pressed: [bool; 3],
pub mouse_wheel: f32,
pub font_texture: u32,
pub shader_handle: u32,
pub vert_handle: u32,
pub frag_handle: u32,
pub attrib_location_tex: u32,
pub attrib_location_proj_mtx: u32,
pub attrib_location_position: u32,
pub attrib_location_uv: u32,
pub attrib_location_color: u32,
pub vbo_handle: u32,
pub vao_handle: u32,
pub elements_handle: u32,
}
pub fn main() {
let builder = glutin::WindowBuilder::new()
.with_dimensions(800, 600)
.with_vsync();
let window = builder.build().unwrap();
let mut demo_state = DemoGLState {
time: 0,
mouse_position: (0, 0),
mouse_pressed: [false; 3],
mouse_wheel: 0.0,
font_texture: 0,
shader_handle: 0,
vert_handle: 0,
frag_handle: 0,
attrib_location_tex: 0,
attrib_location_proj_mtx: 0,
attrib_location_position: 0,
attrib_location_uv: 0,
attrib_location_color: 0,
vbo_handle: 0,
vao_handle: 0,
elements_handle: 0
};
unsafe { window.make_current().unwrap() };
window.set_title("ImGUI-rs Demo");
unsafe {
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
gl::ClearColor(0.1, 0.08, 0.7, 1.0);
}
imgui_init();
'main_loop: loop {
// Poll for events first or you're going to have a bad time.
for event in window.poll_events() {
imgui_check_event(&mut demo_state, &event);
match event {
glutin::Event::Closed => break'main_loop,
_ => ()
}
}
let window_size = window.get_inner_size().expect("Unable to retrieve glutin window size.");
let hidpi_factor = window.hidpi_factor();
// #WARNING calling imgui functions that try to draw widgets
// before new frame will cause a segfault.
imgui_new_frame(&mut demo_state, window_size, hidpi_factor);
imgui_example_draw();
let (w, h) = window.get_inner_size().expect("Unable to retrieve window dimensions.");
unsafe { gl::Viewport(0, 0, w as i32, h as i32) };
unsafe { gl::Clear(gl::COLOR_BUFFER_BIT) };
// #WARINING calling imgui functions that try to draw widgets
// after here (really imgui::render) will cause a segfault.
imgui_render(&demo_state);
window.swap_buffers().expect("Swapping glutin window buffers.");
}
imgui_shutdown(&mut demo_state);
} | {
for i in 0..draw_data.cmd_lists_count {
let cmd_list = unsafe {
(*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD list in placeholder_scale_clip_rects")
};
for cmd_i in 0..cmd_list.cmd_buffer.size {
let imgui::ImVec4 {x, y, z, w} = cmd_list.cmd_buffer[cmd_i as usize].clip_rect;
cmd_list.cmd_buffer[cmd_i as usize].clip_rect = imgui::vec4(
x * scale.x,
y * scale.y,
z * scale.x,
w * scale.y
);
}
}
} | identifier_body |
imgui_demo.rs | extern crate glutin;
extern crate gl;
extern crate time;
#[macro_use] extern crate rust_imgui;
use rust_imgui as imgui;
pub fn imgui_example_draw() {
let mut opened = true;
imgui::begin(imstr!("Not A Window"), &mut opened, imgui::ImGuiWindowFlags_None);
imgui::text(imstr!("Hello World"));
imgui::text(imstr!("Application average {:.3} ms/frame ({:.1} FPS)",
1000.0 / imgui::get_io().framerate,
imgui::get_io().framerate));
imgui::end();
opened = true;
imgui::show_test_window(&mut opened);
}
/// The main rendering function of ImGui. Can also be wrapped in an extern "C" and used as a callback.
/// but you will need a way to pass around your open GL state.
pub unsafe fn imgui_render_draw_lists(state: &DemoGLState, draw_data: &mut imgui::ImDrawData) {
use std::mem;
let io = imgui::get_io();
let fb_width = io.display_size.x * io.display_framebuffer_scale.x;
let fb_height = io.display_size.y * io.display_framebuffer_scale.y;
if fb_width == 0.0 || fb_height == 0.0 { return; }
// draw_data.scale_clip_rects(io.display_framebuffer_scale);
placeholder_scale_clip_rects(draw_data, &io.display_framebuffer_scale);
// Backup GL state.
let mut last_program = 0; gl::GetIntegerv(gl::CURRENT_PROGRAM, &mut last_program);
let mut last_texture = 0; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
let mut last_active_texture = 0; gl::GetIntegerv(gl::ACTIVE_TEXTURE, &mut last_active_texture);
let mut last_array_buffer = 0; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
let mut last_element_array_buffer = 0; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &mut last_element_array_buffer);
let mut last_vertex_array = 0; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let mut last_blend_src = 0; gl::GetIntegerv(gl::BLEND_SRC, &mut last_blend_src);
let mut last_blend_dst = 0; gl::GetIntegerv(gl::BLEND_DST, &mut last_blend_dst);
let mut last_blend_equation_rgb = 0; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &mut last_blend_equation_rgb);
let mut last_blend_equation_alpha = 0; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &mut last_blend_equation_alpha);
let mut last_viewport = [0i32; 4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport[0..4].as_mut_ptr());
let last_enable_blend = gl::IsEnabled(gl::BLEND);
let last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
let last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
let last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, fb_width as i32, fb_height as i32);
let ortho_projection: [[f32; 4]; 4] = [
[ 2.0/io.display_size.x, 0.0, 0.0, 0.0 ],
[ 0.0, 2.0/-io.display_size.y, 0.0, 0.0 ],
[ 0.0, 0.0, -1.0, 0.0 ],
[-1.0, 1.0, 0.0, 1.0 ]
];
gl::UseProgram(state.shader_handle);
gl::Uniform1i(state.attrib_location_tex as i32, 0);
gl::UniformMatrix4fv(state.attrib_location_proj_mtx as i32, 1, gl::FALSE, &ortho_projection[0][0]);
gl::BindVertexArray(state.vao_handle);
for i in 0..draw_data.cmd_lists_count {
let cmd_list = (*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD List in imgui_render_draw_lists");
let mut idx_buffer_offset: *const imgui::ImDrawIdx = mem::transmute(0usize);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::BufferData(
gl::ARRAY_BUFFER,
(cmd_list.vtx_buffer.size * mem::size_of::<imgui::ImDrawVert>() as i32) as isize,
mem::transmute(&cmd_list.vtx_buffer[0]),
gl::STREAM_DRAW
);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize,
mem::transmute(&cmd_list.idx_buffer[0]),
gl::STREAM_DRAW
);
for pcmd_idx in 0..cmd_list.cmd_buffer.size {
let pcmd = &cmd_list.cmd_buffer[pcmd_idx as usize];
if pcmd.user_callback.is_some() {
let _callback = pcmd.user_callback.expect("Failed to get command list user callback.");
_callback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (mem::transmute::<_, usize>(pcmd.texture_id)) as u32);
gl::Scissor(pcmd.clip_rect.x as i32, (fb_height - pcmd.clip_rect.w) as i32, (pcmd.clip_rect.z - pcmd.clip_rect.x) as i32, (pcmd.clip_rect.w - pcmd.clip_rect.y) as i32);
let _s = if mem::size_of::<imgui::ImDrawIdx>() == 2 {gl::UNSIGNED_SHORT} else {gl::UNSIGNED_INT};
gl::DrawElements(gl::TRIANGLES, pcmd.elem_count as i32, _s, mem::transmute(idx_buffer_offset));
}
idx_buffer_offset = idx_buffer_offset.offset(pcmd.elem_count as isize);
}
}
// Restore GL state
gl::UseProgram(last_program as u32);
gl::ActiveTexture(last_active_texture as u32);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindVertexArray(last_vertex_array as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer as u32);
gl::BlendEquationSeparate(last_blend_equation_rgb as u32, last_blend_equation_alpha as u32);
gl::BlendFunc(last_blend_src as u32, last_blend_dst as u32);
if last_enable_blend!= 0 { gl::Enable(gl::BLEND); }
else { gl::Disable(gl::BLEND); }
if last_enable_cull_face!= 0 { gl::Enable(gl::CULL_FACE); }
else { gl::Disable(gl::CULL_FACE) }
if last_enable_depth_test!= 0 { gl::Enable(gl::DEPTH_TEST); }
else { gl::Disable(gl::DEPTH_TEST); }
if last_enable_scissor_test!= 0 { gl::Enable(gl::SCISSOR_TEST); }
else { gl::Disable(gl::SCISSOR_TEST); }
gl::Viewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]);
}
// #NOTE Placeholder functions until cimgui implements the ScaleClipRects
// function in ImGui.
pub fn placeholder_scale_clip_rects(draw_data: &mut imgui::ImDrawData, scale: &imgui::ImVec2) {
for i in 0..draw_data.cmd_lists_count {
let cmd_list = unsafe {
(*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD list in placeholder_scale_clip_rects")
};
for cmd_i in 0..cmd_list.cmd_buffer.size {
let imgui::ImVec4 {x, y, z, w} = cmd_list.cmd_buffer[cmd_i as usize].clip_rect;
cmd_list.cmd_buffer[cmd_i as usize].clip_rect = imgui::vec4(
x * scale.x,
y * scale.y,
z * scale.x,
w * scale.y
);
}
}
}
pub fn imgui_new_frame(state: &mut DemoGLState, window_size: (u32, u32), hidpi_factor: f32) {
if state.font_texture == 0 {
unsafe { imgui_create_device_objects(state) };
}
let io = imgui::get_io();
let (w, h) = window_size;
let hidpi_factor = hidpi_factor;
io.display_size = imgui::vec2(w as f32, h as f32);
io.display_framebuffer_scale = imgui::vec2(hidpi_factor, hidpi_factor); // for hidpi displays (e.g. Macs with retina displays)
// Setup time step:
let current_time = time::precise_time_ns();
io.delta_time = if state.time > 0{
((current_time - state.time) as f64 / 1000000000.0) as f32
} else {
1.0 / 60.0
};
state.time = current_time;
// Update Mouse:
io.mouse_pos = imgui::vec2(state.mouse_position.0 as f32 / hidpi_factor, state.mouse_position.1 as f32 / hidpi_factor);
io.mouse_down[0] = imgui::cbool(state.mouse_pressed[0]);
io.mouse_down[1] = imgui::cbool(state.mouse_pressed[1]);
io.mouse_down[2] = imgui::cbool(state.mouse_pressed[2]);
io.mouse_wheel = state.mouse_wheel;
state.mouse_wheel = 0.0;
imgui::new_frame();
}
pub unsafe fn imgui_create_device_objects(state: &mut DemoGLState) {
use std::mem;
// Backing up the GL state.
let mut last_texture = 0;
let mut last_array_buffer = 0;
let mut last_vertex_array = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let vertex_shader = "
#version 330\n
uniform mat4 ProjMtx;\n
in vec2 Position;\n
in vec2 UV;\n
in vec4 Color;\n
out vec2 Frag_UV;\n
out vec4 Frag_Color;\n
void main()\n
{\n
Frag_UV = UV;\n
Frag_Color = Color;\n
gl_Position = ProjMtx * vec4(Position.xy,0,1);\n
}\n
";
let fragment_shader = "
#version 330\n
uniform sampler2D Texture;\n
in vec2 Frag_UV;\n
in vec4 Frag_Color;\n
out vec4 Out_Color;\n
void main()\n
{\n
Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n
}\n
";
state.shader_handle = gl::CreateProgram();
state.vert_handle = gl::CreateShader(gl::VERTEX_SHADER);
state.frag_handle = gl::CreateShader(gl::FRAGMENT_SHADER);
let vertex_shader_ptr = mem::transmute(vertex_shader.as_ptr());
let fragment_shader_ptr = mem::transmute(fragment_shader.as_ptr());
let vertex_shader_len = vertex_shader.len() as i32;
let fragment_shader_len = fragment_shader.len() as i32;
gl::ShaderSource(state.vert_handle, 1, &vertex_shader_ptr, &vertex_shader_len);
gl::ShaderSource(state.frag_handle, 1, &fragment_shader_ptr, &fragment_shader_len);
gl::CompileShader(state.vert_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.vert_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling vertex shader.");
}
}
gl::CompileShader(state.frag_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.frag_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling fragment shader.");
}
}
// #NOTE you should probably make sure that your shaders compiled successfully here.
gl::AttachShader(state.shader_handle, state.vert_handle);
gl::AttachShader(state.shader_handle, state.frag_handle);
gl::LinkProgram(state.shader_handle);
state.attrib_location_tex = gl::GetUniformLocation(state.shader_handle, imstr!("Texture").as_ptr()) as u32;
state.attrib_location_proj_mtx = gl::GetUniformLocation(state.shader_handle, imstr!("ProjMtx").as_ptr()) as u32;
state.attrib_location_position = gl::GetAttribLocation(state.shader_handle, imstr!("Position").as_ptr()) as u32;
state.attrib_location_uv = gl::GetAttribLocation(state.shader_handle, imstr!("UV").as_ptr()) as u32;
state.attrib_location_color = gl::GetAttribLocation(state.shader_handle, imstr!("Color").as_ptr()) as u32;
gl::GenBuffers(1, &mut state.vbo_handle);
gl::GenBuffers(1, &mut state.elements_handle);
gl::GenVertexArrays(1, &mut state.vao_handle);
gl::BindVertexArray(state.vao_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::EnableVertexAttribArray(state.attrib_location_position);
gl::EnableVertexAttribArray(state.attrib_location_uv);
gl::EnableVertexAttribArray(state.attrib_location_color);
let dv_size = mem::size_of::<imgui::ImDrawVert>() as i32;
gl::VertexAttribPointer(state.attrib_location_position, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(0usize));
gl::VertexAttribPointer(state.attrib_location_uv, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(8usize));
gl::VertexAttribPointer(state.attrib_location_color, 4, gl::UNSIGNED_BYTE, gl::TRUE, dv_size, mem::transmute(16usize));
imgui_create_fonts_texture(state);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindVertexArray(last_vertex_array as u32);
}
pub unsafe fn imgui_create_fonts_texture(state: &mut DemoGLState) {
use std::ptr;
use std::mem;
let io = imgui::get_io();
let mut pixels: *mut u8 = ptr::null_mut();
let mut width = 0;
let mut height = 0;
let mut bytes_per_pixel = 0;
io.fonts.get_tex_data_as_rgba32(&mut pixels, &mut width, &mut height, &mut bytes_per_pixel);
let mut last_texture = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GenTextures(1, &mut state.font_texture);
gl::BindTexture(gl::TEXTURE_2D, state.font_texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, mem::transmute(pixels));
io.fonts.tex_id = mem::transmute(state.font_texture as usize);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
}
/// Setup the ImGui bindings.
pub fn imgui_init() {
let io = imgui::get_io();
io.key_map[imgui::ImGuiKey::Tab as usize] = 0;
io.key_map[imgui::ImGuiKey::LeftArrow as usize] = 1;
io.key_map[imgui::ImGuiKey::RightArrow as usize] = 2;
io.key_map[imgui::ImGuiKey::UpArrow as usize] = 3;
io.key_map[imgui::ImGuiKey::DownArrow as usize] = 4;
io.key_map[imgui::ImGuiKey::PageUp as usize] = 5;
io.key_map[imgui::ImGuiKey::PageDown as usize] = 6;
io.key_map[imgui::ImGuiKey::Home as usize] = 7;
io.key_map[imgui::ImGuiKey::End as usize] = 8;
io.key_map[imgui::ImGuiKey::Delete as usize] = 9;
io.key_map[imgui::ImGuiKey::Backspace as usize] = 10;
io.key_map[imgui::ImGuiKey::Enter as usize] = 11;
io.key_map[imgui::ImGuiKey::Escape as usize] = 12;
io.key_map[imgui::ImGuiKey::A as usize] = 13;
io.key_map[imgui::ImGuiKey::C as usize] = 14;
io.key_map[imgui::ImGuiKey::V as usize] = 15;
io.key_map[imgui::ImGuiKey::X as usize] = 16;
io.key_map[imgui::ImGuiKey::Y as usize] = 17;
io.key_map[imgui::ImGuiKey::Z as usize] = 18;
}
pub fn imgui_shutdown(state: &mut DemoGLState) {
unsafe {
if state.vao_handle!= 0 { gl::DeleteVertexArrays(1, &state.vao_handle); }
if state.vbo_handle!= 0 { gl::DeleteBuffers(1, &state.vbo_handle); }
if state.elements_handle!= 0 { gl::DeleteBuffers(1, &state.elements_handle); }
state.vao_handle = 0;
state.vbo_handle = 0;
state.elements_handle = 0;
gl::DetachShader(state.shader_handle, state.vert_handle);
gl::DeleteShader(state.vert_handle);
state.vert_handle = 0;
gl::DetachShader(state.shader_handle, state.frag_handle);
gl::DeleteShader(state.frag_handle);
state.frag_handle = 0;
gl::DeleteProgram(state.shader_handle);
state.shader_handle = 0;
if state.font_texture!= 0 |
}
imgui::shutdown();
}
// You can also use a callback by wrapping imgui_render_draw_lists
// in an extern C function.
pub fn imgui_render(state: &DemoGLState) {
imgui::render();
let draw_data = imgui::get_draw_data().expect("null imgui draw data.");
unsafe { imgui_render_draw_lists(state, draw_data) };
}
pub fn imgui_check_event(ui_state: &mut DemoGLState, event: &glutin::Event) {
use glutin::{VirtualKeyCode, Event, ElementState,
MouseButton, MouseScrollDelta, TouchPhase};
let io = imgui::get_io();
match *event {
Event::KeyboardInput(state, _, code) => {
let pressed = imgui::cbool(state == ElementState::Pressed);
match code {
Some(VirtualKeyCode::Tab) => io.keys_down[0] = pressed,
Some(VirtualKeyCode::Left) => io.keys_down[1] = pressed,
Some(VirtualKeyCode::Right) => io.keys_down[2] = pressed,
Some(VirtualKeyCode::Up) => io.keys_down[3] = pressed,
Some(VirtualKeyCode::Down) => io.keys_down[4] = pressed,
Some(VirtualKeyCode::PageUp) => io.keys_down[5] = pressed,
Some(VirtualKeyCode::PageDown) => io.keys_down[6] = pressed,
Some(VirtualKeyCode::Home) => io.keys_down[7] = pressed,
Some(VirtualKeyCode::End) => io.keys_down[8] = pressed,
Some(VirtualKeyCode::Delete) => io.keys_down[9] = pressed,
Some(VirtualKeyCode::Back) => io.keys_down[10] = pressed,
Some(VirtualKeyCode::Return) => io.keys_down[11] = pressed,
Some(VirtualKeyCode::Escape) => io.keys_down[12] = pressed,
Some(VirtualKeyCode::A) => io.keys_down[13] = pressed,
Some(VirtualKeyCode::C) => io.keys_down[14] = pressed,
Some(VirtualKeyCode::V) => io.keys_down[15] = pressed,
Some(VirtualKeyCode::X) => io.keys_down[16] = pressed,
Some(VirtualKeyCode::Y) => io.keys_down[17] = pressed,
Some(VirtualKeyCode::Z) => io.keys_down[18] = pressed,
Some(VirtualKeyCode::LControl) | Some(VirtualKeyCode::RControl) => {
io.key_ctrl = pressed;
},
Some(VirtualKeyCode::LShift) | Some(VirtualKeyCode::RShift) => {
io.key_shift = pressed;
},
Some(VirtualKeyCode::LAlt) | Some(VirtualKeyCode::RAlt) => {
io.key_alt = pressed;
}, // #TODO super key.
_ => {}
}
},
Event::MouseMoved(x, y) => ui_state.mouse_position = (x, y),
Event::MouseInput(state, MouseButton::Left) => ui_state.mouse_pressed[0] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Right) => ui_state.mouse_pressed[1] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Middle) => ui_state.mouse_pressed[2] = state == ElementState::Pressed,
Event::MouseWheel(MouseScrollDelta::LineDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::MouseWheel(MouseScrollDelta::PixelDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::ReceivedCharacter(c) => {
io.add_input_character(c as u16);
},
_ => {}
}
}
pub struct DemoGLState {
pub time: u64,
pub mouse_position: (i32, i32),
pub mouse_pressed: [bool; 3],
pub mouse_wheel: f32,
pub font_texture: u32,
pub shader_handle: u32,
pub vert_handle: u32,
pub frag_handle: u32,
pub attrib_location_tex: u32,
pub attrib_location_proj_mtx: u32,
pub attrib_location_position: u32,
pub attrib_location_uv: u32,
pub attrib_location_color: u32,
pub vbo_handle: u32,
pub vao_handle: u32,
pub elements_handle: u32,
}
pub fn main() {
let builder = glutin::WindowBuilder::new()
.with_dimensions(800, 600)
.with_vsync();
let window = builder.build().unwrap();
let mut demo_state = DemoGLState {
time: 0,
mouse_position: (0, 0),
mouse_pressed: [false; 3],
mouse_wheel: 0.0,
font_texture: 0,
shader_handle: 0,
vert_handle: 0,
frag_handle: 0,
attrib_location_tex: 0,
attrib_location_proj_mtx: 0,
attrib_location_position: 0,
attrib_location_uv: 0,
attrib_location_color: 0,
vbo_handle: 0,
vao_handle: 0,
elements_handle: 0
};
unsafe { window.make_current().unwrap() };
window.set_title("ImGUI-rs Demo");
unsafe {
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
gl::ClearColor(0.1, 0.08, 0.7, 1.0);
}
imgui_init();
'main_loop: loop {
// Poll for events first or you're going to have a bad time.
for event in window.poll_events() {
imgui_check_event(&mut demo_state, &event);
match event {
glutin::Event::Closed => break'main_loop,
_ => ()
}
}
let window_size = window.get_inner_size().expect("Unable to retrieve glutin window size.");
let hidpi_factor = window.hidpi_factor();
// #WARNING calling imgui functions that try to draw widgets
// before new frame will cause a segfault.
imgui_new_frame(&mut demo_state, window_size, hidpi_factor);
imgui_example_draw();
let (w, h) = window.get_inner_size().expect("Unable to retrieve window dimensions.");
unsafe { gl::Viewport(0, 0, w as i32, h as i32) };
unsafe { gl::Clear(gl::COLOR_BUFFER_BIT) };
// #WARINING calling imgui functions that try to draw widgets
// after here (really imgui::render) will cause a segfault.
imgui_render(&demo_state);
window.swap_buffers().expect("Swapping glutin window buffers.");
}
imgui_shutdown(&mut demo_state);
} | {
use std::ptr;
gl::DeleteTextures(1, &state.font_texture);
imgui::get_io().fonts.tex_id = ptr::null_mut();
state.font_texture = 0;
} | conditional_block |
imgui_demo.rs | extern crate glutin;
extern crate gl;
extern crate time;
#[macro_use] extern crate rust_imgui;
use rust_imgui as imgui;
pub fn imgui_example_draw() {
let mut opened = true;
imgui::begin(imstr!("Not A Window"), &mut opened, imgui::ImGuiWindowFlags_None);
imgui::text(imstr!("Hello World"));
imgui::text(imstr!("Application average {:.3} ms/frame ({:.1} FPS)",
1000.0 / imgui::get_io().framerate,
imgui::get_io().framerate));
imgui::end();
opened = true;
imgui::show_test_window(&mut opened);
}
/// The main rendering function of ImGui. Can also be wrapped in an extern "C" and used as a callback.
/// but you will need a way to pass around your open GL state.
pub unsafe fn imgui_render_draw_lists(state: &DemoGLState, draw_data: &mut imgui::ImDrawData) {
use std::mem;
let io = imgui::get_io();
let fb_width = io.display_size.x * io.display_framebuffer_scale.x;
let fb_height = io.display_size.y * io.display_framebuffer_scale.y;
if fb_width == 0.0 || fb_height == 0.0 { return; }
// draw_data.scale_clip_rects(io.display_framebuffer_scale);
placeholder_scale_clip_rects(draw_data, &io.display_framebuffer_scale);
// Backup GL state.
let mut last_program = 0; gl::GetIntegerv(gl::CURRENT_PROGRAM, &mut last_program);
let mut last_texture = 0; gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
let mut last_active_texture = 0; gl::GetIntegerv(gl::ACTIVE_TEXTURE, &mut last_active_texture);
let mut last_array_buffer = 0; gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
let mut last_element_array_buffer = 0; gl::GetIntegerv(gl::ELEMENT_ARRAY_BUFFER_BINDING, &mut last_element_array_buffer);
let mut last_vertex_array = 0; gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let mut last_blend_src = 0; gl::GetIntegerv(gl::BLEND_SRC, &mut last_blend_src);
let mut last_blend_dst = 0; gl::GetIntegerv(gl::BLEND_DST, &mut last_blend_dst);
let mut last_blend_equation_rgb = 0; gl::GetIntegerv(gl::BLEND_EQUATION_RGB, &mut last_blend_equation_rgb);
let mut last_blend_equation_alpha = 0; gl::GetIntegerv(gl::BLEND_EQUATION_ALPHA, &mut last_blend_equation_alpha);
let mut last_viewport = [0i32; 4]; gl::GetIntegerv(gl::VIEWPORT, last_viewport[0..4].as_mut_ptr());
let last_enable_blend = gl::IsEnabled(gl::BLEND);
let last_enable_cull_face = gl::IsEnabled(gl::CULL_FACE);
let last_enable_depth_test = gl::IsEnabled(gl::DEPTH_TEST);
let last_enable_scissor_test = gl::IsEnabled(gl::SCISSOR_TEST);
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
gl::Enable(gl::BLEND);
gl::BlendEquation(gl::FUNC_ADD);
gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
gl::Disable(gl::CULL_FACE);
gl::Disable(gl::DEPTH_TEST);
gl::Enable(gl::SCISSOR_TEST);
gl::ActiveTexture(gl::TEXTURE0);
// Setup viewport, orthographic projection matrix
gl::Viewport(0, 0, fb_width as i32, fb_height as i32);
let ortho_projection: [[f32; 4]; 4] = [
[ 2.0/io.display_size.x, 0.0, 0.0, 0.0 ],
[ 0.0, 2.0/-io.display_size.y, 0.0, 0.0 ],
[ 0.0, 0.0, -1.0, 0.0 ],
[-1.0, 1.0, 0.0, 1.0 ]
];
gl::UseProgram(state.shader_handle);
gl::Uniform1i(state.attrib_location_tex as i32, 0);
gl::UniformMatrix4fv(state.attrib_location_proj_mtx as i32, 1, gl::FALSE, &ortho_projection[0][0]);
gl::BindVertexArray(state.vao_handle);
for i in 0..draw_data.cmd_lists_count {
let cmd_list = (*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD List in imgui_render_draw_lists");
let mut idx_buffer_offset: *const imgui::ImDrawIdx = mem::transmute(0usize);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::BufferData(
gl::ARRAY_BUFFER,
(cmd_list.vtx_buffer.size * mem::size_of::<imgui::ImDrawVert>() as i32) as isize,
mem::transmute(&cmd_list.vtx_buffer[0]),
gl::STREAM_DRAW
);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle);
gl::BufferData(
gl::ELEMENT_ARRAY_BUFFER,
(cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize,
mem::transmute(&cmd_list.idx_buffer[0]),
gl::STREAM_DRAW
);
for pcmd_idx in 0..cmd_list.cmd_buffer.size {
let pcmd = &cmd_list.cmd_buffer[pcmd_idx as usize];
if pcmd.user_callback.is_some() {
let _callback = pcmd.user_callback.expect("Failed to get command list user callback.");
_callback(cmd_list, pcmd);
} else {
gl::BindTexture(gl::TEXTURE_2D, (mem::transmute::<_, usize>(pcmd.texture_id)) as u32);
gl::Scissor(pcmd.clip_rect.x as i32, (fb_height - pcmd.clip_rect.w) as i32, (pcmd.clip_rect.z - pcmd.clip_rect.x) as i32, (pcmd.clip_rect.w - pcmd.clip_rect.y) as i32);
let _s = if mem::size_of::<imgui::ImDrawIdx>() == 2 {gl::UNSIGNED_SHORT} else {gl::UNSIGNED_INT};
gl::DrawElements(gl::TRIANGLES, pcmd.elem_count as i32, _s, mem::transmute(idx_buffer_offset));
}
idx_buffer_offset = idx_buffer_offset.offset(pcmd.elem_count as isize);
}
}
// Restore GL state
gl::UseProgram(last_program as u32);
gl::ActiveTexture(last_active_texture as u32);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindVertexArray(last_vertex_array as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, last_element_array_buffer as u32);
gl::BlendEquationSeparate(last_blend_equation_rgb as u32, last_blend_equation_alpha as u32);
gl::BlendFunc(last_blend_src as u32, last_blend_dst as u32);
if last_enable_blend!= 0 { gl::Enable(gl::BLEND); }
else { gl::Disable(gl::BLEND); }
if last_enable_cull_face!= 0 { gl::Enable(gl::CULL_FACE); } | else { gl::Disable(gl::CULL_FACE) }
if last_enable_depth_test!= 0 { gl::Enable(gl::DEPTH_TEST); }
else { gl::Disable(gl::DEPTH_TEST); }
if last_enable_scissor_test!= 0 { gl::Enable(gl::SCISSOR_TEST); }
else { gl::Disable(gl::SCISSOR_TEST); }
gl::Viewport(last_viewport[0], last_viewport[1], last_viewport[2], last_viewport[3]);
}
// #NOTE Placeholder functions until cimgui implements the ScaleClipRects
// function in ImGui.
pub fn placeholder_scale_clip_rects(draw_data: &mut imgui::ImDrawData, scale: &imgui::ImVec2) {
for i in 0..draw_data.cmd_lists_count {
let cmd_list = unsafe {
(*draw_data.cmd_lists.offset(i as isize)).as_mut()
.expect("Indexing CMD list in placeholder_scale_clip_rects")
};
for cmd_i in 0..cmd_list.cmd_buffer.size {
let imgui::ImVec4 {x, y, z, w} = cmd_list.cmd_buffer[cmd_i as usize].clip_rect;
cmd_list.cmd_buffer[cmd_i as usize].clip_rect = imgui::vec4(
x * scale.x,
y * scale.y,
z * scale.x,
w * scale.y
);
}
}
}
pub fn imgui_new_frame(state: &mut DemoGLState, window_size: (u32, u32), hidpi_factor: f32) {
if state.font_texture == 0 {
unsafe { imgui_create_device_objects(state) };
}
let io = imgui::get_io();
let (w, h) = window_size;
let hidpi_factor = hidpi_factor;
io.display_size = imgui::vec2(w as f32, h as f32);
io.display_framebuffer_scale = imgui::vec2(hidpi_factor, hidpi_factor); // for hidpi displays (e.g. Macs with retina displays)
// Setup time step:
let current_time = time::precise_time_ns();
io.delta_time = if state.time > 0{
((current_time - state.time) as f64 / 1000000000.0) as f32
} else {
1.0 / 60.0
};
state.time = current_time;
// Update Mouse:
io.mouse_pos = imgui::vec2(state.mouse_position.0 as f32 / hidpi_factor, state.mouse_position.1 as f32 / hidpi_factor);
io.mouse_down[0] = imgui::cbool(state.mouse_pressed[0]);
io.mouse_down[1] = imgui::cbool(state.mouse_pressed[1]);
io.mouse_down[2] = imgui::cbool(state.mouse_pressed[2]);
io.mouse_wheel = state.mouse_wheel;
state.mouse_wheel = 0.0;
imgui::new_frame();
}
pub unsafe fn imgui_create_device_objects(state: &mut DemoGLState) {
use std::mem;
// Backing up the GL state.
let mut last_texture = 0;
let mut last_array_buffer = 0;
let mut last_vertex_array = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GetIntegerv(gl::ARRAY_BUFFER_BINDING, &mut last_array_buffer);
gl::GetIntegerv(gl::VERTEX_ARRAY_BINDING, &mut last_vertex_array);
let vertex_shader = "
#version 330\n
uniform mat4 ProjMtx;\n
in vec2 Position;\n
in vec2 UV;\n
in vec4 Color;\n
out vec2 Frag_UV;\n
out vec4 Frag_Color;\n
void main()\n
{\n
Frag_UV = UV;\n
Frag_Color = Color;\n
gl_Position = ProjMtx * vec4(Position.xy,0,1);\n
}\n
";
let fragment_shader = "
#version 330\n
uniform sampler2D Texture;\n
in vec2 Frag_UV;\n
in vec4 Frag_Color;\n
out vec4 Out_Color;\n
void main()\n
{\n
Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n
}\n
";
state.shader_handle = gl::CreateProgram();
state.vert_handle = gl::CreateShader(gl::VERTEX_SHADER);
state.frag_handle = gl::CreateShader(gl::FRAGMENT_SHADER);
let vertex_shader_ptr = mem::transmute(vertex_shader.as_ptr());
let fragment_shader_ptr = mem::transmute(fragment_shader.as_ptr());
let vertex_shader_len = vertex_shader.len() as i32;
let fragment_shader_len = fragment_shader.len() as i32;
gl::ShaderSource(state.vert_handle, 1, &vertex_shader_ptr, &vertex_shader_len);
gl::ShaderSource(state.frag_handle, 1, &fragment_shader_ptr, &fragment_shader_len);
gl::CompileShader(state.vert_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.vert_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling vertex shader.");
}
}
gl::CompileShader(state.frag_handle);
{
let mut is_compiled = 0;
gl::GetShaderiv(state.frag_handle, gl::COMPILE_STATUS, &mut is_compiled);
if is_compiled == (gl::FALSE as i32) {
println!("Error while compiling fragment shader.");
}
}
// #NOTE you should probably make sure that your shaders compiled successfully here.
gl::AttachShader(state.shader_handle, state.vert_handle);
gl::AttachShader(state.shader_handle, state.frag_handle);
gl::LinkProgram(state.shader_handle);
state.attrib_location_tex = gl::GetUniformLocation(state.shader_handle, imstr!("Texture").as_ptr()) as u32;
state.attrib_location_proj_mtx = gl::GetUniformLocation(state.shader_handle, imstr!("ProjMtx").as_ptr()) as u32;
state.attrib_location_position = gl::GetAttribLocation(state.shader_handle, imstr!("Position").as_ptr()) as u32;
state.attrib_location_uv = gl::GetAttribLocation(state.shader_handle, imstr!("UV").as_ptr()) as u32;
state.attrib_location_color = gl::GetAttribLocation(state.shader_handle, imstr!("Color").as_ptr()) as u32;
gl::GenBuffers(1, &mut state.vbo_handle);
gl::GenBuffers(1, &mut state.elements_handle);
gl::GenVertexArrays(1, &mut state.vao_handle);
gl::BindVertexArray(state.vao_handle);
gl::BindBuffer(gl::ARRAY_BUFFER, state.vbo_handle);
gl::EnableVertexAttribArray(state.attrib_location_position);
gl::EnableVertexAttribArray(state.attrib_location_uv);
gl::EnableVertexAttribArray(state.attrib_location_color);
let dv_size = mem::size_of::<imgui::ImDrawVert>() as i32;
gl::VertexAttribPointer(state.attrib_location_position, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(0usize));
gl::VertexAttribPointer(state.attrib_location_uv, 2, gl::FLOAT, gl::FALSE, dv_size, mem::transmute(8usize));
gl::VertexAttribPointer(state.attrib_location_color, 4, gl::UNSIGNED_BYTE, gl::TRUE, dv_size, mem::transmute(16usize));
imgui_create_fonts_texture(state);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
gl::BindBuffer(gl::ARRAY_BUFFER, last_array_buffer as u32);
gl::BindVertexArray(last_vertex_array as u32);
}
pub unsafe fn imgui_create_fonts_texture(state: &mut DemoGLState) {
use std::ptr;
use std::mem;
let io = imgui::get_io();
let mut pixels: *mut u8 = ptr::null_mut();
let mut width = 0;
let mut height = 0;
let mut bytes_per_pixel = 0;
io.fonts.get_tex_data_as_rgba32(&mut pixels, &mut width, &mut height, &mut bytes_per_pixel);
let mut last_texture = 0;
gl::GetIntegerv(gl::TEXTURE_BINDING_2D, &mut last_texture);
gl::GenTextures(1, &mut state.font_texture);
gl::BindTexture(gl::TEXTURE_2D, state.font_texture);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
gl::TexImage2D(gl::TEXTURE_2D, 0, gl::RGBA as i32, width, height, 0, gl::RGBA, gl::UNSIGNED_BYTE, mem::transmute(pixels));
io.fonts.tex_id = mem::transmute(state.font_texture as usize);
gl::BindTexture(gl::TEXTURE_2D, last_texture as u32);
}
/// Setup the ImGui bindings.
pub fn imgui_init() {
let io = imgui::get_io();
io.key_map[imgui::ImGuiKey::Tab as usize] = 0;
io.key_map[imgui::ImGuiKey::LeftArrow as usize] = 1;
io.key_map[imgui::ImGuiKey::RightArrow as usize] = 2;
io.key_map[imgui::ImGuiKey::UpArrow as usize] = 3;
io.key_map[imgui::ImGuiKey::DownArrow as usize] = 4;
io.key_map[imgui::ImGuiKey::PageUp as usize] = 5;
io.key_map[imgui::ImGuiKey::PageDown as usize] = 6;
io.key_map[imgui::ImGuiKey::Home as usize] = 7;
io.key_map[imgui::ImGuiKey::End as usize] = 8;
io.key_map[imgui::ImGuiKey::Delete as usize] = 9;
io.key_map[imgui::ImGuiKey::Backspace as usize] = 10;
io.key_map[imgui::ImGuiKey::Enter as usize] = 11;
io.key_map[imgui::ImGuiKey::Escape as usize] = 12;
io.key_map[imgui::ImGuiKey::A as usize] = 13;
io.key_map[imgui::ImGuiKey::C as usize] = 14;
io.key_map[imgui::ImGuiKey::V as usize] = 15;
io.key_map[imgui::ImGuiKey::X as usize] = 16;
io.key_map[imgui::ImGuiKey::Y as usize] = 17;
io.key_map[imgui::ImGuiKey::Z as usize] = 18;
}
pub fn imgui_shutdown(state: &mut DemoGLState) {
unsafe {
if state.vao_handle!= 0 { gl::DeleteVertexArrays(1, &state.vao_handle); }
if state.vbo_handle!= 0 { gl::DeleteBuffers(1, &state.vbo_handle); }
if state.elements_handle!= 0 { gl::DeleteBuffers(1, &state.elements_handle); }
state.vao_handle = 0;
state.vbo_handle = 0;
state.elements_handle = 0;
gl::DetachShader(state.shader_handle, state.vert_handle);
gl::DeleteShader(state.vert_handle);
state.vert_handle = 0;
gl::DetachShader(state.shader_handle, state.frag_handle);
gl::DeleteShader(state.frag_handle);
state.frag_handle = 0;
gl::DeleteProgram(state.shader_handle);
state.shader_handle = 0;
if state.font_texture!= 0 {
use std::ptr;
gl::DeleteTextures(1, &state.font_texture);
imgui::get_io().fonts.tex_id = ptr::null_mut();
state.font_texture = 0;
}
}
imgui::shutdown();
}
// You can also use a callback by wrapping imgui_render_draw_lists
// in an extern C function.
pub fn imgui_render(state: &DemoGLState) {
imgui::render();
let draw_data = imgui::get_draw_data().expect("null imgui draw data.");
unsafe { imgui_render_draw_lists(state, draw_data) };
}
pub fn imgui_check_event(ui_state: &mut DemoGLState, event: &glutin::Event) {
use glutin::{VirtualKeyCode, Event, ElementState,
MouseButton, MouseScrollDelta, TouchPhase};
let io = imgui::get_io();
match *event {
Event::KeyboardInput(state, _, code) => {
let pressed = imgui::cbool(state == ElementState::Pressed);
match code {
Some(VirtualKeyCode::Tab) => io.keys_down[0] = pressed,
Some(VirtualKeyCode::Left) => io.keys_down[1] = pressed,
Some(VirtualKeyCode::Right) => io.keys_down[2] = pressed,
Some(VirtualKeyCode::Up) => io.keys_down[3] = pressed,
Some(VirtualKeyCode::Down) => io.keys_down[4] = pressed,
Some(VirtualKeyCode::PageUp) => io.keys_down[5] = pressed,
Some(VirtualKeyCode::PageDown) => io.keys_down[6] = pressed,
Some(VirtualKeyCode::Home) => io.keys_down[7] = pressed,
Some(VirtualKeyCode::End) => io.keys_down[8] = pressed,
Some(VirtualKeyCode::Delete) => io.keys_down[9] = pressed,
Some(VirtualKeyCode::Back) => io.keys_down[10] = pressed,
Some(VirtualKeyCode::Return) => io.keys_down[11] = pressed,
Some(VirtualKeyCode::Escape) => io.keys_down[12] = pressed,
Some(VirtualKeyCode::A) => io.keys_down[13] = pressed,
Some(VirtualKeyCode::C) => io.keys_down[14] = pressed,
Some(VirtualKeyCode::V) => io.keys_down[15] = pressed,
Some(VirtualKeyCode::X) => io.keys_down[16] = pressed,
Some(VirtualKeyCode::Y) => io.keys_down[17] = pressed,
Some(VirtualKeyCode::Z) => io.keys_down[18] = pressed,
Some(VirtualKeyCode::LControl) | Some(VirtualKeyCode::RControl) => {
io.key_ctrl = pressed;
},
Some(VirtualKeyCode::LShift) | Some(VirtualKeyCode::RShift) => {
io.key_shift = pressed;
},
Some(VirtualKeyCode::LAlt) | Some(VirtualKeyCode::RAlt) => {
io.key_alt = pressed;
}, // #TODO super key.
_ => {}
}
},
Event::MouseMoved(x, y) => ui_state.mouse_position = (x, y),
Event::MouseInput(state, MouseButton::Left) => ui_state.mouse_pressed[0] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Right) => ui_state.mouse_pressed[1] = state == ElementState::Pressed,
Event::MouseInput(state, MouseButton::Middle) => ui_state.mouse_pressed[2] = state == ElementState::Pressed,
Event::MouseWheel(MouseScrollDelta::LineDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::MouseWheel(MouseScrollDelta::PixelDelta(_, y), TouchPhase::Moved) => ui_state.mouse_wheel = y,
Event::ReceivedCharacter(c) => {
io.add_input_character(c as u16);
},
_ => {}
}
}
pub struct DemoGLState {
pub time: u64,
pub mouse_position: (i32, i32),
pub mouse_pressed: [bool; 3],
pub mouse_wheel: f32,
pub font_texture: u32,
pub shader_handle: u32,
pub vert_handle: u32,
pub frag_handle: u32,
pub attrib_location_tex: u32,
pub attrib_location_proj_mtx: u32,
pub attrib_location_position: u32,
pub attrib_location_uv: u32,
pub attrib_location_color: u32,
pub vbo_handle: u32,
pub vao_handle: u32,
pub elements_handle: u32,
}
pub fn main() {
let builder = glutin::WindowBuilder::new()
.with_dimensions(800, 600)
.with_vsync();
let window = builder.build().unwrap();
let mut demo_state = DemoGLState {
time: 0,
mouse_position: (0, 0),
mouse_pressed: [false; 3],
mouse_wheel: 0.0,
font_texture: 0,
shader_handle: 0,
vert_handle: 0,
frag_handle: 0,
attrib_location_tex: 0,
attrib_location_proj_mtx: 0,
attrib_location_position: 0,
attrib_location_uv: 0,
attrib_location_color: 0,
vbo_handle: 0,
vao_handle: 0,
elements_handle: 0
};
unsafe { window.make_current().unwrap() };
window.set_title("ImGUI-rs Demo");
unsafe {
gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);
gl::ClearColor(0.1, 0.08, 0.7, 1.0);
}
imgui_init();
'main_loop: loop {
// Poll for events first or you're going to have a bad time.
for event in window.poll_events() {
imgui_check_event(&mut demo_state, &event);
match event {
glutin::Event::Closed => break'main_loop,
_ => ()
}
}
let window_size = window.get_inner_size().expect("Unable to retrieve glutin window size.");
let hidpi_factor = window.hidpi_factor();
// #WARNING calling imgui functions that try to draw widgets
// before new frame will cause a segfault.
imgui_new_frame(&mut demo_state, window_size, hidpi_factor);
imgui_example_draw();
let (w, h) = window.get_inner_size().expect("Unable to retrieve window dimensions.");
unsafe { gl::Viewport(0, 0, w as i32, h as i32) };
unsafe { gl::Clear(gl::COLOR_BUFFER_BIT) };
// #WARINING calling imgui functions that try to draw widgets
// after here (really imgui::render) will cause a segfault.
imgui_render(&demo_state);
window.swap_buffers().expect("Swapping glutin window buffers.");
}
imgui_shutdown(&mut demo_state);
} | random_line_split | |
geometry.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;
// Units for use with geom::length and geom::scale_factor.
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}
/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length. This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be
/// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
// An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Zero)]
pub struct Au(pub i32);
impl Default for Au {
#[inline]
fn default() -> Au {
Au(0)
}
}
impl fmt::Show for Au {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Au(n) = *self;
write!(f, "Au(au={} px={})", n, to_frac_px(*self))
}}
impl Add<Au,Au> for Au {
#[inline]
fn add(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s + o)
}
}
impl Sub<Au,Au> for Au {
#[inline]
fn sub(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s - o)
}
}
impl Mul<Au,Au> for Au {
#[inline]
fn mul(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s * o)
}
}
impl Div<Au,Au> for Au {
#[inline]
fn div(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s / o)
}
}
impl Rem<Au,Au> for Au {
#[inline]
fn rem(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s % o)
}
}
impl Neg<Au> for Au {
#[inline]
fn neg(&self) -> Au {
let Au(s) = *self;
Au(-s)
}
}
impl One for Au {
#[inline]
fn one() -> Au { Au(1) }
}
impl Num for Au {}
#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else | }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }
impl NumCast for Au {
#[inline]
fn from<T:ToPrimitive>(n: T) -> Option<Au> {
Some(Au(n.to_i32().unwrap()))
}
}
impl ToPrimitive for Au {
#[inline]
fn to_i64(&self) -> Option<i64> {
let Au(s) = *self;
Some(s as i64)
}
#[inline]
fn to_u64(&self) -> Option<u64> {
let Au(s) = *self;
Some(s as u64)
}
#[inline]
fn to_f32(&self) -> Option<f32> {
let Au(s) = *self;
s.to_f32()
}
#[inline]
fn to_f64(&self) -> Option<f64> {
let Au(s) = *self;
s.to_f64()
}
}
impl Au {
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
#[inline]
pub fn new(value: i32) -> Au {
Au(value)
}
#[inline]
pub fn scale_by(self, factor: f64) -> Au {
let Au(s) = self;
Au(((s as f64) * factor) as i32)
}
#[inline]
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
#[inline]
pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
NumCast::from(px.get() * 60f32).unwrap()
}
#[inline]
pub fn to_nearest_px(&self) -> int {
let Au(s) = *self;
((s as f64) / 60f64).round() as int
}
#[inline]
pub fn to_snapped(&self) -> Au {
let Au(s) = *self;
let res = s % 60i32;
return if res >= 30i32 { return Au(s - res + 60i32) }
else { return Au(s - res) };
}
#[inline]
pub fn from_frac32_px(px: f32) -> Au {
Au((px * 60f32) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
from_px(pt_to_px(pt) as int)
}
#[inline]
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
#[inline]
pub fn min(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi < yi { x } else { y }
}
#[inline]
pub fn max(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi > yi { x } else { y }
}
}
// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
pt / 72f64 * 96f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
px / 96f64 * 72f64
}
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
pub fn to_px(au: Au) -> int {
let Au(a) = au;
(a / 60) as int
}
pub fn to_frac_px(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
from_px((pt / 72f64 * 96f64) as int)
}
// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64 * 72f64 / 96f64
}
/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
}
| { y } | conditional_block |
geometry.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;
// Units for use with geom::length and geom::scale_factor.
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}
/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length. This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be
/// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
// An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Zero)]
pub struct Au(pub i32);
impl Default for Au {
#[inline]
fn default() -> Au {
Au(0)
}
}
impl fmt::Show for Au {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Au(n) = *self;
write!(f, "Au(au={} px={})", n, to_frac_px(*self))
}}
impl Add<Au,Au> for Au {
#[inline]
fn add(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s + o)
}
}
impl Sub<Au,Au> for Au {
#[inline]
fn sub(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other; | impl Mul<Au,Au> for Au {
#[inline]
fn mul(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s * o)
}
}
impl Div<Au,Au> for Au {
#[inline]
fn div(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s / o)
}
}
impl Rem<Au,Au> for Au {
#[inline]
fn rem(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s % o)
}
}
impl Neg<Au> for Au {
#[inline]
fn neg(&self) -> Au {
let Au(s) = *self;
Au(-s)
}
}
impl One for Au {
#[inline]
fn one() -> Au { Au(1) }
}
impl Num for Au {}
#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }
impl NumCast for Au {
#[inline]
fn from<T:ToPrimitive>(n: T) -> Option<Au> {
Some(Au(n.to_i32().unwrap()))
}
}
impl ToPrimitive for Au {
#[inline]
fn to_i64(&self) -> Option<i64> {
let Au(s) = *self;
Some(s as i64)
}
#[inline]
fn to_u64(&self) -> Option<u64> {
let Au(s) = *self;
Some(s as u64)
}
#[inline]
fn to_f32(&self) -> Option<f32> {
let Au(s) = *self;
s.to_f32()
}
#[inline]
fn to_f64(&self) -> Option<f64> {
let Au(s) = *self;
s.to_f64()
}
}
impl Au {
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
#[inline]
pub fn new(value: i32) -> Au {
Au(value)
}
#[inline]
pub fn scale_by(self, factor: f64) -> Au {
let Au(s) = self;
Au(((s as f64) * factor) as i32)
}
#[inline]
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
#[inline]
pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
NumCast::from(px.get() * 60f32).unwrap()
}
#[inline]
pub fn to_nearest_px(&self) -> int {
let Au(s) = *self;
((s as f64) / 60f64).round() as int
}
#[inline]
pub fn to_snapped(&self) -> Au {
let Au(s) = *self;
let res = s % 60i32;
return if res >= 30i32 { return Au(s - res + 60i32) }
else { return Au(s - res) };
}
#[inline]
pub fn from_frac32_px(px: f32) -> Au {
Au((px * 60f32) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
from_px(pt_to_px(pt) as int)
}
#[inline]
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
#[inline]
pub fn min(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi < yi { x } else { y }
}
#[inline]
pub fn max(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi > yi { x } else { y }
}
}
// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
pt / 72f64 * 96f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
px / 96f64 * 72f64
}
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
pub fn to_px(au: Au) -> int {
let Au(a) = au;
(a / 60) as int
}
pub fn to_frac_px(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
from_px((pt / 72f64 * 96f64) as int)
}
// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64 * 72f64 / 96f64
}
/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
} | Au(s - o)
}
}
| random_line_split |
geometry.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;
// Units for use with geom::length and geom::scale_factor.
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}
/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length. This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be
/// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
// An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Zero)]
pub struct Au(pub i32);
impl Default for Au {
#[inline]
fn default() -> Au {
Au(0)
}
}
impl fmt::Show for Au {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Au(n) = *self;
write!(f, "Au(au={} px={})", n, to_frac_px(*self))
}}
impl Add<Au,Au> for Au {
#[inline]
fn add(&self, other: &Au) -> Au |
}
impl Sub<Au,Au> for Au {
#[inline]
fn sub(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s - o)
}
}
impl Mul<Au,Au> for Au {
#[inline]
fn mul(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s * o)
}
}
impl Div<Au,Au> for Au {
#[inline]
fn div(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s / o)
}
}
impl Rem<Au,Au> for Au {
#[inline]
fn rem(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s % o)
}
}
impl Neg<Au> for Au {
#[inline]
fn neg(&self) -> Au {
let Au(s) = *self;
Au(-s)
}
}
impl One for Au {
#[inline]
fn one() -> Au { Au(1) }
}
impl Num for Au {}
#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }
impl NumCast for Au {
#[inline]
fn from<T:ToPrimitive>(n: T) -> Option<Au> {
Some(Au(n.to_i32().unwrap()))
}
}
impl ToPrimitive for Au {
#[inline]
fn to_i64(&self) -> Option<i64> {
let Au(s) = *self;
Some(s as i64)
}
#[inline]
fn to_u64(&self) -> Option<u64> {
let Au(s) = *self;
Some(s as u64)
}
#[inline]
fn to_f32(&self) -> Option<f32> {
let Au(s) = *self;
s.to_f32()
}
#[inline]
fn to_f64(&self) -> Option<f64> {
let Au(s) = *self;
s.to_f64()
}
}
impl Au {
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
#[inline]
pub fn new(value: i32) -> Au {
Au(value)
}
#[inline]
pub fn scale_by(self, factor: f64) -> Au {
let Au(s) = self;
Au(((s as f64) * factor) as i32)
}
#[inline]
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
#[inline]
pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
NumCast::from(px.get() * 60f32).unwrap()
}
#[inline]
pub fn to_nearest_px(&self) -> int {
let Au(s) = *self;
((s as f64) / 60f64).round() as int
}
#[inline]
pub fn to_snapped(&self) -> Au {
let Au(s) = *self;
let res = s % 60i32;
return if res >= 30i32 { return Au(s - res + 60i32) }
else { return Au(s - res) };
}
#[inline]
pub fn from_frac32_px(px: f32) -> Au {
Au((px * 60f32) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
from_px(pt_to_px(pt) as int)
}
#[inline]
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
#[inline]
pub fn min(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi < yi { x } else { y }
}
#[inline]
pub fn max(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi > yi { x } else { y }
}
}
// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
pt / 72f64 * 96f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
px / 96f64 * 72f64
}
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
pub fn to_px(au: Au) -> int {
let Au(a) = au;
(a / 60) as int
}
pub fn to_frac_px(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
from_px((pt / 72f64 * 96f64) as int)
}
// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64 * 72f64 / 96f64
}
/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
}
| {
let Au(s) = *self;
let Au(o) = *other;
Au(s + o)
} | identifier_body |
geometry.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;
// Units for use with geom::length and geom::scale_factor.
/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}
/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length. This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS. On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel. But on high-density screens it can be
/// some larger number. For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels. On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}
/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user. This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx. However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}
/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
// An Au is an "App Unit" and represents 1/60th of a CSS pixel. It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Zero)]
pub struct Au(pub i32);
impl Default for Au {
#[inline]
fn default() -> Au {
Au(0)
}
}
impl fmt::Show for Au {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let Au(n) = *self;
write!(f, "Au(au={} px={})", n, to_frac_px(*self))
}}
impl Add<Au,Au> for Au {
#[inline]
fn add(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s + o)
}
}
impl Sub<Au,Au> for Au {
#[inline]
fn sub(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s - o)
}
}
impl Mul<Au,Au> for Au {
#[inline]
fn mul(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s * o)
}
}
impl Div<Au,Au> for Au {
#[inline]
fn div(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s / o)
}
}
impl Rem<Au,Au> for Au {
#[inline]
fn rem(&self, other: &Au) -> Au {
let Au(s) = *self;
let Au(o) = *other;
Au(s % o)
}
}
impl Neg<Au> for Au {
#[inline]
fn neg(&self) -> Au {
let Au(s) = *self;
Au(-s)
}
}
impl One for Au {
#[inline]
fn one() -> Au { Au(1) }
}
impl Num for Au {}
#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }
impl NumCast for Au {
#[inline]
fn from<T:ToPrimitive>(n: T) -> Option<Au> {
Some(Au(n.to_i32().unwrap()))
}
}
impl ToPrimitive for Au {
#[inline]
fn to_i64(&self) -> Option<i64> {
let Au(s) = *self;
Some(s as i64)
}
#[inline]
fn to_u64(&self) -> Option<u64> {
let Au(s) = *self;
Some(s as u64)
}
#[inline]
fn to_f32(&self) -> Option<f32> {
let Au(s) = *self;
s.to_f32()
}
#[inline]
fn to_f64(&self) -> Option<f64> {
let Au(s) = *self;
s.to_f64()
}
}
impl Au {
/// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
#[inline]
pub fn new(value: i32) -> Au {
Au(value)
}
#[inline]
pub fn scale_by(self, factor: f64) -> Au {
let Au(s) = self;
Au(((s as f64) * factor) as i32)
}
#[inline]
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
#[inline]
pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
NumCast::from(px.get() * 60f32).unwrap()
}
#[inline]
pub fn | (&self) -> int {
let Au(s) = *self;
((s as f64) / 60f64).round() as int
}
#[inline]
pub fn to_snapped(&self) -> Au {
let Au(s) = *self;
let res = s % 60i32;
return if res >= 30i32 { return Au(s - res + 60i32) }
else { return Au(s - res) };
}
#[inline]
pub fn from_frac32_px(px: f32) -> Au {
Au((px * 60f32) as i32)
}
#[inline]
pub fn from_pt(pt: f64) -> Au {
from_px(pt_to_px(pt) as int)
}
#[inline]
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
#[inline]
pub fn min(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi < yi { x } else { y }
}
#[inline]
pub fn max(x: Au, y: Au) -> Au {
let Au(xi) = x;
let Au(yi) = y;
if xi > yi { x } else { y }
}
}
// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
pt / 72f64 * 96f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
px / 96f64 * 72f64
}
pub fn from_frac_px(px: f64) -> Au {
Au((px * 60f64) as i32)
}
pub fn from_px(px: int) -> Au {
NumCast::from(px * 60).unwrap()
}
pub fn to_px(au: Au) -> int {
let Au(a) = au;
(a / 60) as int
}
pub fn to_frac_px(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64
}
// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
from_px((pt / 72f64 * 96f64) as int)
}
// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
let Au(a) = au;
(a as f64) / 60f64 * 72f64 / 96f64
}
/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}
/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
}
| to_nearest_px | identifier_name |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::marker;
use core::mem;
use core::clone::Clone;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() |
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1);
assert_eq!(x.and(Some(2)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s, "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5;
let new_val = 11;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
/* FIXME(#20575)
#[test]
fn test_collect() {
let v: Option<Vec<int>> = (0..0).map(|_| Some(0)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = (0..3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = (0..3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions: [Box<Fn() -> Option<()>>; 3] =
[box || Some(()), box || None, box || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
*/
#[test]
fn test_cloned() {
let val1 = 1u32;
let mut val2 = 2u32;
let val1_ref = &val1;
let opt_none: Option<&'static u32> = None;
let opt_ref = Some(&val1);
let opt_ref_ref = Some(&val1_ref);
let opt_mut_ref = Some(&mut val2);
// None works
assert_eq!(opt_none.clone(), None);
assert_eq!(opt_none.cloned(), None);
// Mutable refs work
assert_eq!(opt_mut_ref.cloned(), Some(2u32));
// Immutable ref works
assert_eq!(opt_ref.clone(), Some(&val1));
assert_eq!(opt_ref.cloned(), Some(1u32));
// Double Immutable ref works
assert_eq!(opt_ref_ref.clone(), Some(&val1_ref));
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1));
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32));
}
| {
let x = "test".to_string();
let addr_x = x.as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_ptr();
assert_eq!(addr_x, addr_y);
} | identifier_body |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::marker;
use core::mem;
use core::clone::Clone;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct | {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1);
assert_eq!(x.and(Some(2)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s, "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5;
let new_val = 11;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
/* FIXME(#20575)
#[test]
fn test_collect() {
let v: Option<Vec<int>> = (0..0).map(|_| Some(0)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = (0..3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = (0..3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions: [Box<Fn() -> Option<()>>; 3] =
[box || Some(()), box || None, box || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
*/
#[test]
fn test_cloned() {
let val1 = 1u32;
let mut val2 = 2u32;
let val1_ref = &val1;
let opt_none: Option<&'static u32> = None;
let opt_ref = Some(&val1);
let opt_ref_ref = Some(&val1_ref);
let opt_mut_ref = Some(&mut val2);
// None works
assert_eq!(opt_none.clone(), None);
assert_eq!(opt_none.cloned(), None);
// Mutable refs work
assert_eq!(opt_mut_ref.cloned(), Some(2u32));
// Immutable ref works
assert_eq!(opt_ref.clone(), Some(&val1));
assert_eq!(opt_ref.cloned(), Some(1u32));
// Double Immutable ref works
assert_eq!(opt_ref_ref.clone(), Some(&val1_ref));
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1));
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32));
}
| R | identifier_name |
option.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::option::*;
use core::marker;
use core::mem;
use core::clone::Clone;
#[test]
fn test_get_ptr() {
unsafe {
let x = box 0;
let addr_x: *const int = mem::transmute(&*x);
let opt = Some(x);
let y = opt.unwrap();
let addr_y: *const int = mem::transmute(&*y);
assert_eq!(addr_x, addr_y);
}
}
#[test]
fn test_get_str() {
let x = "test".to_string();
let addr_x = x.as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_ptr();
assert_eq!(addr_x, addr_y);
}
#[test]
fn test_get_resource() {
use std::rc::Rc;
use core::cell::RefCell;
struct R {
i: Rc<RefCell<int>>,
}
#[unsafe_destructor]
impl Drop for R {
fn drop(&mut self) {
let ii = &*self.i;
let i = *ii.borrow();
*ii.borrow_mut() = i + 1;
}
}
fn r(i: Rc<RefCell<int>>) -> R {
R {
i: i
}
}
let i = Rc::new(RefCell::new(0));
{
let x = r(i.clone());
let opt = Some(x);
let _y = opt.unwrap();
}
assert_eq!(*i.borrow(), 1);
}
#[test]
fn test_option_dance() {
let x = Some(());
let mut y = Some(5);
let mut y2 = 0;
for _x in x.iter() {
y2 = y.take().unwrap();
}
assert_eq!(y2, 5);
assert!(y.is_none());
}
#[test] #[should_fail]
fn test_option_too_much_dance() {
let mut y = Some(marker::NoCopy);
let _y2 = y.take().unwrap();
let _y3 = y.take().unwrap();
}
#[test]
fn test_and() {
let x: Option<int> = Some(1);
assert_eq!(x.and(Some(2)), Some(2));
assert_eq!(x.and(None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and(Some(2)), None);
assert_eq!(x.and(None::<int>), None);
}
#[test]
fn test_and_then() {
let x: Option<int> = Some(1);
assert_eq!(x.and_then(|x| Some(x + 1)), Some(2));
assert_eq!(x.and_then(|_| None::<int>), None);
let x: Option<int> = None;
assert_eq!(x.and_then(|x| Some(x + 1)), None);
assert_eq!(x.and_then(|_| None::<int>), None);
}
#[test]
fn test_or() {
let x: Option<int> = Some(1);
assert_eq!(x.or(Some(2)), Some(1));
assert_eq!(x.or(None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or(Some(2)), Some(2));
assert_eq!(x.or(None), None);
}
#[test]
fn test_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.or_else(|| Some(2)), Some(1));
assert_eq!(x.or_else(|| None), Some(1));
let x: Option<int> = None;
assert_eq!(x.or_else(|| Some(2)), Some(2));
assert_eq!(x.or_else(|| None), None);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
let s = Some("hello".to_string()).unwrap();
assert_eq!(s, "hello");
}
#[test]
#[should_fail]
fn test_unwrap_panic1() {
let x: Option<int> = None;
x.unwrap();
}
#[test]
#[should_fail]
fn test_unwrap_panic2() {
let x: Option<String> = None;
x.unwrap();
}
#[test]
fn test_unwrap_or() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or(2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or(2), 2);
}
#[test]
fn test_unwrap_or_else() {
let x: Option<int> = Some(1);
assert_eq!(x.unwrap_or_else(|| 2), 1);
let x: Option<int> = None;
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
fn test_iter() {
let val = 5;
let x = Some(val);
let mut it = x.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next(), Some(&val));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_mut_iter() {
let val = 5;
let new_val = 11;
let mut x = Some(val);
{
let mut it = x.iter_mut();
assert_eq!(it.size_hint(), (1, Some(1)));
match it.next() {
Some(interior) => {
assert_eq!(*interior, val);
*interior = new_val;
}
None => assert!(false),
}
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
assert_eq!(x, Some(new_val));
}
#[test]
fn test_ord() {
let small = Some(1.0f64);
let big = Some(5.0f64);
let nan = Some(0.0f64/0.0);
assert!(!(nan < big));
assert!(!(nan > big));
assert!(small < big);
assert!(None < big);
assert!(big > None);
}
/* FIXME(#20575)
#[test]
fn test_collect() {
let v: Option<Vec<int>> = (0..0).map(|_| Some(0)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = (0..3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = (0..3).map(|x| { | // test that it does not take more elements than it needs
let mut functions: [Box<Fn() -> Option<()>>; 3] =
[box || Some(()), box || None, box || panic!()];
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}
*/
#[test]
fn test_cloned() {
let val1 = 1u32;
let mut val2 = 2u32;
let val1_ref = &val1;
let opt_none: Option<&'static u32> = None;
let opt_ref = Some(&val1);
let opt_ref_ref = Some(&val1_ref);
let opt_mut_ref = Some(&mut val2);
// None works
assert_eq!(opt_none.clone(), None);
assert_eq!(opt_none.cloned(), None);
// Mutable refs work
assert_eq!(opt_mut_ref.cloned(), Some(2u32));
// Immutable ref works
assert_eq!(opt_ref.clone(), Some(&val1));
assert_eq!(opt_ref.cloned(), Some(1u32));
// Double Immutable ref works
assert_eq!(opt_ref_ref.clone(), Some(&val1_ref));
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val1));
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32));
} | if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
| random_line_split |
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::{Document, DocumentHelpers};
use dom::element::AttributeHandlers;
use dom::element::ElementTypeId;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{document_from_node, Node, NodeTypeId, NodeHelpers, NodeDamage, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use script_task::{Runnable, ScriptChan, CommonScriptMsg};
use string_cache::Atom;
use util::str::DOMString;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::Image;
use net_traits::image_cache_task::{ImageResponder, ImageResponse};
use url::{Url, UrlParser};
use std::borrow::ToOwned;
use std::sync::Arc;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)))
}
}
pub trait HTMLImageElementHelpers {
fn get_url(&self) -> Option<Url>;
}
impl<'a> HTMLImageElementHelpers for &'a HTMLImageElement {
fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
*element_ref.image.borrow_mut() = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
Some(image)
}
ImageResponse::None => None,
};
// Mark the node dirty
let node = NodeCast::from_ref(element.r());
let document = document_from_node(node);
document.r().content_changed(node, NodeDamage::OtherNodeDamage);
// Fire image.onload
let window = window_from_node(document.r());
let event = Event::new(GlobalRef::Window(window.r()),
"load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let event = event.r();
let target = EventTargetCast::from_ref(node);
event.fire(target);
// Trigger reflow
window.r().add_pending_reflow();
}
}
impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node = NodeCast::from_ref(self);
let document = node.owner_doc();
let window = document.r().window();
let window = window.r();
let image_cache = window.image_cache_task();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(window.get_cx(), self, window.script_chan());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.script_chan();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script task, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
script_chan.send(CommonScriptMsg::RunnableMsg(
box ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response))).unwrap();
});
image_cache.request_image(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLImageElement, localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new("img".to_owned(), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height |
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
}
impl<'a> HTMLImageElementMethods for &'a HTMLImageElement {
make_getter!(Alt);
make_setter!(SetAlt, "alt");
make_url_getter!(Src);
make_setter!(SetSrc, "src");
make_getter!(UseMap);
make_setter!(SetUseMap, "usemap");
make_bool_getter!(IsMap);
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
fn SetIsMap(self, is_map: bool) {
let element = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(self, width: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(self, height: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/#dom-img-name
make_getter!(Name);
make_atomic_setter!(SetName, "name");
make_getter!(Align);
make_setter!(SetAlign, "align");
make_uint_getter!(Hspace);
make_uint_setter!(SetHspace, "hspace");
make_uint_getter!(Vspace);
make_uint_setter!(SetVspace, "vspace");
make_getter!(LongDesc);
make_setter!(SetLongDesc, "longdesc");
make_getter!(Border);
make_setter!(SetBorder, "border");
}
impl<'a> VirtualMethods for &'a HTMLImageElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("src") => {
let window = window_from_node(*self);
let url = window.r().get_url();
self.update_image(Some(((**attr.value()).to_owned(), &url)));
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("src") => self.update_image(None),
_ => ()
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") |
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
| {
image.SetHeight(h);
} | conditional_block |
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::{Document, DocumentHelpers};
use dom::element::AttributeHandlers;
use dom::element::ElementTypeId;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{document_from_node, Node, NodeTypeId, NodeHelpers, NodeDamage, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use script_task::{Runnable, ScriptChan, CommonScriptMsg};
use string_cache::Atom;
use util::str::DOMString;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::Image;
use net_traits::image_cache_task::{ImageResponder, ImageResponse};
use url::{Url, UrlParser};
use std::borrow::ToOwned;
use std::sync::Arc;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)))
}
}
pub trait HTMLImageElementHelpers {
fn get_url(&self) -> Option<Url>;
}
impl<'a> HTMLImageElementHelpers for &'a HTMLImageElement {
fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
*element_ref.image.borrow_mut() = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
Some(image)
}
ImageResponse::None => None,
};
// Mark the node dirty
let node = NodeCast::from_ref(element.r());
let document = document_from_node(node);
document.r().content_changed(node, NodeDamage::OtherNodeDamage);
// Fire image.onload
let window = window_from_node(document.r());
let event = Event::new(GlobalRef::Window(window.r()),
"load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let event = event.r();
let target = EventTargetCast::from_ref(node);
event.fire(target);
// Trigger reflow
window.r().add_pending_reflow();
}
}
impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node = NodeCast::from_ref(self);
let document = node.owner_doc();
let window = document.r().window();
let window = window.r();
let image_cache = window.image_cache_task();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(window.get_cx(), self, window.script_chan());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.script_chan();
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script task, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
script_chan.send(CommonScriptMsg::RunnableMsg(
box ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response))).unwrap();
});
image_cache.request_image(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLImageElement, localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new("img".to_owned(), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
}
impl<'a> HTMLImageElementMethods for &'a HTMLImageElement {
make_getter!(Alt);
make_setter!(SetAlt, "alt");
make_url_getter!(Src);
make_setter!(SetSrc, "src");
make_getter!(UseMap);
make_setter!(SetUseMap, "usemap");
make_bool_getter!(IsMap);
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
fn SetIsMap(self, is_map: bool) {
let element = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(self, width: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(self, height: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/#dom-img-name
make_getter!(Name);
make_atomic_setter!(SetName, "name");
make_getter!(Align);
make_setter!(SetAlign, "align");
make_uint_getter!(Hspace);
make_uint_setter!(SetHspace, "hspace");
make_uint_getter!(Vspace);
make_uint_setter!(SetVspace, "vspace");
make_getter!(LongDesc);
make_setter!(SetLongDesc, "longdesc");
make_getter!(Border);
make_setter!(SetBorder, "border");
}
impl<'a> VirtualMethods for &'a HTMLImageElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("src") => {
let window = window_from_node(*self);
let url = window.r().get_url();
self.update_image(Some(((**attr.value()).to_owned(), &url)));
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("src") => self.update_image(None),
_ => ()
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") |
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
| new | identifier_name |
htmlimageelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::{AttrHelpers, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding;
use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLImageElementDerived};
use dom::bindings::codegen::InheritTypes::{NodeCast, ElementCast, EventTargetCast};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::refcounted::Trusted;
use dom::document::{Document, DocumentHelpers};
use dom::element::AttributeHandlers;
use dom::element::ElementTypeId;
use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers};
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{document_from_node, Node, NodeTypeId, NodeHelpers, NodeDamage, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use script_task::{Runnable, ScriptChan, CommonScriptMsg};
use string_cache::Atom;
use util::str::DOMString;
use ipc_channel::ipc;
use ipc_channel::router::ROUTER;
use net_traits::image::base::Image;
use net_traits::image_cache_task::{ImageResponder, ImageResponse};
use url::{Url, UrlParser};
use std::borrow::ToOwned;
use std::sync::Arc;
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct HTMLImageElement {
htmlelement: HTMLElement,
url: DOMRefCell<Option<Url>>,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLImageElementDerived for EventTarget {
fn is_htmlimageelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)))
}
}
pub trait HTMLImageElementHelpers {
fn get_url(&self) -> Option<Url>;
}
impl<'a> HTMLImageElementHelpers for &'a HTMLImageElement {
fn get_url(&self) -> Option<Url>{
self.url.borrow().clone()
}
}
trait PrivateHTMLImageElementHelpers {
fn update_image(self, value: Option<(DOMString, &Url)>);
}
struct ImageResponseHandlerRunnable {
element: Trusted<HTMLImageElement>,
image: ImageResponse,
}
impl ImageResponseHandlerRunnable {
fn new(element: Trusted<HTMLImageElement>, image: ImageResponse)
-> ImageResponseHandlerRunnable {
ImageResponseHandlerRunnable {
element: element,
image: image,
}
}
}
impl Runnable for ImageResponseHandlerRunnable {
fn handler(self: Box<Self>) {
// Update the image field
let element = self.element.root();
let element_ref = element.r();
*element_ref.image.borrow_mut() = match self.image {
ImageResponse::Loaded(image) | ImageResponse::PlaceholderLoaded(image) => {
Some(image)
}
ImageResponse::None => None,
};
// Mark the node dirty
let node = NodeCast::from_ref(element.r());
let document = document_from_node(node);
document.r().content_changed(node, NodeDamage::OtherNodeDamage);
// Fire image.onload
let window = window_from_node(document.r());
let event = Event::new(GlobalRef::Window(window.r()),
"load".to_owned(),
EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable);
let event = event.r();
let target = EventTargetCast::from_ref(node);
event.fire(target);
// Trigger reflow
window.r().add_pending_reflow();
}
}
impl<'a> PrivateHTMLImageElementHelpers for &'a HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed.
fn update_image(self, value: Option<(DOMString, &Url)>) {
let node = NodeCast::from_ref(self);
let document = node.owner_doc();
let window = document.r().window();
let window = window.r();
let image_cache = window.image_cache_task();
match value {
None => {
*self.url.borrow_mut() = None;
*self.image.borrow_mut() = None;
}
Some((src, base_url)) => {
let img_url = UrlParser::new().base_url(base_url).parse(&src);
// FIXME: handle URL parse errors more gracefully.
let img_url = img_url.unwrap();
*self.url.borrow_mut() = Some(img_url.clone());
let trusted_node = Trusted::new(window.get_cx(), self, window.script_chan());
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let script_chan = window.script_chan(); | ROUTER.add_route(responder_receiver.to_opaque(), box move |message| {
// Return the image via a message to the script task, which marks the element
// as dirty and triggers a reflow.
let image_response = message.to().unwrap();
script_chan.send(CommonScriptMsg::RunnableMsg(
box ImageResponseHandlerRunnable::new(
trusted_node.clone(), image_response))).unwrap();
});
image_cache.request_image(img_url,
window.image_cache_chan(),
Some(ImageResponder::new(responder_sender)));
}
}
}
}
impl HTMLImageElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLImageElement {
HTMLImageElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLImageElement, localName, prefix, document),
url: DOMRefCell::new(None),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLImageElement> {
let element = HTMLImageElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap)
}
pub fn Image(global: GlobalRef,
width: Option<u32>,
height: Option<u32>) -> Fallible<Root<HTMLImageElement>> {
let document = global.as_window().Document();
let image = HTMLImageElement::new("img".to_owned(), None, document.r());
if let Some(w) = width {
image.SetWidth(w);
}
if let Some(h) = height {
image.SetHeight(h);
}
Ok(image)
}
}
pub trait LayoutHTMLImageElementHelpers {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>>;
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url>;
}
impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> {
#[allow(unsafe_code)]
unsafe fn image(&self) -> Option<Arc<Image>> {
(*self.unsafe_get()).image.borrow_for_layout().clone()
}
#[allow(unsafe_code)]
unsafe fn image_url(&self) -> Option<Url> {
(*self.unsafe_get()).url.borrow_for_layout().clone()
}
}
impl<'a> HTMLImageElementMethods for &'a HTMLImageElement {
make_getter!(Alt);
make_setter!(SetAlt, "alt");
make_url_getter!(Src);
make_setter!(SetSrc, "src");
make_getter!(UseMap);
make_setter!(SetUseMap, "usemap");
make_bool_getter!(IsMap);
// https://html.spec.whatwg.org/multipage/#dom-img-ismap
fn SetIsMap(self, is_map: bool) {
let element = ElementCast::from_ref(self);
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn Width(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.width.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(self, width: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("width"), width)
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn Height(self) -> u32 {
let node = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box();
rect.size.height.to_px() as u32
}
// https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(self, height: u32) {
let elem = ElementCast::from_ref(self);
elem.set_uint_attribute(&atom!("height"), height)
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
fn NaturalWidth(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.width,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-naturalheight
fn NaturalHeight(self) -> u32 {
let image = self.image.borrow();
match *image {
Some(ref image) => image.height,
None => 0,
}
}
// https://html.spec.whatwg.org/multipage/#dom-img-complete
fn Complete(self) -> bool {
let image = self.image.borrow();
image.is_some()
}
// https://html.spec.whatwg.org/#dom-img-name
make_getter!(Name);
make_atomic_setter!(SetName, "name");
make_getter!(Align);
make_setter!(SetAlign, "align");
make_uint_getter!(Hspace);
make_uint_setter!(SetHspace, "hspace");
make_uint_getter!(Vspace);
make_uint_setter!(SetVspace, "vspace");
make_getter!(LongDesc);
make_setter!(SetLongDesc, "longdesc");
make_getter!(Border);
make_setter!(SetBorder, "border");
}
impl<'a> VirtualMethods for &'a HTMLImageElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &&HTMLElement = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("src") => {
let window = window_from_node(*self);
let url = window.r().get_url();
self.update_image(Some(((**attr.value()).to_owned(), &url)));
},
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("src") => self.update_image(None),
_ => ()
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atomic(value),
&atom!("width") | &atom!("height") |
&atom!("hspace") | &atom!("vspace") => AttrValue::from_u32(value, 0),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
} | random_line_split | |
os_str.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// The underlying OsString/OsStr implementation on Unix systems: just
/// a `Vec<u8>`/`[u8]`.
use borrow::Cow;
use fmt;
use str;
use mem;
use rc::Rc;
use sync::Arc;
use sys_common::{AsInner, IntoInner};
use sys_common::bytestring::debug_fmt_bytestring;
use core::str::lossy::Utf8Lossy;
#[derive(Clone, Hash)]
pub struct Buf {
pub inner: Vec<u8>
}
pub struct Slice {
pub inner: [u8]
}
impl fmt::Debug for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
debug_fmt_bytestring(&self.inner, formatter)
}
}
impl fmt::Display for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter)
}
}
impl fmt::Debug for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_slice(), formatter)
}
}
impl fmt::Display for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_slice(), formatter)
}
}
impl IntoInner<Vec<u8>> for Buf {
fn into_inner(self) -> Vec<u8> {
self.inner
}
}
impl AsInner<[u8]> for Buf {
fn as_inner(&self) -> &[u8] {
&self.inner
}
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: s.into_bytes() }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Buf {
Buf {
inner: Vec::with_capacity(capacity)
}
}
#[inline]
pub fn clear(&mut self) {
self.inner.clear()
}
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.inner.shrink_to(min_capacity)
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(&*self.inner) }
}
pub fn into_string(self) -> Result<String, Buf> {
String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } )
}
pub fn push_slice(&mut self, s: &Slice) {
self.inner.extend_from_slice(&s.inner)
}
#[inline]
pub fn into_box(self) -> Box<Slice> {
unsafe { mem::transmute(self.inner.into_boxed_slice()) }
}
#[inline]
pub fn from_box(boxed: Box<Slice>) -> Buf {
let inner: Box<[u8]> = unsafe { mem::transmute(boxed) };
Buf { inner: inner.into_vec() }
}
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
self.as_slice().into_arc()
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
self.as_slice().into_rc()
}
}
impl Slice {
fn from_u8_slice(s: &[u8]) -> &Slice {
unsafe { mem::transmute(s) }
}
pub fn from_str(s: &str) -> &Slice {
Slice::from_u8_slice(s.as_bytes())
}
pub fn to_str(&self) -> Option<&str> {
str::from_utf8(&self.inner).ok()
}
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(&self.inner)
}
pub fn to_owned(&self) -> Buf {
Buf { inner: self.inner.to_vec() }
}
#[inline]
pub fn into_box(&self) -> Box<Slice> {
let boxed: Box<[u8]> = self.inner.into();
unsafe { mem::transmute(boxed) }
}
pub fn empty_box() -> Box<Slice> |
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
let arc: Arc<[u8]> = Arc::from(&self.inner);
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) }
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
let rc: Rc<[u8]> = Rc::from(&self.inner);
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) }
}
}
| {
let boxed: Box<[u8]> = Default::default();
unsafe { mem::transmute(boxed) }
} | identifier_body |
os_str.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// The underlying OsString/OsStr implementation on Unix systems: just
/// a `Vec<u8>`/`[u8]`.
use borrow::Cow;
use fmt;
use str;
use mem;
use rc::Rc;
use sync::Arc;
use sys_common::{AsInner, IntoInner};
use sys_common::bytestring::debug_fmt_bytestring;
use core::str::lossy::Utf8Lossy;
#[derive(Clone, Hash)]
pub struct Buf {
pub inner: Vec<u8>
}
pub struct Slice {
pub inner: [u8]
}
impl fmt::Debug for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
debug_fmt_bytestring(&self.inner, formatter)
}
}
impl fmt::Display for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter)
}
}
impl fmt::Debug for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_slice(), formatter)
}
}
impl fmt::Display for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_slice(), formatter)
}
}
impl IntoInner<Vec<u8>> for Buf {
fn into_inner(self) -> Vec<u8> {
self.inner
}
}
impl AsInner<[u8]> for Buf {
fn as_inner(&self) -> &[u8] {
&self.inner
}
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: s.into_bytes() }
}
#[inline]
pub fn with_capacity(capacity: usize) -> Buf {
Buf {
inner: Vec::with_capacity(capacity)
}
}
#[inline]
pub fn clear(&mut self) {
self.inner.clear()
}
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.inner.shrink_to(min_capacity)
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(&*self.inner) }
}
pub fn into_string(self) -> Result<String, Buf> {
String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } )
}
pub fn push_slice(&mut self, s: &Slice) {
self.inner.extend_from_slice(&s.inner)
}
#[inline]
pub fn into_box(self) -> Box<Slice> {
unsafe { mem::transmute(self.inner.into_boxed_slice()) }
}
#[inline]
pub fn from_box(boxed: Box<Slice>) -> Buf {
let inner: Box<[u8]> = unsafe { mem::transmute(boxed) };
Buf { inner: inner.into_vec() }
}
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
self.as_slice().into_arc()
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
self.as_slice().into_rc()
}
}
impl Slice {
fn from_u8_slice(s: &[u8]) -> &Slice {
unsafe { mem::transmute(s) }
}
pub fn from_str(s: &str) -> &Slice {
Slice::from_u8_slice(s.as_bytes()) |
pub fn to_str(&self) -> Option<&str> {
str::from_utf8(&self.inner).ok()
}
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(&self.inner)
}
pub fn to_owned(&self) -> Buf {
Buf { inner: self.inner.to_vec() }
}
#[inline]
pub fn into_box(&self) -> Box<Slice> {
let boxed: Box<[u8]> = self.inner.into();
unsafe { mem::transmute(boxed) }
}
pub fn empty_box() -> Box<Slice> {
let boxed: Box<[u8]> = Default::default();
unsafe { mem::transmute(boxed) }
}
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
let arc: Arc<[u8]> = Arc::from(&self.inner);
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) }
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
let rc: Rc<[u8]> = Rc::from(&self.inner);
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) }
}
} | } | random_line_split |
os_str.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// The underlying OsString/OsStr implementation on Unix systems: just
/// a `Vec<u8>`/`[u8]`.
use borrow::Cow;
use fmt;
use str;
use mem;
use rc::Rc;
use sync::Arc;
use sys_common::{AsInner, IntoInner};
use sys_common::bytestring::debug_fmt_bytestring;
use core::str::lossy::Utf8Lossy;
#[derive(Clone, Hash)]
pub struct Buf {
pub inner: Vec<u8>
}
pub struct Slice {
pub inner: [u8]
}
impl fmt::Debug for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
debug_fmt_bytestring(&self.inner, formatter)
}
}
impl fmt::Display for Slice {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter)
}
}
impl fmt::Debug for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self.as_slice(), formatter)
}
}
impl fmt::Display for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self.as_slice(), formatter)
}
}
impl IntoInner<Vec<u8>> for Buf {
fn into_inner(self) -> Vec<u8> {
self.inner
}
}
impl AsInner<[u8]> for Buf {
fn as_inner(&self) -> &[u8] {
&self.inner
}
}
impl Buf {
pub fn from_string(s: String) -> Buf {
Buf { inner: s.into_bytes() }
}
#[inline]
pub fn | (capacity: usize) -> Buf {
Buf {
inner: Vec::with_capacity(capacity)
}
}
#[inline]
pub fn clear(&mut self) {
self.inner.clear()
}
#[inline]
pub fn capacity(&self) -> usize {
self.inner.capacity()
}
#[inline]
pub fn reserve(&mut self, additional: usize) {
self.inner.reserve(additional)
}
#[inline]
pub fn reserve_exact(&mut self, additional: usize) {
self.inner.reserve_exact(additional)
}
#[inline]
pub fn shrink_to_fit(&mut self) {
self.inner.shrink_to_fit()
}
#[inline]
pub fn shrink_to(&mut self, min_capacity: usize) {
self.inner.shrink_to(min_capacity)
}
pub fn as_slice(&self) -> &Slice {
unsafe { mem::transmute(&*self.inner) }
}
pub fn into_string(self) -> Result<String, Buf> {
String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } )
}
pub fn push_slice(&mut self, s: &Slice) {
self.inner.extend_from_slice(&s.inner)
}
#[inline]
pub fn into_box(self) -> Box<Slice> {
unsafe { mem::transmute(self.inner.into_boxed_slice()) }
}
#[inline]
pub fn from_box(boxed: Box<Slice>) -> Buf {
let inner: Box<[u8]> = unsafe { mem::transmute(boxed) };
Buf { inner: inner.into_vec() }
}
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
self.as_slice().into_arc()
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
self.as_slice().into_rc()
}
}
impl Slice {
fn from_u8_slice(s: &[u8]) -> &Slice {
unsafe { mem::transmute(s) }
}
pub fn from_str(s: &str) -> &Slice {
Slice::from_u8_slice(s.as_bytes())
}
pub fn to_str(&self) -> Option<&str> {
str::from_utf8(&self.inner).ok()
}
pub fn to_string_lossy(&self) -> Cow<str> {
String::from_utf8_lossy(&self.inner)
}
pub fn to_owned(&self) -> Buf {
Buf { inner: self.inner.to_vec() }
}
#[inline]
pub fn into_box(&self) -> Box<Slice> {
let boxed: Box<[u8]> = self.inner.into();
unsafe { mem::transmute(boxed) }
}
pub fn empty_box() -> Box<Slice> {
let boxed: Box<[u8]> = Default::default();
unsafe { mem::transmute(boxed) }
}
#[inline]
pub fn into_arc(&self) -> Arc<Slice> {
let arc: Arc<[u8]> = Arc::from(&self.inner);
unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) }
}
#[inline]
pub fn into_rc(&self) -> Rc<Slice> {
let rc: Rc<[u8]> = Rc::from(&self.inner);
unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) }
}
}
| with_capacity | identifier_name |
i_renderobj.rs | extern crate mazth;
use std::collections::HashMap;
use self::mazth::mat::{ Mat4, Mat3x1 };
use implement::render::renderdevice_gl::RenderUniformCollection;
pub trait Xform {
fn get_xform() -> Mat4< f32 >;
}
pub trait ObjPos {
fn get_pos( & self ) -> Mat3x1< f32 >;
}
#[derive(Debug)]
#[derive(Clone)]
#[derive(Copy)]
pub enum RenderObjType {
TRI,
//todo
QUAD,
POINT,
LINE,
}
#[derive(Debug)]
#[derive(Clone)]
#[derive(Copy)]
#[derive(Eq)]
#[derive(Hash)]
#[derive(PartialEq)]
pub enum BuffDataType {
POS,
NORMAL,
TC,
}
pub trait RenderDevice {
fn bind_buffer( & mut self ) -> Result< (), &'static str >;
fn draw_buffer_all( & mut self ) -> Result< (), &'static str >;
fn draw_buffer_range( & mut self ) -> Result< (), &'static str >;
fn store_buff_data( & mut self, data: & HashMap< BuffDataType, Vec< f32 > > ) -> Result< (), &'static str >;
fn clear_buff_data( & mut self );
}
pub trait IRenderBuffer {
fn load_into_buffer( & mut self, rd: & mut RenderDevice ) -> Result< (), &'static str >;
}
pub enum | {
ADS,
PBR,
NONE,
}
pub trait IRenderable : IRenderBuffer {
fn get_render_method( & self ) -> RenderMethod;
}
pub trait IRenderUniform {
fn load_into_uniform( & mut self, uniforms: & mut RenderUniformCollection ) -> Result< (), &'static str >;
}
| RenderMethod | identifier_name |
i_renderobj.rs | extern crate mazth;
use std::collections::HashMap;
use self::mazth::mat::{ Mat4, Mat3x1 };
use implement::render::renderdevice_gl::RenderUniformCollection;
pub trait Xform {
fn get_xform() -> Mat4< f32 >;
}
pub trait ObjPos {
fn get_pos( & self ) -> Mat3x1< f32 >; |
#[derive(Debug)]
#[derive(Clone)]
#[derive(Copy)]
pub enum RenderObjType {
TRI,
//todo
QUAD,
POINT,
LINE,
}
#[derive(Debug)]
#[derive(Clone)]
#[derive(Copy)]
#[derive(Eq)]
#[derive(Hash)]
#[derive(PartialEq)]
pub enum BuffDataType {
POS,
NORMAL,
TC,
}
pub trait RenderDevice {
fn bind_buffer( & mut self ) -> Result< (), &'static str >;
fn draw_buffer_all( & mut self ) -> Result< (), &'static str >;
fn draw_buffer_range( & mut self ) -> Result< (), &'static str >;
fn store_buff_data( & mut self, data: & HashMap< BuffDataType, Vec< f32 > > ) -> Result< (), &'static str >;
fn clear_buff_data( & mut self );
}
pub trait IRenderBuffer {
fn load_into_buffer( & mut self, rd: & mut RenderDevice ) -> Result< (), &'static str >;
}
pub enum RenderMethod {
ADS,
PBR,
NONE,
}
pub trait IRenderable : IRenderBuffer {
fn get_render_method( & self ) -> RenderMethod;
}
pub trait IRenderUniform {
fn load_into_uniform( & mut self, uniforms: & mut RenderUniformCollection ) -> Result< (), &'static str >;
} | } | random_line_split |
cast-rfc0401-vtable-kinds.rs | // Check that you can cast between different pointers to trait objects
// whose vtable have the same kind (both lengths, or both trait pointers).
trait Foo<T> {
fn foo(&self, _: T) -> u32 { 42 }
}
trait Bar {
fn | (&self) { println!("Bar!"); }
}
impl<T> Foo<T> for () {}
impl Foo<u32> for u32 { fn foo(&self, _: u32) -> u32 { self+43 } }
impl Bar for () {}
unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32>+'a)) -> u32 {
let foo_e : *const dyn Foo<u16> = t as *const _;
let r_1 = foo_e as *mut dyn Foo<u32>;
(&*r_1).foo(0)
}
#[repr(C)]
struct FooS<T:?Sized>(T);
#[repr(C)]
struct BarS<T:?Sized>(T);
fn foo_to_bar<T:?Sized>(u: *const FooS<T>) -> *const BarS<T> {
u as *const BarS<T>
}
fn main() {
let x = 4u32;
let y : &dyn Foo<u32> = &x;
let fl = unsafe { round_trip_and_call(y as *const dyn Foo<u32>) };
assert_eq!(fl, (43+4));
let s = FooS([0,1,2]);
let u: &FooS<[u32]> = &s;
let u: *const FooS<[u32]> = u;
let bar_ref : *const BarS<[u32]> = foo_to_bar(u);
let z : &BarS<[u32]> = unsafe{&*bar_ref};
assert_eq!(&z.0, &[0,1,2]);
// If validation fails here, that's likely because an immutable suspension is recovered mutably.
}
| bar | identifier_name |
cast-rfc0401-vtable-kinds.rs | // Check that you can cast between different pointers to trait objects
// whose vtable have the same kind (both lengths, or both trait pointers).
trait Foo<T> {
fn foo(&self, _: T) -> u32 { 42 }
}
trait Bar {
fn bar(&self) { println!("Bar!"); }
}
impl<T> Foo<T> for () {}
impl Foo<u32> for u32 { fn foo(&self, _: u32) -> u32 { self+43 } }
impl Bar for () {}
unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32>+'a)) -> u32 {
let foo_e : *const dyn Foo<u16> = t as *const _;
let r_1 = foo_e as *mut dyn Foo<u32>;
(&*r_1).foo(0)
}
#[repr(C)]
struct FooS<T:?Sized>(T);
#[repr(C)]
struct BarS<T:?Sized>(T);
fn foo_to_bar<T:?Sized>(u: *const FooS<T>) -> *const BarS<T> { | }
fn main() {
let x = 4u32;
let y : &dyn Foo<u32> = &x;
let fl = unsafe { round_trip_and_call(y as *const dyn Foo<u32>) };
assert_eq!(fl, (43+4));
let s = FooS([0,1,2]);
let u: &FooS<[u32]> = &s;
let u: *const FooS<[u32]> = u;
let bar_ref : *const BarS<[u32]> = foo_to_bar(u);
let z : &BarS<[u32]> = unsafe{&*bar_ref};
assert_eq!(&z.0, &[0,1,2]);
// If validation fails here, that's likely because an immutable suspension is recovered mutably.
} | u as *const BarS<T> | random_line_split |
issue-17718-const-borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::UnsafeCell;
const A: UnsafeCell<usize> = UnsafeCell::new(1);
const B: &'static UnsafeCell<usize> = &A;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
struct | { a: UnsafeCell<usize> }
const D: C = C { a: UnsafeCell::new(1) };
const E: &'static UnsafeCell<usize> = &D.a;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
const F: &'static C = &D;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
fn main() {}
| C | identifier_name |
issue-17718-const-borrow.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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::cell::UnsafeCell;
const A: UnsafeCell<usize> = UnsafeCell::new(1);
const B: &'static UnsafeCell<usize> = &A;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
struct C { a: UnsafeCell<usize> }
const D: C = C { a: UnsafeCell::new(1) };
const E: &'static UnsafeCell<usize> = &D.a;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
const F: &'static C = &D;
//~^ ERROR: cannot borrow a constant which may contain interior mutability
fn main() {} | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
json_codegen_test.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>>
*/
mod json_codegen;
use json_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn kitchen_sink() |
#[test]
fn stable_literals() {
let input = include_str!("json_codegen/fixtures/stable-literals.graphql");
let expected = include_str!("json_codegen/fixtures/stable-literals.expected");
test_fixture(transform_fixture, "stable-literals.graphql", "json_codegen/fixtures/stable-literals.expected", input, expected);
}
| {
let input = include_str!("json_codegen/fixtures/kitchen-sink.graphql");
let expected = include_str!("json_codegen/fixtures/kitchen-sink.expected");
test_fixture(transform_fixture, "kitchen-sink.graphql", "json_codegen/fixtures/kitchen-sink.expected", input, expected);
} | identifier_body |
json_codegen_test.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>>
*/
mod json_codegen; | fn kitchen_sink() {
let input = include_str!("json_codegen/fixtures/kitchen-sink.graphql");
let expected = include_str!("json_codegen/fixtures/kitchen-sink.expected");
test_fixture(transform_fixture, "kitchen-sink.graphql", "json_codegen/fixtures/kitchen-sink.expected", input, expected);
}
#[test]
fn stable_literals() {
let input = include_str!("json_codegen/fixtures/stable-literals.graphql");
let expected = include_str!("json_codegen/fixtures/stable-literals.expected");
test_fixture(transform_fixture, "stable-literals.graphql", "json_codegen/fixtures/stable-literals.expected", input, expected);
} |
use json_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test] | random_line_split |
json_codegen_test.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>>
*/
mod json_codegen;
use json_codegen::transform_fixture;
use fixture_tests::test_fixture;
#[test]
fn kitchen_sink() {
let input = include_str!("json_codegen/fixtures/kitchen-sink.graphql");
let expected = include_str!("json_codegen/fixtures/kitchen-sink.expected");
test_fixture(transform_fixture, "kitchen-sink.graphql", "json_codegen/fixtures/kitchen-sink.expected", input, expected);
}
#[test]
fn | () {
let input = include_str!("json_codegen/fixtures/stable-literals.graphql");
let expected = include_str!("json_codegen/fixtures/stable-literals.expected");
test_fixture(transform_fixture, "stable-literals.graphql", "json_codegen/fixtures/stable-literals.expected", input, expected);
}
| stable_literals | identifier_name |
print.rs | fn main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positional
// arguments can be used.
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
// As can named arguments.
println!("{subject} {verb} {object}",
object="the lazy dog", | // Special formatting can be specified after a `:`.
println!("{} of {:b} people know binary, the other half don't", 1, 2);
// You can right-align text with a specified width. This will output
// " 1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);
// It will even check to make sure the correct number of arguments are
// used.
println!("My name is {0}, {1} {0}", "Bond");
// FIXME ^ Add the missing argument: "James"
// Create a structure which contains an `i32`. Name it `Structure`.
struct Structure(i32);
// However, custom types such as this structure require more complicated
// handling. This will not work.
println!("This struct `{}` won't print...", Structure(3));
// FIXME ^ Comment out this line.
} | subject="the quick brown fox",
verb="jumps over");
| random_line_split |
print.rs | fn main() {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positional
// arguments can be used.
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
// As can named arguments.
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
// Special formatting can be specified after a `:`.
println!("{} of {:b} people know binary, the other half don't", 1, 2);
// You can right-align text with a specified width. This will output
// " 1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);
// It will even check to make sure the correct number of arguments are
// used.
println!("My name is {0}, {1} {0}", "Bond");
// FIXME ^ Add the missing argument: "James"
// Create a structure which contains an `i32`. Name it `Structure`.
struct | (i32);
// However, custom types such as this structure require more complicated
// handling. This will not work.
println!("This struct `{}` won't print...", Structure(3));
// FIXME ^ Comment out this line.
}
| Structure | identifier_name |
print.rs | fn main() |
// You can right-align text with a specified width. This will output
// " 1". 5 white spaces and a "1".
println!("{number:>width$}", number=1, width=6);
// You can pad numbers with extra zeroes. This will output "000001".
println!("{number:>0width$}", number=1, width=6);
// It will even check to make sure the correct number of arguments are
// used.
println!("My name is {0}, {1} {0}", "Bond");
// FIXME ^ Add the missing argument: "James"
// Create a structure which contains an `i32`. Name it `Structure`.
struct Structure(i32);
// However, custom types such as this structure require more complicated
// handling. This will not work.
println!("This struct `{}` won't print...", Structure(3));
// FIXME ^ Comment out this line.
}
| {
// In general, the `{}` will be automatically replaced with any
// arguments. These will be stringified.
println!("{} days", 31);
// Without a suffix, 31 becomes an i32. You can change what type 31 is,
// with a suffix.
// There are various optional patterns this works with. Positional
// arguments can be used.
println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
// As can named arguments.
println!("{subject} {verb} {object}",
object="the lazy dog",
subject="the quick brown fox",
verb="jumps over");
// Special formatting can be specified after a `:`.
println!("{} of {:b} people know binary, the other half don't", 1, 2); | identifier_body |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure status.
fn execute(&mut self) -> io::Result<()> {
let status = try!(self.status());
if status.success() {
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, format!("The command\n\
\t{:?}\n\
did not run successfully.", self)))
}
}
}
/// The command to build lua, with switches for different OSes.
fn build_lua(tooling: &gcc::Tool, source: &Path, build: &Path) -> io::Result<()> {
// calculate the Lua platform name
let platform = match env::var("TARGET").unwrap().split('-').nth(2).unwrap() {
"windows" => "mingw",
"macos" => "macosx",
"linux" => "linux",
"freebsd" => "freebsd",
"dragonfly" => "bsd",
// fall back to the "generic" system
_ => "generic",
};
// extract CC and MYCFLAGS from the detected tooling
let cc = tooling.path();
let mut cflags = OsString::new();
for arg in tooling.args() {
cflags.push(arg);
cflags.push(" ");
}
// VPATH is used to invoke "make" from the directory where we want Lua to
// be built into, but read the sources from the provided source directory.
// Setting MAKE to match the command we invoke means that the VPATH and
// Makefile path will be carried over when the Makefile invokes itself.
let makefile = source.join("Makefile");
let make = OsString::from(format!("make -e -f {:?}", makefile.to_string_lossy().replace("\\", "/")));
// call the makefile
let mut command = Command::new("make");
for &(ref key, ref val) in tooling.env() {
command.env(key, val);
}
command.current_dir(build)
.env("VPATH", source.to_string_lossy().replace("\\", "/"))
.env("MAKE", make)
.env("CC", cc)
.env("MYCFLAGS", cflags)
.arg("-e")
.arg("-f").arg(makefile)
.arg(platform)
.execute()
}
/// If a static Lua is not yet available from a prior run of this script, this
/// will download Lua and build it. The cargo configuration text to link
/// statically against lua.a is then printed to stdout.
fn prebuild() -> io::Result<()> | if!build_dir.join("liblua.a").exists() {
let tooling = config.get_compiler();
try!(fs::create_dir_all(&build_dir));
try!(build_lua(&tooling, &lua_dir, &build_dir));
}
println!("cargo:rustc-link-search=native={}", build_dir.display());
}
// Ensure the presence of glue.rs
if!build_dir.join("glue.rs").exists() {
// Compile and run glue.c
let glue = build_dir.join("glue");
try!(config.include(&lua_dir).get_compiler().to_command()
.arg("-I").arg(&lua_dir)
.arg("src/glue/glue.c")
.arg("-o").arg(&glue)
.execute());
try!(Command::new(glue)
.arg(build_dir.join("glue.rs"))
.execute());
}
Ok(())
}
fn main() {
match prebuild() {
Err(e) => panic!("Error: {}", e),
Ok(()) => (),
}
}
| {
let lua_dir = match env::var_os("LUA_LOCAL_SOURCE") {
// If LUA_LOCAL_SOURCE is set, use it
Some(dir) => PathBuf::from(dir),
// Otherwise, pull from lua-source/src in the crate root
None => {
let mut dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
dir.push("lua-source/src");
dir
}
};
let build_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let mut config = gcc::Config::new();
println!("cargo:rustc-link-lib=static=lua");
if lua_dir.join("liblua.a").exists() {
// If liblua.a is already in lua_dir, use it
println!("cargo:rustc-link-search=native={}", lua_dir.display());
} else {
// Otherwise, build from lua_dir into build_dir | identifier_body |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure status.
fn execute(&mut self) -> io::Result<()> {
let status = try!(self.status());
if status.success() {
Ok(()) | Err(io::Error::new(io::ErrorKind::Other, format!("The command\n\
\t{:?}\n\
did not run successfully.", self)))
}
}
}
/// The command to build lua, with switches for different OSes.
fn build_lua(tooling: &gcc::Tool, source: &Path, build: &Path) -> io::Result<()> {
// calculate the Lua platform name
let platform = match env::var("TARGET").unwrap().split('-').nth(2).unwrap() {
"windows" => "mingw",
"macos" => "macosx",
"linux" => "linux",
"freebsd" => "freebsd",
"dragonfly" => "bsd",
// fall back to the "generic" system
_ => "generic",
};
// extract CC and MYCFLAGS from the detected tooling
let cc = tooling.path();
let mut cflags = OsString::new();
for arg in tooling.args() {
cflags.push(arg);
cflags.push(" ");
}
// VPATH is used to invoke "make" from the directory where we want Lua to
// be built into, but read the sources from the provided source directory.
// Setting MAKE to match the command we invoke means that the VPATH and
// Makefile path will be carried over when the Makefile invokes itself.
let makefile = source.join("Makefile");
let make = OsString::from(format!("make -e -f {:?}", makefile.to_string_lossy().replace("\\", "/")));
// call the makefile
let mut command = Command::new("make");
for &(ref key, ref val) in tooling.env() {
command.env(key, val);
}
command.current_dir(build)
.env("VPATH", source.to_string_lossy().replace("\\", "/"))
.env("MAKE", make)
.env("CC", cc)
.env("MYCFLAGS", cflags)
.arg("-e")
.arg("-f").arg(makefile)
.arg(platform)
.execute()
}
/// If a static Lua is not yet available from a prior run of this script, this
/// will download Lua and build it. The cargo configuration text to link
/// statically against lua.a is then printed to stdout.
fn prebuild() -> io::Result<()> {
let lua_dir = match env::var_os("LUA_LOCAL_SOURCE") {
// If LUA_LOCAL_SOURCE is set, use it
Some(dir) => PathBuf::from(dir),
// Otherwise, pull from lua-source/src in the crate root
None => {
let mut dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
dir.push("lua-source/src");
dir
}
};
let build_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let mut config = gcc::Config::new();
println!("cargo:rustc-link-lib=static=lua");
if lua_dir.join("liblua.a").exists() {
// If liblua.a is already in lua_dir, use it
println!("cargo:rustc-link-search=native={}", lua_dir.display());
} else {
// Otherwise, build from lua_dir into build_dir
if!build_dir.join("liblua.a").exists() {
let tooling = config.get_compiler();
try!(fs::create_dir_all(&build_dir));
try!(build_lua(&tooling, &lua_dir, &build_dir));
}
println!("cargo:rustc-link-search=native={}", build_dir.display());
}
// Ensure the presence of glue.rs
if!build_dir.join("glue.rs").exists() {
// Compile and run glue.c
let glue = build_dir.join("glue");
try!(config.include(&lua_dir).get_compiler().to_command()
.arg("-I").arg(&lua_dir)
.arg("src/glue/glue.c")
.arg("-o").arg(&glue)
.execute());
try!(Command::new(glue)
.arg(build_dir.join("glue.rs"))
.execute());
}
Ok(())
}
fn main() {
match prebuild() {
Err(e) => panic!("Error: {}", e),
Ok(()) => (),
}
} | } else { | random_line_split |
build.rs | extern crate gcc;
use std::fs;
use std::io;
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::ffi::OsString;
trait CommandExt {
fn execute(&mut self) -> io::Result<()>;
}
impl CommandExt for Command {
/// Execute the command and return an error if it exited with a failure status.
fn execute(&mut self) -> io::Result<()> {
let status = try!(self.status());
if status.success() {
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, format!("The command\n\
\t{:?}\n\
did not run successfully.", self)))
}
}
}
/// The command to build lua, with switches for different OSes.
fn | (tooling: &gcc::Tool, source: &Path, build: &Path) -> io::Result<()> {
// calculate the Lua platform name
let platform = match env::var("TARGET").unwrap().split('-').nth(2).unwrap() {
"windows" => "mingw",
"macos" => "macosx",
"linux" => "linux",
"freebsd" => "freebsd",
"dragonfly" => "bsd",
// fall back to the "generic" system
_ => "generic",
};
// extract CC and MYCFLAGS from the detected tooling
let cc = tooling.path();
let mut cflags = OsString::new();
for arg in tooling.args() {
cflags.push(arg);
cflags.push(" ");
}
// VPATH is used to invoke "make" from the directory where we want Lua to
// be built into, but read the sources from the provided source directory.
// Setting MAKE to match the command we invoke means that the VPATH and
// Makefile path will be carried over when the Makefile invokes itself.
let makefile = source.join("Makefile");
let make = OsString::from(format!("make -e -f {:?}", makefile.to_string_lossy().replace("\\", "/")));
// call the makefile
let mut command = Command::new("make");
for &(ref key, ref val) in tooling.env() {
command.env(key, val);
}
command.current_dir(build)
.env("VPATH", source.to_string_lossy().replace("\\", "/"))
.env("MAKE", make)
.env("CC", cc)
.env("MYCFLAGS", cflags)
.arg("-e")
.arg("-f").arg(makefile)
.arg(platform)
.execute()
}
/// If a static Lua is not yet available from a prior run of this script, this
/// will download Lua and build it. The cargo configuration text to link
/// statically against lua.a is then printed to stdout.
fn prebuild() -> io::Result<()> {
let lua_dir = match env::var_os("LUA_LOCAL_SOURCE") {
// If LUA_LOCAL_SOURCE is set, use it
Some(dir) => PathBuf::from(dir),
// Otherwise, pull from lua-source/src in the crate root
None => {
let mut dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());
dir.push("lua-source/src");
dir
}
};
let build_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let mut config = gcc::Config::new();
println!("cargo:rustc-link-lib=static=lua");
if lua_dir.join("liblua.a").exists() {
// If liblua.a is already in lua_dir, use it
println!("cargo:rustc-link-search=native={}", lua_dir.display());
} else {
// Otherwise, build from lua_dir into build_dir
if!build_dir.join("liblua.a").exists() {
let tooling = config.get_compiler();
try!(fs::create_dir_all(&build_dir));
try!(build_lua(&tooling, &lua_dir, &build_dir));
}
println!("cargo:rustc-link-search=native={}", build_dir.display());
}
// Ensure the presence of glue.rs
if!build_dir.join("glue.rs").exists() {
// Compile and run glue.c
let glue = build_dir.join("glue");
try!(config.include(&lua_dir).get_compiler().to_command()
.arg("-I").arg(&lua_dir)
.arg("src/glue/glue.c")
.arg("-o").arg(&glue)
.execute());
try!(Command::new(glue)
.arg(build_dir.join("glue.rs"))
.execute());
}
Ok(())
}
fn main() {
match prebuild() {
Err(e) => panic!("Error: {}", e),
Ok(()) => (),
}
}
| build_lua | identifier_name |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
extern crate std;
use subprocess;
use unpacker;
struct Xz {
}
impl unpacker::Unpacker for Xz {
fn unpack(&self, in_file: &std::path::Path, out_dir: &std::path::Path) -> Result<std::path::PathBuf, unpacker::Error> {
info!("Unpacking (xz) {:?} in {:?}", in_file, out_dir);
unpacker::check_unpack_args(in_file, out_dir)?;
let in_path_str = match in_file.to_str() {
Some(path) => path,
None => { return Err(unpacker::PathError); }
};
/* Create the output directory if it does not exist */
if! out_dir.exists() { | * extension) of in_file */
let mut output = out_dir.to_path_buf();
match in_file.file_name() {
Some(os_str) => {
output.push(os_str);
},
None => { return Err(unpacker::PathError); }
}
output.set_extension("");
let mut cmd = subprocess::new("xz");
cmd.stdout(std::process::Stdio::null());
cmd.arg("-d");
cmd.arg(in_path_str);
subprocess::run(&mut cmd)?;
Ok(output)
}
}
pub fn new() -> Box<unpacker::Unpacker> {
Box::new(Xz {
})
}
pub fn name_get() -> &'static str {
"xz"
} | std::fs::create_dir_all(out_dir)?;
}
/* We will write a single file in out_dir with the basename (without | random_line_split |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
extern crate std;
use subprocess;
use unpacker;
struct Xz {
}
impl unpacker::Unpacker for Xz {
fn unpack(&self, in_file: &std::path::Path, out_dir: &std::path::Path) -> Result<std::path::PathBuf, unpacker::Error> {
info!("Unpacking (xz) {:?} in {:?}", in_file, out_dir);
unpacker::check_unpack_args(in_file, out_dir)?;
let in_path_str = match in_file.to_str() {
Some(path) => path,
None => { return Err(unpacker::PathError); }
};
/* Create the output directory if it does not exist */
if! out_dir.exists() {
std::fs::create_dir_all(out_dir)?;
}
/* We will write a single file in out_dir with the basename (without
* extension) of in_file */
let mut output = out_dir.to_path_buf();
match in_file.file_name() {
Some(os_str) => {
output.push(os_str);
},
None => { return Err(unpacker::PathError); }
}
output.set_extension("");
let mut cmd = subprocess::new("xz");
cmd.stdout(std::process::Stdio::null());
cmd.arg("-d");
cmd.arg(in_path_str);
subprocess::run(&mut cmd)?;
Ok(output)
}
}
pub fn new() -> Box<unpacker::Unpacker> {
Box::new(Xz {
})
}
pub fn | () -> &'static str {
"xz"
}
| name_get | identifier_name |
xz.rs | /*
* Copyright (c) 2017 Jean Guyomarc'h
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
extern crate std;
use subprocess;
use unpacker;
struct Xz {
}
impl unpacker::Unpacker for Xz {
fn unpack(&self, in_file: &std::path::Path, out_dir: &std::path::Path) -> Result<std::path::PathBuf, unpacker::Error> {
info!("Unpacking (xz) {:?} in {:?}", in_file, out_dir);
unpacker::check_unpack_args(in_file, out_dir)?;
let in_path_str = match in_file.to_str() {
Some(path) => path,
None => |
};
/* Create the output directory if it does not exist */
if! out_dir.exists() {
std::fs::create_dir_all(out_dir)?;
}
/* We will write a single file in out_dir with the basename (without
* extension) of in_file */
let mut output = out_dir.to_path_buf();
match in_file.file_name() {
Some(os_str) => {
output.push(os_str);
},
None => { return Err(unpacker::PathError); }
}
output.set_extension("");
let mut cmd = subprocess::new("xz");
cmd.stdout(std::process::Stdio::null());
cmd.arg("-d");
cmd.arg(in_path_str);
subprocess::run(&mut cmd)?;
Ok(output)
}
}
pub fn new() -> Box<unpacker::Unpacker> {
Box::new(Xz {
})
}
pub fn name_get() -> &'static str {
"xz"
}
| { return Err(unpacker::PathError); } | conditional_block |
canvas_util.rs | use std::convert::{Into};
use super::canvas::{Canvas, Image, FONT_W};
use super::{WidgetId};
use ::{V2, Rect, color, Rgba};
use ::Anchor::*;
/// Helper methods for canvas context that do not depend on the underlying
/// implementation details.
pub trait CanvasUtil {
/// Draw a thick solid line on the canvas.
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C);
/// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw a wireframe rectangle.
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw an immediate GUI button and return whether it was pressed.
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool;
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>);
fn char_width(&self, c: char) -> f32;
/// Write a timestamped screenshot PNG to disk.
fn save_screenshot(&mut self, basename: &str);
}
impl<'a> CanvasUtil for Canvas<'a> {
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) | self.push_vertex(p1 + v2 + v1, layer, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn image_dim(&self, img: Image) -> V2<u32> {
self.image_data(img).pos.1.map(|x| x as u32)
}
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D) {
// Use round numbers, fractions seem to cause artifacts to pixels.
let offset = offset.map(|x| x.floor());
let mut pos;
let mut tex;
{
let data = self.image_data(img);
pos = data.pos + offset;
tex = data.tex;
}
let ind0 = self.num_vertices();
self.push_vertex(pos.point(TopLeft), z, tex.point(TopLeft), color, back_color);
self.push_vertex(pos.point(TopRight), z, tex.point(TopRight), color, back_color);
self.push_vertex(pos.point(BottomRight), z, tex.point(BottomRight), color, back_color);
self.push_vertex(pos.point(BottomLeft), z, tex.point(BottomLeft), color, back_color);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
let tex = self.solid_tex_coord();
let ind0 = self.num_vertices();
self.push_vertex(rect.point(TopLeft), z, tex, color, color::BLACK);
self.push_vertex(rect.point(TopRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomLeft), z, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
self.draw_line(1.0, rect.point(TopLeft), rect.point(TopRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(TopRight) - V2(1.0, 0.0), rect.point(BottomRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(BottomLeft) - V2(0.0, 1.0), rect.point(BottomRight) - V2(1.0, 1.0), z, color);
self.draw_line(1.0, rect.point(TopLeft), rect.point(BottomLeft), z, color);
}
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool {
// TODO: Button visual style! Closures?
let area = Rect(pos, V2(64.0, 16.0));
let mut color = color::GREEN;
if area.contains(&self.mouse_pos) {
self.hot_widget = Some(id);
if self.active_widget.is_none() && self.mouse_pressed {
self.active_widget = Some(id);
}
color = color::RED;
}
self.fill_rect(&area, z, color);
return!self.mouse_pressed // Mouse is released
&& self.active_widget == Some(id) // But this button is hot and active
&& self.hot_widget == Some(id);
}
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>) {
static BORDER: [V2<f32>; 8] =
[V2(-1.0, -1.0), V2( 0.0, -1.0), V2( 1.0, -1.0),
V2(-1.0, 0.0), V2( 1.0, 0.0),
V2(-1.0, 1.0), V2( 0.0, 1.0), V2( 1.0, 1.0)];
if let Some(img) = self.font_image(c) {
if let Some(b) = border {
// Put the border a tiny bit further in the z-buffer so it
// won't clobber the text on the same layer.
let border_z = z + 0.00001;
for &d in BORDER.iter() {
self.draw_image(img, offset + d, border_z, b, color::BLACK);
}
}
self.draw_image(img, offset, z, color, color::BLACK);
}
}
fn char_width(&self, c: char) -> f32 {
// Special case for space, the atlas image won't have a width.
if c =='' { return (FONT_W / 2) as f32; }
// Infer letter width from the cropped atlas image. (Use mx instead of
// dim on the pos rectangle so that the left-side space will be
// preserved and the letters are kept slightly apart.)
if let Some(img) = self.font_image(c) {
let width = self.image_data(img).pos.mx().0;
return width;
}
// Not a valid letter.
(FONT_W / 2) as f32
}
fn save_screenshot(&mut self, basename: &str) {
use time;
use std::path::{Path};
use std::fs::{self, File};
use image;
let shot = self.screenshot();
let timestamp = time::precise_time_s() as u64;
// Create screenshot filenames by concatenating the current timestamp in
// seconds with a running number from 00 to 99. 100 shots per second
// should be good enough.
// Default if we fail to generate any of the 100 candidates for this
// second, just overwrite with the "xx" prefix then.
let mut filename = format!("{}-{}{}.png", basename, timestamp, "xx");
// Run through candidates for this second.
for i in 0..100 {
let test_filename = format!("{}-{}{:02}.png", basename, timestamp, i);
// If file does not exist.
if fs::metadata(&test_filename).is_err() {
// Thread-safe claiming: create_dir will fail if the dir
// already exists (it'll exist if another thread is gunning
// for the same filename and managed to get past us here).
// At least assuming that create_dir is atomic...
let squat_dir = format!(".tmp-{}{:02}", timestamp, i);
if fs::create_dir(&squat_dir).is_ok() {
File::create(&test_filename).unwrap();
filename = test_filename;
fs::remove_dir(&squat_dir).unwrap();
break;
} else {
continue;
}
}
}
let _ = image::save_buffer(&Path::new(&filename), &shot, shot.width(), shot.height(), image::ColorType::RGB(8));
}
}
| {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width) / scalar;
let v1 = v1 * scalar;
// The sideways vector, turn into unit vector, then multiply by half the width.
let v2 = V2(-v1.1, v1.0);
let scalar = width / 2.0 * 1.0 / v2.dot(v2).sqrt();
let v2 = v2 * scalar;
let ind0 = self.num_vertices();
self.push_vertex(p1 + v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2 + v1, layer, tex, color, color::BLACK); | identifier_body |
canvas_util.rs | use std::convert::{Into};
use super::canvas::{Canvas, Image, FONT_W};
use super::{WidgetId};
use ::{V2, Rect, color, Rgba};
use ::Anchor::*;
/// Helper methods for canvas context that do not depend on the underlying
/// implementation details.
pub trait CanvasUtil {
/// Draw a thick solid line on the canvas.
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C);
/// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw a wireframe rectangle.
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw an immediate GUI button and return whether it was pressed.
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool;
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>);
fn char_width(&self, c: char) -> f32;
/// Write a timestamped screenshot PNG to disk.
fn save_screenshot(&mut self, basename: &str);
}
impl<'a> CanvasUtil for Canvas<'a> {
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width) / scalar;
let v1 = v1 * scalar;
// The sideways vector, turn into unit vector, then multiply by half the width.
let v2 = V2(-v1.1, v1.0);
let scalar = width / 2.0 * 1.0 / v2.dot(v2).sqrt();
let v2 = v2 * scalar;
let ind0 = self.num_vertices();
self.push_vertex(p1 + v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2 + v1, layer, tex, color, color::BLACK);
self.push_vertex(p1 + v2 + v1, layer, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn image_dim(&self, img: Image) -> V2<u32> {
self.image_data(img).pos.1.map(|x| x as u32)
}
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D) {
// Use round numbers, fractions seem to cause artifacts to pixels.
let offset = offset.map(|x| x.floor());
let mut pos;
let mut tex;
{
let data = self.image_data(img);
pos = data.pos + offset;
tex = data.tex;
}
let ind0 = self.num_vertices();
self.push_vertex(pos.point(TopLeft), z, tex.point(TopLeft), color, back_color);
self.push_vertex(pos.point(TopRight), z, tex.point(TopRight), color, back_color);
self.push_vertex(pos.point(BottomRight), z, tex.point(BottomRight), color, back_color);
self.push_vertex(pos.point(BottomLeft), z, tex.point(BottomLeft), color, back_color);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
let tex = self.solid_tex_coord();
let ind0 = self.num_vertices();
self.push_vertex(rect.point(TopLeft), z, tex, color, color::BLACK);
self.push_vertex(rect.point(TopRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomLeft), z, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
self.draw_line(1.0, rect.point(TopLeft), rect.point(TopRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(TopRight) - V2(1.0, 0.0), rect.point(BottomRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(BottomLeft) - V2(0.0, 1.0), rect.point(BottomRight) - V2(1.0, 1.0), z, color);
self.draw_line(1.0, rect.point(TopLeft), rect.point(BottomLeft), z, color);
}
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool {
// TODO: Button visual style! Closures?
let area = Rect(pos, V2(64.0, 16.0));
let mut color = color::GREEN;
if area.contains(&self.mouse_pos) {
self.hot_widget = Some(id);
if self.active_widget.is_none() && self.mouse_pressed {
self.active_widget = Some(id);
}
color = color::RED;
}
self.fill_rect(&area, z, color);
return!self.mouse_pressed // Mouse is released
&& self.active_widget == Some(id) // But this button is hot and active
&& self.hot_widget == Some(id);
}
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>) {
static BORDER: [V2<f32>; 8] =
[V2(-1.0, -1.0), V2( 0.0, -1.0), V2( 1.0, -1.0),
V2(-1.0, 0.0), V2( 1.0, 0.0),
V2(-1.0, 1.0), V2( 0.0, 1.0), V2( 1.0, 1.0)];
if let Some(img) = self.font_image(c) {
if let Some(b) = border {
// Put the border a tiny bit further in the z-buffer so it
// won't clobber the text on the same layer.
let border_z = z + 0.00001;
for &d in BORDER.iter() {
self.draw_image(img, offset + d, border_z, b, color::BLACK);
}
}
self.draw_image(img, offset, z, color, color::BLACK);
}
}
fn char_width(&self, c: char) -> f32 {
// Special case for space, the atlas image won't have a width.
if c =='' { return (FONT_W / 2) as f32; }
// Infer letter width from the cropped atlas image. (Use mx instead of
// dim on the pos rectangle so that the left-side space will be
// preserved and the letters are kept slightly apart.)
if let Some(img) = self.font_image(c) {
let width = self.image_data(img).pos.mx().0;
return width;
}
// Not a valid letter.
(FONT_W / 2) as f32
}
fn save_screenshot(&mut self, basename: &str) {
use time;
use std::path::{Path};
use std::fs::{self, File};
use image;
let shot = self.screenshot();
| // Default if we fail to generate any of the 100 candidates for this
// second, just overwrite with the "xx" prefix then.
let mut filename = format!("{}-{}{}.png", basename, timestamp, "xx");
// Run through candidates for this second.
for i in 0..100 {
let test_filename = format!("{}-{}{:02}.png", basename, timestamp, i);
// If file does not exist.
if fs::metadata(&test_filename).is_err() {
// Thread-safe claiming: create_dir will fail if the dir
// already exists (it'll exist if another thread is gunning
// for the same filename and managed to get past us here).
// At least assuming that create_dir is atomic...
let squat_dir = format!(".tmp-{}{:02}", timestamp, i);
if fs::create_dir(&squat_dir).is_ok() {
File::create(&test_filename).unwrap();
filename = test_filename;
fs::remove_dir(&squat_dir).unwrap();
break;
} else {
continue;
}
}
}
let _ = image::save_buffer(&Path::new(&filename), &shot, shot.width(), shot.height(), image::ColorType::RGB(8));
}
} | let timestamp = time::precise_time_s() as u64;
// Create screenshot filenames by concatenating the current timestamp in
// seconds with a running number from 00 to 99. 100 shots per second
// should be good enough.
| random_line_split |
canvas_util.rs | use std::convert::{Into};
use super::canvas::{Canvas, Image, FONT_W};
use super::{WidgetId};
use ::{V2, Rect, color, Rgba};
use ::Anchor::*;
/// Helper methods for canvas context that do not depend on the underlying
/// implementation details.
pub trait CanvasUtil {
/// Draw a thick solid line on the canvas.
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C);
/// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw a wireframe rectangle.
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw an immediate GUI button and return whether it was pressed.
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool;
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>);
fn char_width(&self, c: char) -> f32;
/// Write a timestamped screenshot PNG to disk.
fn save_screenshot(&mut self, basename: &str);
}
impl<'a> CanvasUtil for Canvas<'a> {
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width) / scalar;
let v1 = v1 * scalar;
// The sideways vector, turn into unit vector, then multiply by half the width.
let v2 = V2(-v1.1, v1.0);
let scalar = width / 2.0 * 1.0 / v2.dot(v2).sqrt();
let v2 = v2 * scalar;
let ind0 = self.num_vertices();
self.push_vertex(p1 + v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2 + v1, layer, tex, color, color::BLACK);
self.push_vertex(p1 + v2 + v1, layer, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn image_dim(&self, img: Image) -> V2<u32> {
self.image_data(img).pos.1.map(|x| x as u32)
}
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D) {
// Use round numbers, fractions seem to cause artifacts to pixels.
let offset = offset.map(|x| x.floor());
let mut pos;
let mut tex;
{
let data = self.image_data(img);
pos = data.pos + offset;
tex = data.tex;
}
let ind0 = self.num_vertices();
self.push_vertex(pos.point(TopLeft), z, tex.point(TopLeft), color, back_color);
self.push_vertex(pos.point(TopRight), z, tex.point(TopRight), color, back_color);
self.push_vertex(pos.point(BottomRight), z, tex.point(BottomRight), color, back_color);
self.push_vertex(pos.point(BottomLeft), z, tex.point(BottomLeft), color, back_color);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
let tex = self.solid_tex_coord();
let ind0 = self.num_vertices();
self.push_vertex(rect.point(TopLeft), z, tex, color, color::BLACK);
self.push_vertex(rect.point(TopRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomLeft), z, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
self.draw_line(1.0, rect.point(TopLeft), rect.point(TopRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(TopRight) - V2(1.0, 0.0), rect.point(BottomRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(BottomLeft) - V2(0.0, 1.0), rect.point(BottomRight) - V2(1.0, 1.0), z, color);
self.draw_line(1.0, rect.point(TopLeft), rect.point(BottomLeft), z, color);
}
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool {
// TODO: Button visual style! Closures?
let area = Rect(pos, V2(64.0, 16.0));
let mut color = color::GREEN;
if area.contains(&self.mouse_pos) {
self.hot_widget = Some(id);
if self.active_widget.is_none() && self.mouse_pressed {
self.active_widget = Some(id);
}
color = color::RED;
}
self.fill_rect(&area, z, color);
return!self.mouse_pressed // Mouse is released
&& self.active_widget == Some(id) // But this button is hot and active
&& self.hot_widget == Some(id);
}
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>) {
static BORDER: [V2<f32>; 8] =
[V2(-1.0, -1.0), V2( 0.0, -1.0), V2( 1.0, -1.0),
V2(-1.0, 0.0), V2( 1.0, 0.0),
V2(-1.0, 1.0), V2( 0.0, 1.0), V2( 1.0, 1.0)];
if let Some(img) = self.font_image(c) {
if let Some(b) = border {
// Put the border a tiny bit further in the z-buffer so it
// won't clobber the text on the same layer.
let border_z = z + 0.00001;
for &d in BORDER.iter() {
self.draw_image(img, offset + d, border_z, b, color::BLACK);
}
}
self.draw_image(img, offset, z, color, color::BLACK);
}
}
fn char_width(&self, c: char) -> f32 {
// Special case for space, the atlas image won't have a width.
if c =='' { return (FONT_W / 2) as f32; }
// Infer letter width from the cropped atlas image. (Use mx instead of
// dim on the pos rectangle so that the left-side space will be
// preserved and the letters are kept slightly apart.)
if let Some(img) = self.font_image(c) {
let width = self.image_data(img).pos.mx().0;
return width;
}
// Not a valid letter.
(FONT_W / 2) as f32
}
fn save_screenshot(&mut self, basename: &str) {
use time;
use std::path::{Path};
use std::fs::{self, File};
use image;
let shot = self.screenshot();
let timestamp = time::precise_time_s() as u64;
// Create screenshot filenames by concatenating the current timestamp in
// seconds with a running number from 00 to 99. 100 shots per second
// should be good enough.
// Default if we fail to generate any of the 100 candidates for this
// second, just overwrite with the "xx" prefix then.
let mut filename = format!("{}-{}{}.png", basename, timestamp, "xx");
// Run through candidates for this second.
for i in 0..100 {
let test_filename = format!("{}-{}{:02}.png", basename, timestamp, i);
// If file does not exist.
if fs::metadata(&test_filename).is_err() |
}
let _ = image::save_buffer(&Path::new(&filename), &shot, shot.width(), shot.height(), image::ColorType::RGB(8));
}
}
| {
// Thread-safe claiming: create_dir will fail if the dir
// already exists (it'll exist if another thread is gunning
// for the same filename and managed to get past us here).
// At least assuming that create_dir is atomic...
let squat_dir = format!(".tmp-{}{:02}", timestamp, i);
if fs::create_dir(&squat_dir).is_ok() {
File::create(&test_filename).unwrap();
filename = test_filename;
fs::remove_dir(&squat_dir).unwrap();
break;
} else {
continue;
}
} | conditional_block |
canvas_util.rs | use std::convert::{Into};
use super::canvas::{Canvas, Image, FONT_W};
use super::{WidgetId};
use ::{V2, Rect, color, Rgba};
use ::Anchor::*;
/// Helper methods for canvas context that do not depend on the underlying
/// implementation details.
pub trait CanvasUtil {
/// Draw a thick solid line on the canvas.
fn draw_line<C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C);
/// Get the size of an atlas image.
fn image_dim(&self, img: Image) -> V2<u32>;
/// Draw a stored image on the canvas.
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D);
/// Draw a filled rectangle.
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw a wireframe rectangle.
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C);
/// Draw an immediate GUI button and return whether it was pressed.
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool;
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>);
fn char_width(&self, c: char) -> f32;
/// Write a timestamped screenshot PNG to disk.
fn save_screenshot(&mut self, basename: &str);
}
impl<'a> CanvasUtil for Canvas<'a> {
fn | <C: Into<Rgba>+Copy>(&mut self, width: f32, p1: V2<f32>, p2: V2<f32>, layer: f32, color: C) {
if p1 == p2 { return; }
let tex = self.solid_tex_coord();
// The front vector. Extend by width.
let v1 = p2 - p1;
let scalar = v1.dot(v1);
let scalar = (scalar + width * width) / scalar;
let v1 = v1 * scalar;
// The sideways vector, turn into unit vector, then multiply by half the width.
let v2 = V2(-v1.1, v1.0);
let scalar = width / 2.0 * 1.0 / v2.dot(v2).sqrt();
let v2 = v2 * scalar;
let ind0 = self.num_vertices();
self.push_vertex(p1 + v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2, layer, tex, color, color::BLACK);
self.push_vertex(p1 - v2 + v1, layer, tex, color, color::BLACK);
self.push_vertex(p1 + v2 + v1, layer, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn image_dim(&self, img: Image) -> V2<u32> {
self.image_data(img).pos.1.map(|x| x as u32)
}
fn draw_image<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, img: Image,
offset: V2<f32>, z: f32, color: C, back_color: D) {
// Use round numbers, fractions seem to cause artifacts to pixels.
let offset = offset.map(|x| x.floor());
let mut pos;
let mut tex;
{
let data = self.image_data(img);
pos = data.pos + offset;
tex = data.tex;
}
let ind0 = self.num_vertices();
self.push_vertex(pos.point(TopLeft), z, tex.point(TopLeft), color, back_color);
self.push_vertex(pos.point(TopRight), z, tex.point(TopRight), color, back_color);
self.push_vertex(pos.point(BottomRight), z, tex.point(BottomRight), color, back_color);
self.push_vertex(pos.point(BottomLeft), z, tex.point(BottomLeft), color, back_color);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn fill_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
let tex = self.solid_tex_coord();
let ind0 = self.num_vertices();
self.push_vertex(rect.point(TopLeft), z, tex, color, color::BLACK);
self.push_vertex(rect.point(TopRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomRight), z, tex, color, color::BLACK);
self.push_vertex(rect.point(BottomLeft), z, tex, color, color::BLACK);
self.push_triangle(ind0, ind0 + 1, ind0 + 2);
self.push_triangle(ind0, ind0 + 2, ind0 + 3);
self.flush();
}
fn draw_rect<C: Into<Rgba>+Copy>(&mut self, rect: &Rect<f32>, z: f32, color: C) {
self.draw_line(1.0, rect.point(TopLeft), rect.point(TopRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(TopRight) - V2(1.0, 0.0), rect.point(BottomRight) - V2(1.0, 0.0), z, color);
self.draw_line(1.0, rect.point(BottomLeft) - V2(0.0, 1.0), rect.point(BottomRight) - V2(1.0, 1.0), z, color);
self.draw_line(1.0, rect.point(TopLeft), rect.point(BottomLeft), z, color);
}
fn button(&mut self, id: WidgetId, pos: V2<f32>, z: f32) -> bool {
// TODO: Button visual style! Closures?
let area = Rect(pos, V2(64.0, 16.0));
let mut color = color::GREEN;
if area.contains(&self.mouse_pos) {
self.hot_widget = Some(id);
if self.active_widget.is_none() && self.mouse_pressed {
self.active_widget = Some(id);
}
color = color::RED;
}
self.fill_rect(&area, z, color);
return!self.mouse_pressed // Mouse is released
&& self.active_widget == Some(id) // But this button is hot and active
&& self.hot_widget == Some(id);
}
fn draw_char<C: Into<Rgba>+Copy, D: Into<Rgba>+Copy>(&mut self, c: char, offset: V2<f32>, z: f32, color: C, border: Option<D>) {
static BORDER: [V2<f32>; 8] =
[V2(-1.0, -1.0), V2( 0.0, -1.0), V2( 1.0, -1.0),
V2(-1.0, 0.0), V2( 1.0, 0.0),
V2(-1.0, 1.0), V2( 0.0, 1.0), V2( 1.0, 1.0)];
if let Some(img) = self.font_image(c) {
if let Some(b) = border {
// Put the border a tiny bit further in the z-buffer so it
// won't clobber the text on the same layer.
let border_z = z + 0.00001;
for &d in BORDER.iter() {
self.draw_image(img, offset + d, border_z, b, color::BLACK);
}
}
self.draw_image(img, offset, z, color, color::BLACK);
}
}
fn char_width(&self, c: char) -> f32 {
// Special case for space, the atlas image won't have a width.
if c =='' { return (FONT_W / 2) as f32; }
// Infer letter width from the cropped atlas image. (Use mx instead of
// dim on the pos rectangle so that the left-side space will be
// preserved and the letters are kept slightly apart.)
if let Some(img) = self.font_image(c) {
let width = self.image_data(img).pos.mx().0;
return width;
}
// Not a valid letter.
(FONT_W / 2) as f32
}
fn save_screenshot(&mut self, basename: &str) {
use time;
use std::path::{Path};
use std::fs::{self, File};
use image;
let shot = self.screenshot();
let timestamp = time::precise_time_s() as u64;
// Create screenshot filenames by concatenating the current timestamp in
// seconds with a running number from 00 to 99. 100 shots per second
// should be good enough.
// Default if we fail to generate any of the 100 candidates for this
// second, just overwrite with the "xx" prefix then.
let mut filename = format!("{}-{}{}.png", basename, timestamp, "xx");
// Run through candidates for this second.
for i in 0..100 {
let test_filename = format!("{}-{}{:02}.png", basename, timestamp, i);
// If file does not exist.
if fs::metadata(&test_filename).is_err() {
// Thread-safe claiming: create_dir will fail if the dir
// already exists (it'll exist if another thread is gunning
// for the same filename and managed to get past us here).
// At least assuming that create_dir is atomic...
let squat_dir = format!(".tmp-{}{:02}", timestamp, i);
if fs::create_dir(&squat_dir).is_ok() {
File::create(&test_filename).unwrap();
filename = test_filename;
fs::remove_dir(&squat_dir).unwrap();
break;
} else {
continue;
}
}
}
let _ = image::save_buffer(&Path::new(&filename), &shot, shot.width(), shot.height(), image::ColorType::RGB(8));
}
}
| draw_line | identifier_name |
service.rs | // This file is generated. Do not edit
// @generated
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(Clone,Default)]
pub struct Service {
// message fields
name: ::protobuf::SingularField<::std::string::String>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::std::cell::Cell<u32>,
}
impl Service {
pub fn new() -> Service {
::std::default::Default::default()
}
pub fn default_instance() -> &'static Service {
static mut instance: ::protobuf::lazy::Lazy<Service> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const Service,
};
unsafe {
instance.get(|| {
Service {
name: ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
// Param is passed by value, moved
pub fn set_name(&mut self, v: ::std::string::String) {
self.name = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_name<'a>(&'a mut self) -> &'a mut ::std::string::String {
if self.name.is_none() {
self.name.set_default();
};
self.name.as_mut().unwrap()
}
// Take field
pub fn take_name(&mut self) -> ::std::string::String {
self.name.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_name<'a>(&'a self) -> &'a str {
match self.name.as_ref() {
Some(v) => &v,
None => "",
}
}
}
impl ::protobuf::Message for Service {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while!try!(is.eof()) {
let (field_number, wire_type) = try!(is.read_tag_unpack());
match field_number {
1 => {
if wire_type!= ::protobuf::wire_format::WireTypeLengthDelimited {
return ::std::result::Result::Err(::protobuf::ProtobufError::WireError("unexpected wire type".to_string()));
};
let tmp = self.name.set_default();
try!(is.read_string_into(tmp))
},
_ => {
let unknown = try!(is.read_unknown(wire_type));
self.mut_unknown_fields().add_value(field_number, unknown);
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
for value in self.name.iter() {
my_size += ::protobuf::rt::string_size(1, &value);
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.name.as_ref() {
try!(os.write_string(1, &v));
};
try!(os.write_unknown_fields(self.get_unknown_fields()));
::std::result::Result::Ok(())
}
fn | (&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields<'s>(&'s self) -> &'s ::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn type_id(&self) -> ::std::any::TypeId {
::std::any::TypeId::of::<Service>()
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
::protobuf::MessageStatic::descriptor_static(None::<Self>)
}
}
impl ::protobuf::MessageStatic for Service {
fn new() -> Service {
Service::new()
}
fn descriptor_static(_: ::std::option::Option<Service>) -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_string_accessor(
"name",
Service::has_name,
Service::get_name,
));
::protobuf::reflect::MessageDescriptor::new::<Service>(
"Service",
fields,
file_descriptor_proto()
)
})
}
}
}
impl ::protobuf::Clear for Service {
fn clear(&mut self) {
self.clear_name();
self.unknown_fields.clear();
}
}
impl ::std::cmp::PartialEq for Service {
fn eq(&self, other: &Service) -> bool {
self.name == other.name &&
self.unknown_fields == other.unknown_fields
}
}
impl ::std::fmt::Debug for Service {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
static file_descriptor_proto_data: &'static [u8] = &[
0x0a, 0x0d, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x17, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76,
0x69, 0x63, 0x65, 0x12, 0x0c, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x4a, 0x9d, 0x01, 0x0a, 0x06, 0x12, 0x04, 0x00, 0x00, 0x05, 0x01, 0x0a, 0x08, 0x0a, 0x01,
0x02, 0x12, 0x03, 0x00, 0x08, 0x0f, 0x0a, 0x38, 0x0a, 0x02, 0x04, 0x00, 0x12, 0x04, 0x03, 0x00,
0x05, 0x01, 0x1a, 0x2c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x63, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x20, 0x61,
0x62, 0x6f, 0x75, 0x74, 0x20, 0x61, 0x20, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x0a,
0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x00, 0x01, 0x12, 0x03, 0x03, 0x08, 0x0f, 0x0a, 0x0b, 0x0a, 0x04,
0x04, 0x00, 0x02, 0x00, 0x12, 0x03, 0x04, 0x02, 0x1b, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02,
0x00, 0x04, 0x12, 0x03, 0x04, 0x02, 0x0a, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x05,
0x12, 0x03, 0x04, 0x0b, 0x11, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x01, 0x12, 0x03,
0x04, 0x12, 0x16, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x03, 0x12, 0x03, 0x04, 0x19,
0x1a,
];
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}
| get_cached_size | identifier_name |
service.rs | // This file is generated. Do not edit
// @generated
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(Clone,Default)]
pub struct Service {
// message fields
name: ::protobuf::SingularField<::std::string::String>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::std::cell::Cell<u32>,
}
impl Service {
pub fn new() -> Service {
::std::default::Default::default()
}
pub fn default_instance() -> &'static Service {
static mut instance: ::protobuf::lazy::Lazy<Service> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const Service,
};
unsafe {
instance.get(|| {
Service {
name: ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
// Param is passed by value, moved
pub fn set_name(&mut self, v: ::std::string::String) {
self.name = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_name<'a>(&'a mut self) -> &'a mut ::std::string::String {
if self.name.is_none() {
self.name.set_default();
};
self.name.as_mut().unwrap()
}
// Take field
pub fn take_name(&mut self) -> ::std::string::String {
self.name.take().unwrap_or_else(|| ::std::string::String::new())
} |
pub fn get_name<'a>(&'a self) -> &'a str {
match self.name.as_ref() {
Some(v) => &v,
None => "",
}
}
}
impl ::protobuf::Message for Service {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while!try!(is.eof()) {
let (field_number, wire_type) = try!(is.read_tag_unpack());
match field_number {
1 => {
if wire_type!= ::protobuf::wire_format::WireTypeLengthDelimited {
return ::std::result::Result::Err(::protobuf::ProtobufError::WireError("unexpected wire type".to_string()));
};
let tmp = self.name.set_default();
try!(is.read_string_into(tmp))
},
_ => {
let unknown = try!(is.read_unknown(wire_type));
self.mut_unknown_fields().add_value(field_number, unknown);
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
for value in self.name.iter() {
my_size += ::protobuf::rt::string_size(1, &value);
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.name.as_ref() {
try!(os.write_string(1, &v));
};
try!(os.write_unknown_fields(self.get_unknown_fields()));
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields<'s>(&'s self) -> &'s ::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn type_id(&self) -> ::std::any::TypeId {
::std::any::TypeId::of::<Service>()
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
::protobuf::MessageStatic::descriptor_static(None::<Self>)
}
}
impl ::protobuf::MessageStatic for Service {
fn new() -> Service {
Service::new()
}
fn descriptor_static(_: ::std::option::Option<Service>) -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_string_accessor(
"name",
Service::has_name,
Service::get_name,
));
::protobuf::reflect::MessageDescriptor::new::<Service>(
"Service",
fields,
file_descriptor_proto()
)
})
}
}
}
impl ::protobuf::Clear for Service {
fn clear(&mut self) {
self.clear_name();
self.unknown_fields.clear();
}
}
impl ::std::cmp::PartialEq for Service {
fn eq(&self, other: &Service) -> bool {
self.name == other.name &&
self.unknown_fields == other.unknown_fields
}
}
impl ::std::fmt::Debug for Service {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
static file_descriptor_proto_data: &'static [u8] = &[
0x0a, 0x0d, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x17, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76,
0x69, 0x63, 0x65, 0x12, 0x0c, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x4a, 0x9d, 0x01, 0x0a, 0x06, 0x12, 0x04, 0x00, 0x00, 0x05, 0x01, 0x0a, 0x08, 0x0a, 0x01,
0x02, 0x12, 0x03, 0x00, 0x08, 0x0f, 0x0a, 0x38, 0x0a, 0x02, 0x04, 0x00, 0x12, 0x04, 0x03, 0x00,
0x05, 0x01, 0x1a, 0x2c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x63, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x20, 0x61,
0x62, 0x6f, 0x75, 0x74, 0x20, 0x61, 0x20, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x0a,
0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x00, 0x01, 0x12, 0x03, 0x03, 0x08, 0x0f, 0x0a, 0x0b, 0x0a, 0x04,
0x04, 0x00, 0x02, 0x00, 0x12, 0x03, 0x04, 0x02, 0x1b, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02,
0x00, 0x04, 0x12, 0x03, 0x04, 0x02, 0x0a, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x05,
0x12, 0x03, 0x04, 0x0b, 0x11, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x01, 0x12, 0x03,
0x04, 0x12, 0x16, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x03, 0x12, 0x03, 0x04, 0x19,
0x1a,
];
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
} | random_line_split | |
service.rs | // This file is generated. Do not edit
// @generated
#![allow(dead_code)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(unused_imports)]
use protobuf::Message as Message_imported_for_functions;
use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions;
#[derive(Clone,Default)]
pub struct Service {
// message fields
name: ::protobuf::SingularField<::std::string::String>,
// special fields
unknown_fields: ::protobuf::UnknownFields,
cached_size: ::std::cell::Cell<u32>,
}
impl Service {
pub fn new() -> Service {
::std::default::Default::default()
}
pub fn default_instance() -> &'static Service {
static mut instance: ::protobuf::lazy::Lazy<Service> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const Service,
};
unsafe {
instance.get(|| {
Service {
name: ::protobuf::SingularField::none(),
unknown_fields: ::protobuf::UnknownFields::new(),
cached_size: ::std::cell::Cell::new(0),
}
})
}
}
// optional string name = 1;
pub fn clear_name(&mut self) {
self.name.clear();
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
// Param is passed by value, moved
pub fn set_name(&mut self, v: ::std::string::String) {
self.name = ::protobuf::SingularField::some(v);
}
// Mutable pointer to the field.
// If field is not initialized, it is initialized with default value first.
pub fn mut_name<'a>(&'a mut self) -> &'a mut ::std::string::String {
if self.name.is_none() {
self.name.set_default();
};
self.name.as_mut().unwrap()
}
// Take field
pub fn take_name(&mut self) -> ::std::string::String {
self.name.take().unwrap_or_else(|| ::std::string::String::new())
}
pub fn get_name<'a>(&'a self) -> &'a str {
match self.name.as_ref() {
Some(v) => &v,
None => "",
}
}
}
impl ::protobuf::Message for Service {
fn is_initialized(&self) -> bool {
true
}
fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> {
while!try!(is.eof()) {
let (field_number, wire_type) = try!(is.read_tag_unpack());
match field_number {
1 => {
if wire_type!= ::protobuf::wire_format::WireTypeLengthDelimited {
return ::std::result::Result::Err(::protobuf::ProtobufError::WireError("unexpected wire type".to_string()));
};
let tmp = self.name.set_default();
try!(is.read_string_into(tmp))
},
_ => {
let unknown = try!(is.read_unknown(wire_type));
self.mut_unknown_fields().add_value(field_number, unknown);
},
};
}
::std::result::Result::Ok(())
}
// Compute sizes of nested messages
#[allow(unused_variables)]
fn compute_size(&self) -> u32 {
let mut my_size = 0;
for value in self.name.iter() {
my_size += ::protobuf::rt::string_size(1, &value);
};
my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields());
self.cached_size.set(my_size);
my_size
}
fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> {
if let Some(v) = self.name.as_ref() {
try!(os.write_string(1, &v));
};
try!(os.write_unknown_fields(self.get_unknown_fields()));
::std::result::Result::Ok(())
}
fn get_cached_size(&self) -> u32 {
self.cached_size.get()
}
fn get_unknown_fields<'s>(&'s self) -> &'s ::protobuf::UnknownFields {
&self.unknown_fields
}
fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut ::protobuf::UnknownFields {
&mut self.unknown_fields
}
fn type_id(&self) -> ::std::any::TypeId {
::std::any::TypeId::of::<Service>()
}
fn as_any(&self) -> &::std::any::Any {
self as &::std::any::Any
}
fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor {
::protobuf::MessageStatic::descriptor_static(None::<Self>)
}
}
impl ::protobuf::MessageStatic for Service {
fn new() -> Service |
fn descriptor_static(_: ::std::option::Option<Service>) -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::reflect::MessageDescriptor,
};
unsafe {
descriptor.get(|| {
let mut fields = ::std::vec::Vec::new();
fields.push(::protobuf::reflect::accessor::make_singular_string_accessor(
"name",
Service::has_name,
Service::get_name,
));
::protobuf::reflect::MessageDescriptor::new::<Service>(
"Service",
fields,
file_descriptor_proto()
)
})
}
}
}
impl ::protobuf::Clear for Service {
fn clear(&mut self) {
self.clear_name();
self.unknown_fields.clear();
}
}
impl ::std::cmp::PartialEq for Service {
fn eq(&self, other: &Service) -> bool {
self.name == other.name &&
self.unknown_fields == other.unknown_fields
}
}
impl ::std::fmt::Debug for Service {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
::protobuf::text_format::fmt(self, f)
}
}
static file_descriptor_proto_data: &'static [u8] = &[
0x0a, 0x0d, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12,
0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x17, 0x0a, 0x07, 0x53, 0x65, 0x72, 0x76,
0x69, 0x63, 0x65, 0x12, 0x0c, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x4a, 0x9d, 0x01, 0x0a, 0x06, 0x12, 0x04, 0x00, 0x00, 0x05, 0x01, 0x0a, 0x08, 0x0a, 0x01,
0x02, 0x12, 0x03, 0x00, 0x08, 0x0f, 0x0a, 0x38, 0x0a, 0x02, 0x04, 0x00, 0x12, 0x04, 0x03, 0x00,
0x05, 0x01, 0x1a, 0x2c, 0x20, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x20, 0x63, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x69, 0x6e, 0x66, 0x6f, 0x20, 0x61,
0x62, 0x6f, 0x75, 0x74, 0x20, 0x61, 0x20, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x0a,
0x0a, 0x0a, 0x0a, 0x03, 0x04, 0x00, 0x01, 0x12, 0x03, 0x03, 0x08, 0x0f, 0x0a, 0x0b, 0x0a, 0x04,
0x04, 0x00, 0x02, 0x00, 0x12, 0x03, 0x04, 0x02, 0x1b, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02,
0x00, 0x04, 0x12, 0x03, 0x04, 0x02, 0x0a, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x05,
0x12, 0x03, 0x04, 0x0b, 0x11, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x01, 0x12, 0x03,
0x04, 0x12, 0x16, 0x0a, 0x0c, 0x0a, 0x05, 0x04, 0x00, 0x02, 0x00, 0x03, 0x12, 0x03, 0x04, 0x19,
0x1a,
];
static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy {
lock: ::protobuf::lazy::ONCE_INIT,
ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto,
};
fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto {
::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap()
}
pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {
unsafe {
file_descriptor_proto_lazy.get(|| {
parse_descriptor_proto()
})
}
}
| {
Service::new()
} | identifier_body |
htmlbrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBRElement {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBRElement |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
}
| {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
} | identifier_body |
htmlbrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBRElement {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn | (localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
}
| new_inherited | identifier_name |
htmlbrelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLBRElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLBRElement {
htmlelement: HTMLElement,
}
impl HTMLBRElementDerived for EventTarget {
fn is_htmlbrelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement)))
}
}
impl HTMLBRElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLBRElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)] | Node::reflect_node(box element, document, HTMLBRElementBinding::Wrap)
}
} | pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLBRElement> {
let element = HTMLBRElement::new_inherited(localName, prefix, document); | random_line_split |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub mod kitty {
use std::fmt;
pub struct cat {
meows : uint,
pub how_hungry : int,
pub name : String,
}
impl fmt::String for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
impl cat {
fn meow(&mut self) |
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
}
| {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
} | identifier_body |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub mod kitty {
use std::fmt;
pub struct cat {
meows : uint,
pub how_hungry : int,
pub name : String, | }
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
}
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
} | }
impl fmt::String for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name) | random_line_split |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub mod kitty {
use std::fmt;
pub struct cat {
meows : uint,
pub how_hungry : int,
pub name : String,
}
impl fmt::String for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
}
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn eat(&mut self) -> bool {
if self.how_hungry > 0 |
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
}
| {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
} | conditional_block |
cci_class_cast.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub mod kitty {
use std::fmt;
pub struct cat {
meows : uint,
pub how_hungry : int,
pub name : String,
}
impl fmt::String for cat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
impl cat {
fn meow(&mut self) {
println!("Meow");
self.meows += 1_usize;
if self.meows % 5_usize == 0_usize {
self.how_hungry += 1;
}
}
}
impl cat {
pub fn speak(&mut self) { self.meow(); }
pub fn | (&mut self) -> bool {
if self.how_hungry > 0 {
println!("OM NOM NOM");
self.how_hungry -= 2;
return true;
}
else {
println!("Not hungry!");
return false;
}
}
}
pub fn cat(in_x : uint, in_y : int, in_name: String) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
}
| eat | identifier_name |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes.gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.help("create various diagnostic outputs during compilation"))
.arg(Arg::with_name("timings")
.short("t")
.help("print timings after each phase"))
.arg(Arg::with_name("input")
.required(true)
.multiple(true))
.get_matches();
// initiate diagnostics config
let config = if arguments.is_present("diagnostics") {
Some(diag::Config::default())
} else {
None
};
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
| fe::check_with_diag(&functions, &config).unwrap();
let end = PreciseTime::now();
if arguments.is_present("timings") {
println!("Frontend time: {}", start.to(end));
}
// TODO error hanlding
} | // run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap(); | random_line_split |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() | } else {
None
};
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
// run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap();
fe::check_with_diag(&functions, &config).unwrap();
let end = PreciseTime::now();
if arguments.is_present("timings") {
println!("Frontend time: {}", start.to(end));
}
// TODO error hanlding
}
| {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes .gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.help("create various diagnostic outputs during compilation"))
.arg(Arg::with_name("timings")
.short("t")
.help("print timings after each phase"))
.arg(Arg::with_name("input")
.required(true)
.multiple(true))
.get_matches();
// initiate diagnostics config
let config = if arguments.is_present("diagnostics") {
Some(diag::Config::default()) | identifier_body |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn | () {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes.gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.help("create various diagnostic outputs during compilation"))
.arg(Arg::with_name("timings")
.short("t")
.help("print timings after each phase"))
.arg(Arg::with_name("input")
.required(true)
.multiple(true))
.get_matches();
// initiate diagnostics config
let config = if arguments.is_present("diagnostics") {
Some(diag::Config::default())
} else {
None
};
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
// run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap();
fe::check_with_diag(&functions, &config).unwrap();
let end = PreciseTime::now();
if arguments.is_present("timings") {
println!("Frontend time: {}", start.to(end));
}
// TODO error hanlding
}
| main | identifier_name |
driver.rs | extern crate cleaver;
use cleaver::fe;
use cleaver::diag;
extern crate clap;
use clap::{App, Arg};
extern crate time;
use time::PreciseTime;
use std::path::Path;
use std::process::exit;
fn main() {
// commandline arguments
let arguments = App::new("Cleaver")
.about("Cleaver is a toy / research compiler, it takes.gib files as input.")
.version("0.1")
.author("Alex Hirsch <W4RH4WK@bluephoenix.at>")
.arg(Arg::with_name("diagnostics")
.short("d")
.help("create various diagnostic outputs during compilation"))
.arg(Arg::with_name("timings")
.short("t")
.help("print timings after each phase"))
.arg(Arg::with_name("input")
.required(true)
.multiple(true))
.get_matches();
// initiate diagnostics config
let config = if arguments.is_present("diagnostics") {
Some(diag::Config::default())
} else | ;
// list of input files
let inputs: Vec<_> = arguments.values_of("input").unwrap().map(Path::new).collect();
// run frontend
let start = PreciseTime::now();
let functions = fe::parse_with_diag(&inputs, &config).unwrap();
fe::check_with_diag(&functions, &config).unwrap();
let end = PreciseTime::now();
if arguments.is_present("timings") {
println!("Frontend time: {}", start.to(end));
}
// TODO error hanlding
}
| {
None
} | conditional_block |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use cell::Cell;
use error::{Error};
use fmt;
use marker::Reflect;
use thread;
pub struct Flag { failed: Cell<bool> }
// This flag is only ever accessed with a lock previously held. Note that this
// a totally private structure.
unsafe impl Send for Flag {}
unsafe impl Sync for Flag {}
impl Flag {
pub const fn new() -> Flag {
Flag { failed: Cell::new(false) }
}
#[inline]
pub fn borrow(&self) -> LockResult<Guard> {
let ret = Guard { panicking: thread::panicking() };
if self.get() {
Err(PoisonError::new(ret))
} else {
Ok(ret)
}
}
#[inline]
pub fn done(&self, guard: &Guard) {
if!guard.panicking && thread::panicking() {
self.failed.set(true);
}
}
#[inline]
pub fn get(&self) -> bool {
self.failed.get()
}
}
pub struct Guard {
panicking: bool,
}
/// A type of error which can be returned whenever a lock is acquired.
///
/// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PoisonError<T> {
guard: T,
}
/// An enumeration of possible errors which can occur while calling the
/// `try_lock` method.
#[stable(feature = "rust1", since = "1.0.0")]
pub enum TryLockError<T> {
/// The lock could not be acquired because another thread failed while holding
/// the lock.
#[stable(feature = "rust1", since = "1.0.0")]
Poisoned(PoisonError<T>),
/// The lock could not be acquired at this time because the operation would
/// otherwise block.
#[stable(feature = "rust1", since = "1.0.0")]
WouldBlock,
}
/// A type alias for the result of a lock method which can be poisoned.
///
/// The `Ok` variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
/// that the primitive was poisoned. Note that the `Err` variant *also* carries
/// the associated guard, and it can be acquired through the `into_inner`
/// method.
#[stable(feature = "rust1", since = "1.0.0")]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see `LockResult`. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the `Err` type as the lock may not
/// have been acquired for other reasons.
#[stable(feature = "rust1", since = "1.0.0")]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"PoisonError { inner:.. }".fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"poisoned lock: another task failed inside".fmt(f)
}
}
impl<T: Send + Reflect> Error for PoisonError<T> {
fn description(&self) -> &str {
"poisoned lock: another task failed inside"
}
}
impl<T> PoisonError<T> {
/// Creates a `PoisonError`.
#[unstable(feature = "std_misc")]
pub fn new(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
}
/// Consumes this error indicating that a lock is poisoned, returning the
/// underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn into_inner(self) -> T { self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_ref(&self) -> &T { &self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// mutable reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}
impl<T> From<PoisonError<T>> for TryLockError<T> {
fn from(err: PoisonError<T>) -> TryLockError<T> {
TryLockError::Poisoned(err)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f), | }
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Reflect> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
TryLockError::Poisoned(ref p) => p.description(),
TryLockError::WouldBlock => "try_lock failed because the operation would block"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
TryLockError::Poisoned(ref p) => Some(p),
_ => None
}
}
}
pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-> LockResult<U>
where F: FnOnce(T) -> U {
match result {
Ok(t) => Ok(f(t)),
Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
}
} | TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
} | random_line_split |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use cell::Cell;
use error::{Error};
use fmt;
use marker::Reflect;
use thread;
pub struct Flag { failed: Cell<bool> }
// This flag is only ever accessed with a lock previously held. Note that this
// a totally private structure.
unsafe impl Send for Flag {}
unsafe impl Sync for Flag {}
impl Flag {
pub const fn new() -> Flag {
Flag { failed: Cell::new(false) }
}
#[inline]
pub fn borrow(&self) -> LockResult<Guard> {
let ret = Guard { panicking: thread::panicking() };
if self.get() {
Err(PoisonError::new(ret))
} else {
Ok(ret)
}
}
#[inline]
pub fn done(&self, guard: &Guard) {
if!guard.panicking && thread::panicking() {
self.failed.set(true);
}
}
#[inline]
pub fn get(&self) -> bool {
self.failed.get()
}
}
pub struct Guard {
panicking: bool,
}
/// A type of error which can be returned whenever a lock is acquired.
///
/// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PoisonError<T> {
guard: T,
}
/// An enumeration of possible errors which can occur while calling the
/// `try_lock` method.
#[stable(feature = "rust1", since = "1.0.0")]
pub enum TryLockError<T> {
/// The lock could not be acquired because another thread failed while holding
/// the lock.
#[stable(feature = "rust1", since = "1.0.0")]
Poisoned(PoisonError<T>),
/// The lock could not be acquired at this time because the operation would
/// otherwise block.
#[stable(feature = "rust1", since = "1.0.0")]
WouldBlock,
}
/// A type alias for the result of a lock method which can be poisoned.
///
/// The `Ok` variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
/// that the primitive was poisoned. Note that the `Err` variant *also* carries
/// the associated guard, and it can be acquired through the `into_inner`
/// method.
#[stable(feature = "rust1", since = "1.0.0")]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see `LockResult`. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the `Err` type as the lock may not
/// have been acquired for other reasons.
#[stable(feature = "rust1", since = "1.0.0")]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"PoisonError { inner:.. }".fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"poisoned lock: another task failed inside".fmt(f)
}
}
impl<T: Send + Reflect> Error for PoisonError<T> {
fn description(&self) -> &str {
"poisoned lock: another task failed inside"
}
}
impl<T> PoisonError<T> {
/// Creates a `PoisonError`.
#[unstable(feature = "std_misc")]
pub fn new(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
}
/// Consumes this error indicating that a lock is poisoned, returning the
/// underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn into_inner(self) -> T { self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_ref(&self) -> &T { &self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// mutable reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}
impl<T> From<PoisonError<T>> for TryLockError<T> {
fn from(err: PoisonError<T>) -> TryLockError<T> {
TryLockError::Poisoned(err)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Reflect> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
TryLockError::Poisoned(ref p) => p.description(),
TryLockError::WouldBlock => "try_lock failed because the operation would block"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
TryLockError::Poisoned(ref p) => Some(p),
_ => None
}
}
}
pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-> LockResult<U>
where F: FnOnce(T) -> U {
match result {
Ok(t) => Ok(f(t)),
Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
}
}
| {
match *self {
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
} | identifier_body |
poison.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use cell::Cell;
use error::{Error};
use fmt;
use marker::Reflect;
use thread;
pub struct Flag { failed: Cell<bool> }
// This flag is only ever accessed with a lock previously held. Note that this
// a totally private structure.
unsafe impl Send for Flag {}
unsafe impl Sync for Flag {}
impl Flag {
pub const fn new() -> Flag {
Flag { failed: Cell::new(false) }
}
#[inline]
pub fn borrow(&self) -> LockResult<Guard> {
let ret = Guard { panicking: thread::panicking() };
if self.get() {
Err(PoisonError::new(ret))
} else {
Ok(ret)
}
}
#[inline]
pub fn done(&self, guard: &Guard) {
if!guard.panicking && thread::panicking() {
self.failed.set(true);
}
}
#[inline]
pub fn get(&self) -> bool {
self.failed.get()
}
}
pub struct Guard {
panicking: bool,
}
/// A type of error which can be returned whenever a lock is acquired.
///
/// Both Mutexes and RwLocks are poisoned whenever a thread fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PoisonError<T> {
guard: T,
}
/// An enumeration of possible errors which can occur while calling the
/// `try_lock` method.
#[stable(feature = "rust1", since = "1.0.0")]
pub enum TryLockError<T> {
/// The lock could not be acquired because another thread failed while holding
/// the lock.
#[stable(feature = "rust1", since = "1.0.0")]
Poisoned(PoisonError<T>),
/// The lock could not be acquired at this time because the operation would
/// otherwise block.
#[stable(feature = "rust1", since = "1.0.0")]
WouldBlock,
}
/// A type alias for the result of a lock method which can be poisoned.
///
/// The `Ok` variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
/// that the primitive was poisoned. Note that the `Err` variant *also* carries
/// the associated guard, and it can be acquired through the `into_inner`
/// method.
#[stable(feature = "rust1", since = "1.0.0")]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see `LockResult`. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the `Err` type as the lock may not
/// have been acquired for other reasons.
#[stable(feature = "rust1", since = "1.0.0")]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"PoisonError { inner:.. }".fmt(f)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Display for PoisonError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
"poisoned lock: another task failed inside".fmt(f)
}
}
impl<T: Send + Reflect> Error for PoisonError<T> {
fn description(&self) -> &str {
"poisoned lock: another task failed inside"
}
}
impl<T> PoisonError<T> {
/// Creates a `PoisonError`.
#[unstable(feature = "std_misc")]
pub fn new(guard: T) -> PoisonError<T> {
PoisonError { guard: guard }
}
/// Consumes this error indicating that a lock is poisoned, returning the
/// underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn into_inner(self) -> T { self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn | (&self) -> &T { &self.guard }
/// Reaches into this error indicating that a lock is poisoned, returning a
/// mutable reference to the underlying guard to allow access regardless.
#[unstable(feature = "std_misc")]
pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}
impl<T> From<PoisonError<T>> for TryLockError<T> {
fn from(err: PoisonError<T>) -> TryLockError<T> {
TryLockError::Poisoned(err)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> fmt::Debug for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
TryLockError::WouldBlock => "WouldBlock".fmt(f)
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Send + Reflect> fmt::Display for TryLockError<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.description().fmt(f)
}
}
impl<T: Send + Reflect> Error for TryLockError<T> {
fn description(&self) -> &str {
match *self {
TryLockError::Poisoned(ref p) => p.description(),
TryLockError::WouldBlock => "try_lock failed because the operation would block"
}
}
fn cause(&self) -> Option<&Error> {
match *self {
TryLockError::Poisoned(ref p) => Some(p),
_ => None
}
}
}
pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-> LockResult<U>
where F: FnOnce(T) -> U {
match result {
Ok(t) => Ok(f(t)),
Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
}
}
| get_ref | identifier_name |
lod.rs | //! Structs for keeping track of terrain level of detail.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::ops::Add;
use block_position::BlockPosition;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// A strongly-typed index into various LOD-indexed arrays.
/// 0 is the highest LOD.
pub struct LODIndex(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Level of detail a block can be loaded at.
pub enum LOD {
/// Variable detail as an index into various LOD arrays.
LodIndex(LODIndex),
/// No detail: an invisible solid block that can be loaded synchronously.
Placeholder,
}
impl PartialOrd for LOD {
#[inline(always)]
fn partial_cmp(&self, other: &LOD) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LOD {
#[inline(always)]
fn cmp(&self, other: &LOD) -> Ordering {
match (*self, *other) {
(LOD::Placeholder, LOD::Placeholder) => Ordering::Equal,
(LOD::Placeholder, LOD::LodIndex(_)) => Ordering::Less,
(LOD::LodIndex(_), LOD::Placeholder) => Ordering::Greater,
(LOD::LodIndex(idx1), LOD::LodIndex(idx2)) =>
// A greater level of detail is a lower index, so invert the result of the index comparison.
match idx1.cmp(&idx2) {
Ordering::Less => Ordering::Greater,
Ordering::Greater => Ordering::Less,
ord => ord,
}
}
}
}
/// Data structure to keep track of a position's owners, requested LODs, and current LOD.
pub struct LODMap {
loaded: HashMap<BlockPosition, BlockLoadState>,
}
impl LODMap {
#[allow(missing_docs)]
pub fn new() -> LODMap {
LODMap {
loaded: HashMap::new(),
}
}
/// Find out what LOD is up at a `position`.
pub fn get<'a>(
&'a self,
position: &BlockPosition,
owner: OwnerId,
) -> Option<(Option<LOD>, &'a Vec<(OwnerId, LOD)>)> {
self.loaded.get(position).map(|bls| {
let p = bls.owner_lods.iter().position(|&(o, _)| o == owner);
let lod = p.map(|p| bls.owner_lods[p].1);
(lod, &bls.owner_lods)
})
}
// TODO: Can probably get rid of the LODChange returns; we only assert with em.
/// Acquire/update an owner's handle in `position`.
/// Returns (owner's previous LOD, LOD change if the location's max LOD changes).
pub fn insert(
&mut self,
position: BlockPosition,
lod: LOD,
owner: OwnerId,
) -> (Option<LOD>, Option<LODChange>) {
match self.loaded.entry(position) {
Entry::Vacant(entry) => {
entry.insert(BlockLoadState {
owner_lods: vec!((owner, lod)),
loaded_lod: lod,
});
(
None,
Some(LODChange {
loaded: None,
desired: Some(lod),
}),
)
},
Entry::Occupied(mut entry) => {
let block_load_state = entry.get_mut();
let prev_lod;
match block_load_state.owner_lods.iter().position(|&(o, _)| o == owner) {
None => {
block_load_state.owner_lods.push((owner, lod));
prev_lod = None;
},
Some(position) => {
let &mut (_, ref mut cur_lod) = block_load_state.owner_lods.get_mut(position).unwrap();
prev_lod = Some(*cur_lod);
if lod == *cur_lod {
return (prev_lod, None);
}
*cur_lod = lod;
},
};
let (_, new_lod) = *block_load_state.owner_lods.iter().max_by(|&&(_, x)| x).unwrap();
if new_lod == block_load_state.loaded_lod {
// Already loaded at the right LOD.
return (prev_lod, None);
}
let loaded_lod = Some(block_load_state.loaded_lod);
block_load_state.loaded_lod = new_lod;
(
prev_lod,
Some(LODChange {
loaded: loaded_lod,
desired: Some(new_lod),
}),
)
},
}
}
/// Release an owner's handle on `position`.
/// Returns (owner's previous LOD, LOD change if the location's LOD changes).
pub fn remove(
&mut self,
position: BlockPosition,
owner: OwnerId,
) -> (Option<LOD>, Option<LODChange>) {
match self.loaded.entry(position) {
Entry::Vacant(_) => (None, None),
Entry::Occupied(mut entry) => {
let mut remove = false;
let r = {
let mut r = || {
let block_load_state = entry.get_mut();
let prev_lod;
match block_load_state.owner_lods.iter().position(|&(o, _)| o == owner) {
None => {
return (None, None);
},
Some(position) => {
let (_, lod) = block_load_state.owner_lods.swap_remove(position);
prev_lod = Some(lod);
},
};
let loaded_lod = block_load_state.loaded_lod;
let new_lod;
match block_load_state.owner_lods.iter().max_by(|&&(_, x)| x) {
None => {
remove = true;
return (
prev_lod,
Some(LODChange {
desired: None,
loaded: Some(loaded_lod),
}),
)
},
Some(&(_, lod)) => {
new_lod = lod;
},
}
if new_lod == loaded_lod {
// Already loaded at the right LOD.
return (prev_lod, None);
}
block_load_state.loaded_lod = new_lod;
(
prev_lod,
Some(LODChange {
loaded: Some(loaded_lod),
desired: Some(new_lod),
}),
)
};
r()
};
if remove {
entry.remove();
}
r
},
}
}
}
/// A before and after LOD struct.
pub struct LODChange {
/// The target LOD.
pub desired: Option<LOD>,
/// Currently-loaded LOD
pub loaded: Option<LOD>,
}
/// These are used to identify the owners of terrain load operations.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct | (u32);
impl Add<u32> for OwnerId {
type Output = OwnerId;
fn add(self, rhs: u32) -> OwnerId {
let OwnerId(id) = self;
OwnerId(id + rhs)
}
}
struct BlockLoadState {
/// The LOD indexes requested by each owner of this block.
// TODO: Change this back to a HashMap once initial capacity is zero for those.
pub owner_lods: Vec<(OwnerId, LOD)>,
pub loaded_lod: LOD,
}
| OwnerId | identifier_name |
lod.rs | //! Structs for keeping track of terrain level of detail.
use std::cmp::Ordering;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::ops::Add;
use block_position::BlockPosition;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// A strongly-typed index into various LOD-indexed arrays.
/// 0 is the highest LOD.
pub struct LODIndex(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Level of detail a block can be loaded at.
pub enum LOD {
/// Variable detail as an index into various LOD arrays.
LodIndex(LODIndex),
/// No detail: an invisible solid block that can be loaded synchronously.
Placeholder,
}
impl PartialOrd for LOD {
#[inline(always)]
fn partial_cmp(&self, other: &LOD) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for LOD {
#[inline(always)]
fn cmp(&self, other: &LOD) -> Ordering {
match (*self, *other) {
(LOD::Placeholder, LOD::Placeholder) => Ordering::Equal,
(LOD::Placeholder, LOD::LodIndex(_)) => Ordering::Less,
(LOD::LodIndex(_), LOD::Placeholder) => Ordering::Greater,
(LOD::LodIndex(idx1), LOD::LodIndex(idx2)) =>
// A greater level of detail is a lower index, so invert the result of the index comparison.
match idx1.cmp(&idx2) {
Ordering::Less => Ordering::Greater,
Ordering::Greater => Ordering::Less,
ord => ord,
}
}
}
}
/// Data structure to keep track of a position's owners, requested LODs, and current LOD.
pub struct LODMap {
loaded: HashMap<BlockPosition, BlockLoadState>,
}
impl LODMap {
#[allow(missing_docs)]
pub fn new() -> LODMap {
LODMap {
loaded: HashMap::new(),
}
}
/// Find out what LOD is up at a `position`.
pub fn get<'a>(
&'a self,
position: &BlockPosition,
owner: OwnerId,
) -> Option<(Option<LOD>, &'a Vec<(OwnerId, LOD)>)> {
self.loaded.get(position).map(|bls| {
let p = bls.owner_lods.iter().position(|&(o, _)| o == owner);
let lod = p.map(|p| bls.owner_lods[p].1);
(lod, &bls.owner_lods)
})
}
// TODO: Can probably get rid of the LODChange returns; we only assert with em.
/// Acquire/update an owner's handle in `position`.
/// Returns (owner's previous LOD, LOD change if the location's max LOD changes).
pub fn insert(
&mut self,
position: BlockPosition,
lod: LOD,
owner: OwnerId,
) -> (Option<LOD>, Option<LODChange>) {
match self.loaded.entry(position) {
Entry::Vacant(entry) => {
entry.insert(BlockLoadState {
owner_lods: vec!((owner, lod)),
loaded_lod: lod,
});
(
None,
Some(LODChange {
loaded: None,
desired: Some(lod),
}),
)
},
Entry::Occupied(mut entry) => {
let block_load_state = entry.get_mut();
let prev_lod;
match block_load_state.owner_lods.iter().position(|&(o, _)| o == owner) {
None => {
block_load_state.owner_lods.push((owner, lod));
prev_lod = None;
},
Some(position) => {
let &mut (_, ref mut cur_lod) = block_load_state.owner_lods.get_mut(position).unwrap();
prev_lod = Some(*cur_lod);
if lod == *cur_lod {
return (prev_lod, None);
}
*cur_lod = lod;
},
};
let (_, new_lod) = *block_load_state.owner_lods.iter().max_by(|&&(_, x)| x).unwrap();
if new_lod == block_load_state.loaded_lod {
// Already loaded at the right LOD.
return (prev_lod, None);
}
let loaded_lod = Some(block_load_state.loaded_lod);
block_load_state.loaded_lod = new_lod;
(
prev_lod,
Some(LODChange {
loaded: loaded_lod,
desired: Some(new_lod),
}),
)
},
}
}
/// Release an owner's handle on `position`.
/// Returns (owner's previous LOD, LOD change if the location's LOD changes).
pub fn remove(
&mut self,
position: BlockPosition,
owner: OwnerId,
) -> (Option<LOD>, Option<LODChange>) {
match self.loaded.entry(position) {
Entry::Vacant(_) => (None, None),
Entry::Occupied(mut entry) => {
let mut remove = false;
let r = {
let mut r = || {
let block_load_state = entry.get_mut();
let prev_lod;
match block_load_state.owner_lods.iter().position(|&(o, _)| o == owner) {
None => {
return (None, None);
},
Some(position) => {
let (_, lod) = block_load_state.owner_lods.swap_remove(position);
prev_lod = Some(lod);
},
};
let loaded_lod = block_load_state.loaded_lod;
let new_lod;
match block_load_state.owner_lods.iter().max_by(|&&(_, x)| x) {
None => {
remove = true;
return (
prev_lod,
Some(LODChange {
desired: None,
loaded: Some(loaded_lod),
}),
)
},
Some(&(_, lod)) => {
new_lod = lod;
},
}
if new_lod == loaded_lod {
// Already loaded at the right LOD.
return (prev_lod, None);
}
block_load_state.loaded_lod = new_lod;
(
prev_lod,
Some(LODChange {
loaded: Some(loaded_lod), | r()
};
if remove {
entry.remove();
}
r
},
}
}
}
/// A before and after LOD struct.
pub struct LODChange {
/// The target LOD.
pub desired: Option<LOD>,
/// Currently-loaded LOD
pub loaded: Option<LOD>,
}
/// These are used to identify the owners of terrain load operations.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Default)]
pub struct OwnerId(u32);
impl Add<u32> for OwnerId {
type Output = OwnerId;
fn add(self, rhs: u32) -> OwnerId {
let OwnerId(id) = self;
OwnerId(id + rhs)
}
}
struct BlockLoadState {
/// The LOD indexes requested by each owner of this block.
// TODO: Change this back to a HashMap once initial capacity is zero for those.
pub owner_lods: Vec<(OwnerId, LOD)>,
pub loaded_lod: LOD,
} | desired: Some(new_lod),
}),
)
}; | random_line_split |
params.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::{str, fs};
use std::time::Duration;
use util::{Address, U256, version_data};
use util::journaldb::Algorithm;
use ethcore::spec::Spec;
use ethcore::ethereum;
use ethcore::client::Mode;
use ethcore::miner::{GasPricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn | () -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let spec = match s {
"frontier" | "homestead" | "mainnet" => SpecType::Mainnet,
"frontier-dogmatic" | "homestead-dogmatic" | "classic" => SpecType::Classic,
"morden" | "testnet" => SpecType::Testnet,
"ropsten" => SpecType::Ropsten,
"olympic" => SpecType::Olympic,
"expanse" => SpecType::Expanse,
"dev" => SpecType::Dev,
other => SpecType::Custom(other.into()),
};
Ok(spec)
}
}
impl SpecType {
pub fn spec(&self) -> Result<Spec, String> {
match *self {
SpecType::Mainnet => Ok(ethereum::new_frontier()),
SpecType::Testnet => Ok(ethereum::new_morden()),
SpecType::Ropsten => Ok(ethereum::new_ropsten()),
SpecType::Olympic => Ok(ethereum::new_olympic()),
SpecType::Classic => Ok(ethereum::new_classic()),
SpecType::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => {
let file = try!(fs::File::open(filename).map_err(|_| "Could not load specification file."));
Spec::load(file)
}
}
}
}
#[derive(Debug, PartialEq)]
pub enum Pruning {
Specific(Algorithm),
Auto,
}
impl Default for Pruning {
fn default() -> Self {
Pruning::Auto
}
}
impl str::FromStr for Pruning {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Pruning::Auto),
other => other.parse().map(Pruning::Specific),
}
}
}
impl Pruning {
pub fn to_algorithm(&self, user_defaults: &UserDefaults) -> Algorithm {
match *self {
Pruning::Specific(algo) => algo,
Pruning::Auto => user_defaults.pruning,
}
}
}
#[derive(Debug, PartialEq)]
pub struct ResealPolicy {
pub own: bool,
pub external: bool,
}
impl Default for ResealPolicy {
fn default() -> Self {
ResealPolicy {
own: true,
external: true,
}
}
}
impl str::FromStr for ResealPolicy {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (own, external) = match s {
"none" => (false, false),
"own" => (true, false),
"ext" => (false, true),
"all" => (true, true),
x => return Err(format!("Invalid reseal value: {}", x)),
};
let reseal = ResealPolicy {
own: own,
external: external,
};
Ok(reseal)
}
}
#[derive(Debug, PartialEq)]
pub struct AccountsConfig {
pub iterations: u32,
pub testnet: bool,
pub password_files: Vec<String>,
pub unlocked_accounts: Vec<Address>,
}
impl Default for AccountsConfig {
fn default() -> Self {
AccountsConfig {
iterations: 10240,
testnet: false,
password_files: Vec::new(),
unlocked_accounts: Vec::new(),
}
}
}
#[derive(Debug, PartialEq)]
pub enum GasPricerConfig {
Fixed(U256),
Calibrated {
usd_per_tx: f32,
recalibration_period: Duration,
}
}
impl Default for GasPricerConfig {
fn default() -> Self {
GasPricerConfig::Calibrated {
usd_per_tx: 0.0025f32,
recalibration_period: Duration::from_secs(3600),
}
}
}
impl Into<GasPricer> for GasPricerConfig {
fn into(self) -> GasPricer {
match self {
GasPricerConfig::Fixed(u) => GasPricer::Fixed(u),
GasPricerConfig::Calibrated { usd_per_tx, recalibration_period } => {
GasPricer::new_calibrated(GasPriceCalibratorOptions {
usd_per_tx: usd_per_tx,
recalibration_period: recalibration_period,
})
}
}
}
}
#[derive(Debug, PartialEq)]
pub struct MinerExtras {
pub author: Address,
pub extra_data: Vec<u8>,
pub gas_floor_target: U256,
pub gas_ceil_target: U256,
pub transactions_limit: usize,
}
impl Default for MinerExtras {
fn default() -> Self {
MinerExtras {
author: Default::default(),
extra_data: version_data(),
gas_floor_target: U256::from(4_700_000),
gas_ceil_target: U256::from(6_283_184),
transactions_limit: 1024,
}
}
}
/// 3-value enum.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Switch {
/// True.
On,
/// False.
Off,
/// Auto.
Auto,
}
impl Default for Switch {
fn default() -> Self {
Switch::Auto
}
}
impl str::FromStr for Switch {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"on" => Ok(Switch::On),
"off" => Ok(Switch::Off),
"auto" => Ok(Switch::Auto),
other => Err(format!("Invalid switch value: {}", other))
}
}
}
pub fn tracing_switch_to_bool(switch: Switch, user_defaults: &UserDefaults) -> Result<bool, String> {
match (user_defaults.is_first_launch, switch, user_defaults.tracing) {
(false, Switch::On, false) => Err("TraceDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
}
}
pub fn fatdb_switch_to_bool(switch: Switch, user_defaults: &UserDefaults, _algorithm: Algorithm) -> Result<bool, String> {
let result = match (user_defaults.is_first_launch, switch, user_defaults.fat_db) {
(false, Switch::On, false) => Err("FatDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
};
result
}
pub fn mode_switch_to_bool(switch: Option<Mode>, user_defaults: &UserDefaults) -> Result<Mode, String> {
Ok(switch.unwrap_or(user_defaults.mode.clone()))
}
#[cfg(test)]
mod tests {
use util::journaldb::Algorithm;
use user_defaults::UserDefaults;
use super::{SpecType, Pruning, ResealPolicy, Switch, tracing_switch_to_bool};
#[test]
fn test_spec_type_parsing() {
assert_eq!(SpecType::Mainnet, "frontier".parse().unwrap());
assert_eq!(SpecType::Mainnet, "homestead".parse().unwrap());
assert_eq!(SpecType::Mainnet, "mainnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "testnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "morden".parse().unwrap());
assert_eq!(SpecType::Ropsten, "ropsten".parse().unwrap());
assert_eq!(SpecType::Olympic, "olympic".parse().unwrap());
}
#[test]
fn test_spec_type_default() {
assert_eq!(SpecType::Mainnet, SpecType::default());
}
#[test]
fn test_pruning_parsing() {
assert_eq!(Pruning::Auto, "auto".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::Archive), "archive".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::EarlyMerge), "light".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::OverlayRecent), "fast".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::RefCounted), "basic".parse().unwrap());
}
#[test]
fn test_pruning_default() {
assert_eq!(Pruning::Auto, Pruning::default());
}
#[test]
fn test_reseal_policy_parsing() {
let none = ResealPolicy { own: false, external: false };
let own = ResealPolicy { own: true, external: false };
let ext = ResealPolicy { own: false, external: true };
let all = ResealPolicy { own: true, external: true };
assert_eq!(none, "none".parse().unwrap());
assert_eq!(own, "own".parse().unwrap());
assert_eq!(ext, "ext".parse().unwrap());
assert_eq!(all, "all".parse().unwrap());
}
#[test]
fn test_reseal_policy_default() {
let all = ResealPolicy { own: true, external: true };
assert_eq!(all, ResealPolicy::default());
}
#[test]
fn test_switch_parsing() {
assert_eq!(Switch::On, "on".parse().unwrap());
assert_eq!(Switch::Off, "off".parse().unwrap());
assert_eq!(Switch::Auto, "auto".parse().unwrap());
}
#[test]
fn test_switch_default() {
assert_eq!(Switch::default(), Switch::Auto);
}
fn user_defaults_with_tracing(first_launch: bool, tracing: bool) -> UserDefaults {
let mut ud = UserDefaults::default();
ud.is_first_launch = first_launch;
ud.tracing = tracing;
ud
}
#[test]
fn test_switch_to_bool() {
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, false)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, false)).is_err());
}
}
| default | identifier_name |
params.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::{str, fs};
use std::time::Duration;
use util::{Address, U256, version_data};
use util::journaldb::Algorithm;
use ethcore::spec::Spec;
use ethcore::ethereum;
use ethcore::client::Mode;
use ethcore::miner::{GasPricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn default() -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let spec = match s {
"frontier" | "homestead" | "mainnet" => SpecType::Mainnet,
"frontier-dogmatic" | "homestead-dogmatic" | "classic" => SpecType::Classic,
"morden" | "testnet" => SpecType::Testnet,
"ropsten" => SpecType::Ropsten,
"olympic" => SpecType::Olympic,
"expanse" => SpecType::Expanse,
"dev" => SpecType::Dev,
other => SpecType::Custom(other.into()),
};
Ok(spec)
}
}
impl SpecType {
pub fn spec(&self) -> Result<Spec, String> {
match *self {
SpecType::Mainnet => Ok(ethereum::new_frontier()),
SpecType::Testnet => Ok(ethereum::new_morden()),
SpecType::Ropsten => Ok(ethereum::new_ropsten()),
SpecType::Olympic => Ok(ethereum::new_olympic()),
SpecType::Classic => Ok(ethereum::new_classic()),
SpecType::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => {
let file = try!(fs::File::open(filename).map_err(|_| "Could not load specification file."));
Spec::load(file)
}
}
}
}
#[derive(Debug, PartialEq)]
pub enum Pruning {
Specific(Algorithm),
Auto,
}
impl Default for Pruning {
fn default() -> Self {
Pruning::Auto
}
}
impl str::FromStr for Pruning {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Pruning::Auto),
other => other.parse().map(Pruning::Specific),
}
}
}
impl Pruning {
pub fn to_algorithm(&self, user_defaults: &UserDefaults) -> Algorithm {
match *self {
Pruning::Specific(algo) => algo,
Pruning::Auto => user_defaults.pruning,
}
}
}
#[derive(Debug, PartialEq)]
pub struct ResealPolicy {
pub own: bool,
pub external: bool,
}
impl Default for ResealPolicy {
fn default() -> Self {
ResealPolicy {
own: true,
external: true,
}
}
}
impl str::FromStr for ResealPolicy {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (own, external) = match s {
"none" => (false, false),
"own" => (true, false),
"ext" => (false, true),
"all" => (true, true),
x => return Err(format!("Invalid reseal value: {}", x)),
};
let reseal = ResealPolicy {
own: own,
external: external,
};
Ok(reseal)
}
}
#[derive(Debug, PartialEq)]
pub struct AccountsConfig {
pub iterations: u32,
pub testnet: bool,
pub password_files: Vec<String>,
pub unlocked_accounts: Vec<Address>,
}
impl Default for AccountsConfig {
fn default() -> Self {
AccountsConfig {
iterations: 10240,
testnet: false,
password_files: Vec::new(),
unlocked_accounts: Vec::new(),
}
}
}
#[derive(Debug, PartialEq)]
pub enum GasPricerConfig {
Fixed(U256),
Calibrated {
usd_per_tx: f32,
recalibration_period: Duration,
}
}
impl Default for GasPricerConfig {
fn default() -> Self {
GasPricerConfig::Calibrated {
usd_per_tx: 0.0025f32,
recalibration_period: Duration::from_secs(3600),
}
}
}
impl Into<GasPricer> for GasPricerConfig {
fn into(self) -> GasPricer {
match self {
GasPricerConfig::Fixed(u) => GasPricer::Fixed(u),
GasPricerConfig::Calibrated { usd_per_tx, recalibration_period } => |
}
}
}
#[derive(Debug, PartialEq)]
pub struct MinerExtras {
pub author: Address,
pub extra_data: Vec<u8>,
pub gas_floor_target: U256,
pub gas_ceil_target: U256,
pub transactions_limit: usize,
}
impl Default for MinerExtras {
fn default() -> Self {
MinerExtras {
author: Default::default(),
extra_data: version_data(),
gas_floor_target: U256::from(4_700_000),
gas_ceil_target: U256::from(6_283_184),
transactions_limit: 1024,
}
}
}
/// 3-value enum.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Switch {
/// True.
On,
/// False.
Off,
/// Auto.
Auto,
}
impl Default for Switch {
fn default() -> Self {
Switch::Auto
}
}
impl str::FromStr for Switch {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"on" => Ok(Switch::On),
"off" => Ok(Switch::Off),
"auto" => Ok(Switch::Auto),
other => Err(format!("Invalid switch value: {}", other))
}
}
}
pub fn tracing_switch_to_bool(switch: Switch, user_defaults: &UserDefaults) -> Result<bool, String> {
match (user_defaults.is_first_launch, switch, user_defaults.tracing) {
(false, Switch::On, false) => Err("TraceDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
}
}
pub fn fatdb_switch_to_bool(switch: Switch, user_defaults: &UserDefaults, _algorithm: Algorithm) -> Result<bool, String> {
let result = match (user_defaults.is_first_launch, switch, user_defaults.fat_db) {
(false, Switch::On, false) => Err("FatDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
};
result
}
pub fn mode_switch_to_bool(switch: Option<Mode>, user_defaults: &UserDefaults) -> Result<Mode, String> {
Ok(switch.unwrap_or(user_defaults.mode.clone()))
}
#[cfg(test)]
mod tests {
use util::journaldb::Algorithm;
use user_defaults::UserDefaults;
use super::{SpecType, Pruning, ResealPolicy, Switch, tracing_switch_to_bool};
#[test]
fn test_spec_type_parsing() {
assert_eq!(SpecType::Mainnet, "frontier".parse().unwrap());
assert_eq!(SpecType::Mainnet, "homestead".parse().unwrap());
assert_eq!(SpecType::Mainnet, "mainnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "testnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "morden".parse().unwrap());
assert_eq!(SpecType::Ropsten, "ropsten".parse().unwrap());
assert_eq!(SpecType::Olympic, "olympic".parse().unwrap());
}
#[test]
fn test_spec_type_default() {
assert_eq!(SpecType::Mainnet, SpecType::default());
}
#[test]
fn test_pruning_parsing() {
assert_eq!(Pruning::Auto, "auto".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::Archive), "archive".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::EarlyMerge), "light".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::OverlayRecent), "fast".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::RefCounted), "basic".parse().unwrap());
}
#[test]
fn test_pruning_default() {
assert_eq!(Pruning::Auto, Pruning::default());
}
#[test]
fn test_reseal_policy_parsing() {
let none = ResealPolicy { own: false, external: false };
let own = ResealPolicy { own: true, external: false };
let ext = ResealPolicy { own: false, external: true };
let all = ResealPolicy { own: true, external: true };
assert_eq!(none, "none".parse().unwrap());
assert_eq!(own, "own".parse().unwrap());
assert_eq!(ext, "ext".parse().unwrap());
assert_eq!(all, "all".parse().unwrap());
}
#[test]
fn test_reseal_policy_default() {
let all = ResealPolicy { own: true, external: true };
assert_eq!(all, ResealPolicy::default());
}
#[test]
fn test_switch_parsing() {
assert_eq!(Switch::On, "on".parse().unwrap());
assert_eq!(Switch::Off, "off".parse().unwrap());
assert_eq!(Switch::Auto, "auto".parse().unwrap());
}
#[test]
fn test_switch_default() {
assert_eq!(Switch::default(), Switch::Auto);
}
fn user_defaults_with_tracing(first_launch: bool, tracing: bool) -> UserDefaults {
let mut ud = UserDefaults::default();
ud.is_first_launch = first_launch;
ud.tracing = tracing;
ud
}
#[test]
fn test_switch_to_bool() {
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, false)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, false)).is_err());
}
}
| {
GasPricer::new_calibrated(GasPriceCalibratorOptions {
usd_per_tx: usd_per_tx,
recalibration_period: recalibration_period,
})
} | conditional_block |
params.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::{str, fs};
use std::time::Duration;
use util::{Address, U256, version_data};
use util::journaldb::Algorithm;
use ethcore::spec::Spec;
use ethcore::ethereum;
use ethcore::client::Mode;
use ethcore::miner::{GasPricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn default() -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let spec = match s {
"frontier" | "homestead" | "mainnet" => SpecType::Mainnet,
"frontier-dogmatic" | "homestead-dogmatic" | "classic" => SpecType::Classic,
"morden" | "testnet" => SpecType::Testnet,
"ropsten" => SpecType::Ropsten,
"olympic" => SpecType::Olympic,
"expanse" => SpecType::Expanse,
"dev" => SpecType::Dev,
other => SpecType::Custom(other.into()),
};
Ok(spec)
}
}
impl SpecType {
pub fn spec(&self) -> Result<Spec, String> {
match *self {
SpecType::Mainnet => Ok(ethereum::new_frontier()),
SpecType::Testnet => Ok(ethereum::new_morden()),
SpecType::Ropsten => Ok(ethereum::new_ropsten()),
SpecType::Olympic => Ok(ethereum::new_olympic()),
SpecType::Classic => Ok(ethereum::new_classic()),
SpecType::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => {
let file = try!(fs::File::open(filename).map_err(|_| "Could not load specification file."));
Spec::load(file)
}
}
}
}
#[derive(Debug, PartialEq)]
pub enum Pruning {
Specific(Algorithm),
Auto,
}
impl Default for Pruning {
fn default() -> Self {
Pruning::Auto
}
}
impl str::FromStr for Pruning {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Pruning::Auto),
other => other.parse().map(Pruning::Specific),
}
}
}
impl Pruning {
pub fn to_algorithm(&self, user_defaults: &UserDefaults) -> Algorithm {
match *self {
Pruning::Specific(algo) => algo,
Pruning::Auto => user_defaults.pruning,
}
}
}
#[derive(Debug, PartialEq)]
pub struct ResealPolicy {
pub own: bool,
pub external: bool,
}
impl Default for ResealPolicy {
fn default() -> Self {
ResealPolicy {
own: true,
external: true,
}
}
}
impl str::FromStr for ResealPolicy {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (own, external) = match s {
"none" => (false, false),
"own" => (true, false),
"ext" => (false, true),
"all" => (true, true),
x => return Err(format!("Invalid reseal value: {}", x)),
};
let reseal = ResealPolicy {
own: own,
external: external,
};
Ok(reseal)
}
}
#[derive(Debug, PartialEq)]
pub struct AccountsConfig {
pub iterations: u32,
pub testnet: bool,
pub password_files: Vec<String>,
pub unlocked_accounts: Vec<Address>,
}
impl Default for AccountsConfig {
fn default() -> Self {
AccountsConfig {
iterations: 10240,
testnet: false,
password_files: Vec::new(),
unlocked_accounts: Vec::new(),
}
}
}
#[derive(Debug, PartialEq)]
pub enum GasPricerConfig {
Fixed(U256),
Calibrated {
usd_per_tx: f32,
recalibration_period: Duration,
}
}
impl Default for GasPricerConfig {
fn default() -> Self {
GasPricerConfig::Calibrated {
usd_per_tx: 0.0025f32,
recalibration_period: Duration::from_secs(3600),
}
}
}
impl Into<GasPricer> for GasPricerConfig {
fn into(self) -> GasPricer {
match self {
GasPricerConfig::Fixed(u) => GasPricer::Fixed(u),
GasPricerConfig::Calibrated { usd_per_tx, recalibration_period } => {
GasPricer::new_calibrated(GasPriceCalibratorOptions {
usd_per_tx: usd_per_tx,
recalibration_period: recalibration_period,
})
}
}
}
}
#[derive(Debug, PartialEq)]
pub struct MinerExtras {
pub author: Address,
pub extra_data: Vec<u8>,
pub gas_floor_target: U256,
pub gas_ceil_target: U256,
pub transactions_limit: usize,
}
impl Default for MinerExtras {
fn default() -> Self {
MinerExtras {
author: Default::default(),
extra_data: version_data(),
gas_floor_target: U256::from(4_700_000),
gas_ceil_target: U256::from(6_283_184),
transactions_limit: 1024,
}
}
}
/// 3-value enum.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Switch {
/// True.
On,
/// False.
Off,
/// Auto.
Auto,
}
impl Default for Switch {
fn default() -> Self {
Switch::Auto
}
}
impl str::FromStr for Switch {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"on" => Ok(Switch::On),
"off" => Ok(Switch::Off),
"auto" => Ok(Switch::Auto),
other => Err(format!("Invalid switch value: {}", other))
}
}
}
pub fn tracing_switch_to_bool(switch: Switch, user_defaults: &UserDefaults) -> Result<bool, String> {
match (user_defaults.is_first_launch, switch, user_defaults.tracing) {
(false, Switch::On, false) => Err("TraceDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
}
}
pub fn fatdb_switch_to_bool(switch: Switch, user_defaults: &UserDefaults, _algorithm: Algorithm) -> Result<bool, String> {
let result = match (user_defaults.is_first_launch, switch, user_defaults.fat_db) {
(false, Switch::On, false) => Err("FatDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
};
result
}
pub fn mode_switch_to_bool(switch: Option<Mode>, user_defaults: &UserDefaults) -> Result<Mode, String> {
Ok(switch.unwrap_or(user_defaults.mode.clone()))
}
#[cfg(test)]
mod tests {
use util::journaldb::Algorithm;
use user_defaults::UserDefaults;
use super::{SpecType, Pruning, ResealPolicy, Switch, tracing_switch_to_bool};
#[test]
fn test_spec_type_parsing() {
assert_eq!(SpecType::Mainnet, "frontier".parse().unwrap());
assert_eq!(SpecType::Mainnet, "homestead".parse().unwrap());
assert_eq!(SpecType::Mainnet, "mainnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "testnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "morden".parse().unwrap());
assert_eq!(SpecType::Ropsten, "ropsten".parse().unwrap());
assert_eq!(SpecType::Olympic, "olympic".parse().unwrap());
}
#[test]
fn test_spec_type_default() {
assert_eq!(SpecType::Mainnet, SpecType::default());
}
#[test]
fn test_pruning_parsing() {
assert_eq!(Pruning::Auto, "auto".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::Archive), "archive".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::EarlyMerge), "light".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::OverlayRecent), "fast".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::RefCounted), "basic".parse().unwrap());
}
#[test]
fn test_pruning_default() {
assert_eq!(Pruning::Auto, Pruning::default());
}
#[test]
fn test_reseal_policy_parsing() {
let none = ResealPolicy { own: false, external: false };
let own = ResealPolicy { own: true, external: false };
let ext = ResealPolicy { own: false, external: true };
let all = ResealPolicy { own: true, external: true };
assert_eq!(none, "none".parse().unwrap());
assert_eq!(own, "own".parse().unwrap());
assert_eq!(ext, "ext".parse().unwrap());
assert_eq!(all, "all".parse().unwrap());
}
#[test]
fn test_reseal_policy_default() {
let all = ResealPolicy { own: true, external: true };
assert_eq!(all, ResealPolicy::default());
}
#[test]
fn test_switch_parsing() {
assert_eq!(Switch::On, "on".parse().unwrap());
assert_eq!(Switch::Off, "off".parse().unwrap());
assert_eq!(Switch::Auto, "auto".parse().unwrap());
}
#[test]
fn test_switch_default() |
fn user_defaults_with_tracing(first_launch: bool, tracing: bool) -> UserDefaults {
let mut ud = UserDefaults::default();
ud.is_first_launch = first_launch;
ud.tracing = tracing;
ud
}
#[test]
fn test_switch_to_bool() {
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, false)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, false)).is_err());
}
}
| {
assert_eq!(Switch::default(), Switch::Auto);
} | identifier_body |
params.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use std::{str, fs};
use std::time::Duration;
use util::{Address, U256, version_data};
use util::journaldb::Algorithm;
use ethcore::spec::Spec;
use ethcore::ethereum;
use ethcore::client::Mode;
use ethcore::miner::{GasPricer, GasPriceCalibratorOptions};
use user_defaults::UserDefaults;
#[derive(Debug, PartialEq)]
pub enum SpecType {
Mainnet,
Testnet,
Ropsten,
Olympic,
Classic,
Expanse,
Dev,
Custom(String),
}
impl Default for SpecType {
fn default() -> Self {
SpecType::Mainnet
}
}
impl str::FromStr for SpecType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let spec = match s {
"frontier" | "homestead" | "mainnet" => SpecType::Mainnet,
"frontier-dogmatic" | "homestead-dogmatic" | "classic" => SpecType::Classic,
"morden" | "testnet" => SpecType::Testnet,
"ropsten" => SpecType::Ropsten,
"olympic" => SpecType::Olympic,
"expanse" => SpecType::Expanse,
"dev" => SpecType::Dev,
other => SpecType::Custom(other.into()),
};
Ok(spec)
}
}
impl SpecType {
pub fn spec(&self) -> Result<Spec, String> {
match *self {
SpecType::Mainnet => Ok(ethereum::new_frontier()),
SpecType::Testnet => Ok(ethereum::new_morden()),
SpecType::Ropsten => Ok(ethereum::new_ropsten()),
SpecType::Olympic => Ok(ethereum::new_olympic()),
SpecType::Classic => Ok(ethereum::new_classic()),
SpecType::Expanse => Ok(ethereum::new_expanse()),
SpecType::Dev => Ok(Spec::new_instant()),
SpecType::Custom(ref filename) => {
let file = try!(fs::File::open(filename).map_err(|_| "Could not load specification file."));
Spec::load(file)
}
}
}
}
#[derive(Debug, PartialEq)]
pub enum Pruning {
Specific(Algorithm),
Auto,
}
impl Default for Pruning {
fn default() -> Self {
Pruning::Auto
}
}
impl str::FromStr for Pruning {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"auto" => Ok(Pruning::Auto),
other => other.parse().map(Pruning::Specific),
}
}
}
impl Pruning {
pub fn to_algorithm(&self, user_defaults: &UserDefaults) -> Algorithm {
match *self {
Pruning::Specific(algo) => algo,
Pruning::Auto => user_defaults.pruning,
}
}
}
#[derive(Debug, PartialEq)]
pub struct ResealPolicy {
pub own: bool,
pub external: bool,
}
impl Default for ResealPolicy {
fn default() -> Self {
ResealPolicy {
own: true,
external: true,
}
}
}
impl str::FromStr for ResealPolicy {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (own, external) = match s {
"none" => (false, false),
"own" => (true, false),
"ext" => (false, true),
"all" => (true, true),
x => return Err(format!("Invalid reseal value: {}", x)),
};
let reseal = ResealPolicy {
own: own,
external: external,
};
Ok(reseal)
}
}
#[derive(Debug, PartialEq)]
pub struct AccountsConfig {
pub iterations: u32,
pub testnet: bool,
pub password_files: Vec<String>,
pub unlocked_accounts: Vec<Address>,
}
impl Default for AccountsConfig {
fn default() -> Self {
AccountsConfig {
iterations: 10240,
testnet: false,
password_files: Vec::new(),
unlocked_accounts: Vec::new(),
}
}
}
#[derive(Debug, PartialEq)]
pub enum GasPricerConfig {
Fixed(U256),
Calibrated {
usd_per_tx: f32,
recalibration_period: Duration,
}
}
impl Default for GasPricerConfig {
fn default() -> Self {
GasPricerConfig::Calibrated {
usd_per_tx: 0.0025f32,
recalibration_period: Duration::from_secs(3600),
}
}
}
impl Into<GasPricer> for GasPricerConfig {
fn into(self) -> GasPricer {
match self {
GasPricerConfig::Fixed(u) => GasPricer::Fixed(u),
GasPricerConfig::Calibrated { usd_per_tx, recalibration_period } => {
GasPricer::new_calibrated(GasPriceCalibratorOptions {
usd_per_tx: usd_per_tx,
recalibration_period: recalibration_period,
})
}
}
}
}
#[derive(Debug, PartialEq)]
pub struct MinerExtras {
pub author: Address,
pub extra_data: Vec<u8>,
pub gas_floor_target: U256,
pub gas_ceil_target: U256,
pub transactions_limit: usize,
}
impl Default for MinerExtras { | author: Default::default(),
extra_data: version_data(),
gas_floor_target: U256::from(4_700_000),
gas_ceil_target: U256::from(6_283_184),
transactions_limit: 1024,
}
}
}
/// 3-value enum.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Switch {
/// True.
On,
/// False.
Off,
/// Auto.
Auto,
}
impl Default for Switch {
fn default() -> Self {
Switch::Auto
}
}
impl str::FromStr for Switch {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"on" => Ok(Switch::On),
"off" => Ok(Switch::Off),
"auto" => Ok(Switch::Auto),
other => Err(format!("Invalid switch value: {}", other))
}
}
}
pub fn tracing_switch_to_bool(switch: Switch, user_defaults: &UserDefaults) -> Result<bool, String> {
match (user_defaults.is_first_launch, switch, user_defaults.tracing) {
(false, Switch::On, false) => Err("TraceDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
}
}
pub fn fatdb_switch_to_bool(switch: Switch, user_defaults: &UserDefaults, _algorithm: Algorithm) -> Result<bool, String> {
let result = match (user_defaults.is_first_launch, switch, user_defaults.fat_db) {
(false, Switch::On, false) => Err("FatDB resync required".into()),
(_, Switch::On, _) => Ok(true),
(_, Switch::Off, _) => Ok(false),
(_, Switch::Auto, def) => Ok(def),
};
result
}
pub fn mode_switch_to_bool(switch: Option<Mode>, user_defaults: &UserDefaults) -> Result<Mode, String> {
Ok(switch.unwrap_or(user_defaults.mode.clone()))
}
#[cfg(test)]
mod tests {
use util::journaldb::Algorithm;
use user_defaults::UserDefaults;
use super::{SpecType, Pruning, ResealPolicy, Switch, tracing_switch_to_bool};
#[test]
fn test_spec_type_parsing() {
assert_eq!(SpecType::Mainnet, "frontier".parse().unwrap());
assert_eq!(SpecType::Mainnet, "homestead".parse().unwrap());
assert_eq!(SpecType::Mainnet, "mainnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "testnet".parse().unwrap());
assert_eq!(SpecType::Testnet, "morden".parse().unwrap());
assert_eq!(SpecType::Ropsten, "ropsten".parse().unwrap());
assert_eq!(SpecType::Olympic, "olympic".parse().unwrap());
}
#[test]
fn test_spec_type_default() {
assert_eq!(SpecType::Mainnet, SpecType::default());
}
#[test]
fn test_pruning_parsing() {
assert_eq!(Pruning::Auto, "auto".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::Archive), "archive".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::EarlyMerge), "light".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::OverlayRecent), "fast".parse().unwrap());
assert_eq!(Pruning::Specific(Algorithm::RefCounted), "basic".parse().unwrap());
}
#[test]
fn test_pruning_default() {
assert_eq!(Pruning::Auto, Pruning::default());
}
#[test]
fn test_reseal_policy_parsing() {
let none = ResealPolicy { own: false, external: false };
let own = ResealPolicy { own: true, external: false };
let ext = ResealPolicy { own: false, external: true };
let all = ResealPolicy { own: true, external: true };
assert_eq!(none, "none".parse().unwrap());
assert_eq!(own, "own".parse().unwrap());
assert_eq!(ext, "ext".parse().unwrap());
assert_eq!(all, "all".parse().unwrap());
}
#[test]
fn test_reseal_policy_default() {
let all = ResealPolicy { own: true, external: true };
assert_eq!(all, ResealPolicy::default());
}
#[test]
fn test_switch_parsing() {
assert_eq!(Switch::On, "on".parse().unwrap());
assert_eq!(Switch::Off, "off".parse().unwrap());
assert_eq!(Switch::Auto, "auto".parse().unwrap());
}
#[test]
fn test_switch_default() {
assert_eq!(Switch::default(), Switch::Auto);
}
fn user_defaults_with_tracing(first_launch: bool, tracing: bool) -> UserDefaults {
let mut ud = UserDefaults::default();
ud.is_first_launch = first_launch;
ud.tracing = tracing;
ud
}
#[test]
fn test_switch_to_bool() {
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(true, false)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, true)).unwrap());
assert!(!tracing_switch_to_bool(Switch::Off, &user_defaults_with_tracing(false, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(true, false)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, true)).unwrap());
assert!(tracing_switch_to_bool(Switch::On, &user_defaults_with_tracing(false, false)).is_err());
}
} | fn default() -> Self {
MinerExtras { | random_line_split |
frameobject.rs | use libc::c_int;
use crate::code::{PyCodeObject, CO_MAXBLOCKS};
use crate::object::*;
use crate::pyport::Py_ssize_t;
use crate::pystate::PyThreadState;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PyTryBlock {
pub b_type: c_int,
pub b_handler: c_int,
pub b_level: c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PyFrameObject {
#[cfg(py_sys_config = "Py_TRACE_REFS")]
pub _ob_next: *mut PyObject,
#[cfg(py_sys_config = "Py_TRACE_REFS")]
pub _ob_prev: *mut PyObject,
pub ob_refcnt: Py_ssize_t,
pub ob_type: *mut PyTypeObject,
pub ob_size: Py_ssize_t,
pub f_back: *mut PyFrameObject, /* previous frame, or NULL */
pub f_code: *mut PyCodeObject, /* code segment */
pub f_builtins: *mut PyObject, /* builtin symbol table (PyDictObject) */
pub f_globals: *mut PyObject, /* global symbol table (PyDictObject) */
pub f_locals: *mut PyObject, /* local symbol table (any mapping) */
pub f_valuestack: *mut *mut PyObject, /* points after the last local */
/* Next free slot in f_valuestack. Frame creation sets to f_valuestack.
Frame evaluation usually NULLs it, but a frame that yields sets it
to the current stack top. */
pub f_stacktop: *mut *mut PyObject,
pub f_trace: *mut PyObject, /* Trace function */
pub f_exc_type: *mut PyObject,
pub f_exc_value: *mut PyObject,
pub f_exc_traceback: *mut PyObject,
pub f_tstate: *mut PyThreadState,
pub f_lasti: c_int, /* Last instruction if called */
/* Call PyFrame_GetLineNumber() instead of reading this field
directly. As of 2.3 f_lineno is only valid when tracing is
active (i.e. when f_trace is set). At other times we use
PyCode_Addr2Line to calculate the line from the current
bytecode index. */
pub f_lineno: c_int, /* Current line number */
pub f_iblock: c_int, /* index in f_blockstack */
pub f_blockstack: [PyTryBlock; CO_MAXBLOCKS], /* for try and loop blocks */
pub f_localsplus: [*mut PyObject; 1], /* locals+stack, dynamically sized */
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PyFrame_Type: PyTypeObject;
}
#[inline]
pub unsafe fn | (op: *mut PyObject) -> c_int {
((*op).ob_type == &mut PyFrame_Type) as c_int
}
ignore! {
#[inline]
pub unsafe fn PyFrame_IsRestricted(f: *mut PyFrameObject) -> c_int {
((*f).f_builtins!= (*(*(*f).f_tstate).interp).builtins) as c_int
}
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub fn PyFrame_New(
tstate: *mut PyThreadState,
code: *mut PyCodeObject,
globals: *mut PyObject,
locals: *mut PyObject,
) -> *mut PyFrameObject;
pub fn PyFrame_BlockSetup(
f: *mut PyFrameObject,
_type: c_int,
handler: c_int,
level: c_int,
) -> ();
pub fn PyFrame_BlockPop(f: *mut PyFrameObject) -> *mut PyTryBlock;
pub fn PyFrame_LocalsToFast(f: *mut PyFrameObject, clear: c_int) -> ();
pub fn PyFrame_FastToLocals(f: *mut PyFrameObject) -> ();
pub fn PyFrame_ClearFreeList() -> c_int;
pub fn PyFrame_GetLineNumber(f: *mut PyFrameObject) -> c_int;
}
| PyFrame_Check | identifier_name |
frameobject.rs | use libc::c_int;
use crate::code::{PyCodeObject, CO_MAXBLOCKS};
use crate::object::*;
use crate::pyport::Py_ssize_t;
use crate::pystate::PyThreadState;
| pub b_type: c_int,
pub b_handler: c_int,
pub b_level: c_int,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct PyFrameObject {
#[cfg(py_sys_config = "Py_TRACE_REFS")]
pub _ob_next: *mut PyObject,
#[cfg(py_sys_config = "Py_TRACE_REFS")]
pub _ob_prev: *mut PyObject,
pub ob_refcnt: Py_ssize_t,
pub ob_type: *mut PyTypeObject,
pub ob_size: Py_ssize_t,
pub f_back: *mut PyFrameObject, /* previous frame, or NULL */
pub f_code: *mut PyCodeObject, /* code segment */
pub f_builtins: *mut PyObject, /* builtin symbol table (PyDictObject) */
pub f_globals: *mut PyObject, /* global symbol table (PyDictObject) */
pub f_locals: *mut PyObject, /* local symbol table (any mapping) */
pub f_valuestack: *mut *mut PyObject, /* points after the last local */
/* Next free slot in f_valuestack. Frame creation sets to f_valuestack.
Frame evaluation usually NULLs it, but a frame that yields sets it
to the current stack top. */
pub f_stacktop: *mut *mut PyObject,
pub f_trace: *mut PyObject, /* Trace function */
pub f_exc_type: *mut PyObject,
pub f_exc_value: *mut PyObject,
pub f_exc_traceback: *mut PyObject,
pub f_tstate: *mut PyThreadState,
pub f_lasti: c_int, /* Last instruction if called */
/* Call PyFrame_GetLineNumber() instead of reading this field
directly. As of 2.3 f_lineno is only valid when tracing is
active (i.e. when f_trace is set). At other times we use
PyCode_Addr2Line to calculate the line from the current
bytecode index. */
pub f_lineno: c_int, /* Current line number */
pub f_iblock: c_int, /* index in f_blockstack */
pub f_blockstack: [PyTryBlock; CO_MAXBLOCKS], /* for try and loop blocks */
pub f_localsplus: [*mut PyObject; 1], /* locals+stack, dynamically sized */
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub static mut PyFrame_Type: PyTypeObject;
}
#[inline]
pub unsafe fn PyFrame_Check(op: *mut PyObject) -> c_int {
((*op).ob_type == &mut PyFrame_Type) as c_int
}
ignore! {
#[inline]
pub unsafe fn PyFrame_IsRestricted(f: *mut PyFrameObject) -> c_int {
((*f).f_builtins!= (*(*(*f).f_tstate).interp).builtins) as c_int
}
}
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub fn PyFrame_New(
tstate: *mut PyThreadState,
code: *mut PyCodeObject,
globals: *mut PyObject,
locals: *mut PyObject,
) -> *mut PyFrameObject;
pub fn PyFrame_BlockSetup(
f: *mut PyFrameObject,
_type: c_int,
handler: c_int,
level: c_int,
) -> ();
pub fn PyFrame_BlockPop(f: *mut PyFrameObject) -> *mut PyTryBlock;
pub fn PyFrame_LocalsToFast(f: *mut PyFrameObject, clear: c_int) -> ();
pub fn PyFrame_FastToLocals(f: *mut PyFrameObject) -> ();
pub fn PyFrame_ClearFreeList() -> c_int;
pub fn PyFrame_GetLineNumber(f: *mut PyFrameObject) -> c_int;
} | #[repr(C)]
#[derive(Copy, Clone)]
pub struct PyTryBlock { | random_line_split |
lib.rs | /*!
# graphite-rust
Herein lies a humble reimplementation of the graphite metrics system -- a time series database system,
with HTTP frontend and management tools.
It strikes a reasonable balance between features you need, easy management, and a rich ecosystem of tools which can talk to graphite.
`graphite-rust` aims to maintain total compatibility in both features and file formats.
The big selling point should be the ease of installation: it's just one
binary. It may be higher performance but that's not the main goal.
This work falls under the name `graphite` but in reality the package has distinct components you may want to understand:
* [`whisper`](whisper/index.html) - all the heavy lifting for parsing and writing to whisper database files
* `carbon` - the network daemon which mediates access to whisper files
* `graphite` - the HTTP REST server which handles queries. It has a minimal HTML
application for creating dashboard but I'll be skipping that. For dashboard you'll want [`grafana`](http://grafana.org/).
Status of the codes:
* `whisper`
* *DOES* open and parse header/metadata/archive info
* *IN PROGRESS* take a metric value and provide a WriteOp
* *NOT STARTED* write `vec![WriteOp]` to file
* `carbon`
* *DOESN'T DO ANYTHING*
* `graphite`
* *DOESN'T EXIST*
## Also, this is brand-new code. In the true rust spirit it does not guarantee the safety of your kittens.
*/
#![crate_name = "graphite"]
#![feature(trace_macros)]
#![feature(test)]
extern crate test;
extern crate time;
extern crate byteorder;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate regex;
extern crate whisper;
| // TODO: scuttled until I want to fix all the iron related issues
// pub mod graphite; | pub mod carbon; | random_line_split |
accept_ranges.rs | //! The Accept-Ranges request header, defined in RFC 2616, Section 14.5.
use std::io::IoResult;
use std::ascii::AsciiExt;
pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges};
pub use self::RangeUnit::{Bytes, OtherRangeUnit};
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: range-unit = bytes-unit | other-range-unit
pub enum RangeUnit {
Bytes, // bytes-unit = "bytes"
OtherRangeUnit(String), // other-range-unit = token
}
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: acceptable-ranges = 1#range-unit | "none"
pub enum AcceptableRanges {
RangeUnits(Vec<RangeUnit>),
NoAcceptableRanges,
}
impl super::HeaderConvertible for AcceptableRanges {
fn from_stream<R: Reader>(reader: &mut super::HeaderValueByteIterator<R>)
-> Option<AcceptableRanges> {
let mut range_units = Vec::new();
loop {
match reader.read_token() {
Some(token) => {
let token = token.to_ascii_lowercase();
match &token[] {
"bytes" => range_units.push(Bytes),
"none" if range_units.len() == 0 => return Some(NoAcceptableRanges),
_ => range_units.push(OtherRangeUnit(token)),
}
},
None => break,
}
}
Some(RangeUnits(range_units))
}
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
match *self {
NoAcceptableRanges => writer.write(b"none"),
RangeUnits(ref range_units) => {
for ru in range_units.iter() {
try!(writer.write(match *ru {
Bytes => b"bytes",
OtherRangeUnit(ref ru) => ru.as_bytes(),
}));
}
Ok(())
},
}
}
fn http_value(&self) -> String {
match *self {
NoAcceptableRanges => String::from_str("none"), | RangeUnits(ref range_units) => {
let mut result = String::new();
for ru in range_units.iter() {
match ru {
&Bytes => result.push_str("bytes"),
&OtherRangeUnit(ref ru) => result.push_str(&ru[]),
}
}
result
},
}
}
} | random_line_split | |
accept_ranges.rs | //! The Accept-Ranges request header, defined in RFC 2616, Section 14.5.
use std::io::IoResult;
use std::ascii::AsciiExt;
pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges};
pub use self::RangeUnit::{Bytes, OtherRangeUnit};
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: range-unit = bytes-unit | other-range-unit
pub enum RangeUnit {
Bytes, // bytes-unit = "bytes"
OtherRangeUnit(String), // other-range-unit = token
}
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: acceptable-ranges = 1#range-unit | "none"
pub enum AcceptableRanges {
RangeUnits(Vec<RangeUnit>),
NoAcceptableRanges,
}
impl super::HeaderConvertible for AcceptableRanges {
fn from_stream<R: Reader>(reader: &mut super::HeaderValueByteIterator<R>)
-> Option<AcceptableRanges> {
let mut range_units = Vec::new();
loop {
match reader.read_token() {
Some(token) => {
let token = token.to_ascii_lowercase();
match &token[] {
"bytes" => range_units.push(Bytes),
"none" if range_units.len() == 0 => return Some(NoAcceptableRanges),
_ => range_units.push(OtherRangeUnit(token)),
}
},
None => break,
}
}
Some(RangeUnits(range_units))
}
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
match *self {
NoAcceptableRanges => writer.write(b"none"),
RangeUnits(ref range_units) => {
for ru in range_units.iter() {
try!(writer.write(match *ru {
Bytes => b"bytes",
OtherRangeUnit(ref ru) => ru.as_bytes(),
}));
}
Ok(())
},
}
}
fn http_value(&self) -> String |
}
| {
match *self {
NoAcceptableRanges => String::from_str("none"),
RangeUnits(ref range_units) => {
let mut result = String::new();
for ru in range_units.iter() {
match ru {
&Bytes => result.push_str("bytes"),
&OtherRangeUnit(ref ru) => result.push_str(&ru[]),
}
}
result
},
}
} | identifier_body |
accept_ranges.rs | //! The Accept-Ranges request header, defined in RFC 2616, Section 14.5.
use std::io::IoResult;
use std::ascii::AsciiExt;
pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges};
pub use self::RangeUnit::{Bytes, OtherRangeUnit};
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: range-unit = bytes-unit | other-range-unit
pub enum RangeUnit {
Bytes, // bytes-unit = "bytes"
OtherRangeUnit(String), // other-range-unit = token
}
#[derive(Clone, PartialEq, Eq)]
// RFC 2616: acceptable-ranges = 1#range-unit | "none"
pub enum | {
RangeUnits(Vec<RangeUnit>),
NoAcceptableRanges,
}
impl super::HeaderConvertible for AcceptableRanges {
fn from_stream<R: Reader>(reader: &mut super::HeaderValueByteIterator<R>)
-> Option<AcceptableRanges> {
let mut range_units = Vec::new();
loop {
match reader.read_token() {
Some(token) => {
let token = token.to_ascii_lowercase();
match &token[] {
"bytes" => range_units.push(Bytes),
"none" if range_units.len() == 0 => return Some(NoAcceptableRanges),
_ => range_units.push(OtherRangeUnit(token)),
}
},
None => break,
}
}
Some(RangeUnits(range_units))
}
fn to_stream<W: Writer>(&self, writer: &mut W) -> IoResult<()> {
match *self {
NoAcceptableRanges => writer.write(b"none"),
RangeUnits(ref range_units) => {
for ru in range_units.iter() {
try!(writer.write(match *ru {
Bytes => b"bytes",
OtherRangeUnit(ref ru) => ru.as_bytes(),
}));
}
Ok(())
},
}
}
fn http_value(&self) -> String {
match *self {
NoAcceptableRanges => String::from_str("none"),
RangeUnits(ref range_units) => {
let mut result = String::new();
for ru in range_units.iter() {
match ru {
&Bytes => result.push_str("bytes"),
&OtherRangeUnit(ref ru) => result.push_str(&ru[]),
}
}
result
},
}
}
}
| AcceptableRanges | identifier_name |
revidx.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::{Add, Mul};
use std::str::FromStr;
use std::u32;
/// Index into a `RevLog`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RevIdx(u32);
// Implement `RevIdx`s methods
impl RevIdx {
/// Return index for first entry
pub fn zero() -> Self {
RevIdx(0)
}
/// Return successor index
pub fn succ(self) -> Self {
RevIdx(self.0 + 1)
}
/// Return previous index
///
/// Panics if index is zero.
pub fn pred(self) -> Self {
assert!(self.0 > 0);
RevIdx(self.0 - 1)
}
/// Return iterator for a range from index to `lim`.
pub fn range_to(&self, lim: Self) -> RevIdxRange {
RevIdxRange(self.0, lim.0)
}
/// Return an open ended iterator from index.
pub fn range(&self) -> RevIdxRange {
RevIdxRange(self.0, u32::MAX)
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
// Construct a `RevIdx` from a `u32`
impl From<u32> for RevIdx {
fn from(v: u32) -> Self {
RevIdx(v)
}
}
// Construct a `RevIdx` from a `usize`
// Panics if the usize is larger than u32::MAX
impl From<usize> for RevIdx {
fn from(v: usize) -> Self {
assert!(v <= u32::MAX as usize);
RevIdx(v as u32)
}
}
// Construct a `RevIdx` from a string (which may fail)
impl FromStr for RevIdx {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(RevIdx)
}
}
// Multiply operator for RevIdx * usize -> usize
// Used for constructing a byte offset for an index
impl Mul<usize> for RevIdx {
type Output = usize;
fn mul(self, other: usize) -> Self::Output {
self.0 as usize * other
}
}
// RevIdx + usize -> RevIdx
impl Add<usize> for RevIdx {
type Output = RevIdx;
fn add(self, other: usize) -> Self::Output {
RevIdx((self.0 as usize + other) as u32)
}
}
// Convert a `RevIdx` into an open-ended iterator of RevIdx values
// starting at RevIdx's value. ie, RevIdx(2).into_iter() => RevIdx(2), RevIdx(3),...
impl<'a> IntoIterator for &'a RevIdx {
type Item = RevIdx;
type IntoIter = RevIdxRange;
fn into_iter(self) -> Self::IntoIter {
self.range()
}
}
/// An open-ended or bounded iterator over a range of RevIdx
#[derive(Copy, Clone, Debug)]
pub struct RevIdxRange(u32, u32);
impl Iterator for RevIdxRange {
type Item = RevIdx;
fn next(&mut self) -> Option<Self::Item> {
if self.0 < self.1 | else {
None
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::str::FromStr;
#[test]
fn zero() {
assert_eq!(RevIdx::zero(), RevIdx(0))
}
#[test]
fn succ() {
assert_eq!(RevIdx::zero().succ(), RevIdx(1));
assert_eq!(RevIdx::zero().succ().succ(), RevIdx(2));
}
#[test]
fn pred() {
assert_eq!(RevIdx(10).pred(), RevIdx(9));
}
#[test]
#[should_panic]
fn bad_pred() {
println!("bad {:?}", RevIdx::zero().pred());
}
#[test]
fn range_to() {
let v: Vec<_> = RevIdx::zero().range_to(RevIdx(5)).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
);
}
#[test]
fn iter() {
let v: Vec<_> = RevIdx::zero().into_iter().take(5).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
)
}
#[test]
fn fromstr() {
let idx: RevIdx = FromStr::from_str("555").expect("Valid string");
assert_eq!(idx, RevIdx(555));
}
#[test]
fn fromstr_bad1() {
match RevIdx::from_str("abc123") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
#[test]
fn fromstr_bad2() {
match RevIdx::from_str("-1") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
}
| {
let ret = RevIdx(self.0);
self.0 += 1;
Some(ret)
} | conditional_block |
revidx.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::{Add, Mul};
use std::str::FromStr;
use std::u32;
/// Index into a `RevLog`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RevIdx(u32);
// Implement `RevIdx`s methods
impl RevIdx {
/// Return index for first entry
pub fn zero() -> Self {
RevIdx(0)
}
/// Return successor index
pub fn succ(self) -> Self {
RevIdx(self.0 + 1)
}
/// Return previous index
///
/// Panics if index is zero.
pub fn pred(self) -> Self {
assert!(self.0 > 0); | RevIdx(self.0 - 1)
}
/// Return iterator for a range from index to `lim`.
pub fn range_to(&self, lim: Self) -> RevIdxRange {
RevIdxRange(self.0, lim.0)
}
/// Return an open ended iterator from index.
pub fn range(&self) -> RevIdxRange {
RevIdxRange(self.0, u32::MAX)
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
// Construct a `RevIdx` from a `u32`
impl From<u32> for RevIdx {
fn from(v: u32) -> Self {
RevIdx(v)
}
}
// Construct a `RevIdx` from a `usize`
// Panics if the usize is larger than u32::MAX
impl From<usize> for RevIdx {
fn from(v: usize) -> Self {
assert!(v <= u32::MAX as usize);
RevIdx(v as u32)
}
}
// Construct a `RevIdx` from a string (which may fail)
impl FromStr for RevIdx {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(RevIdx)
}
}
// Multiply operator for RevIdx * usize -> usize
// Used for constructing a byte offset for an index
impl Mul<usize> for RevIdx {
type Output = usize;
fn mul(self, other: usize) -> Self::Output {
self.0 as usize * other
}
}
// RevIdx + usize -> RevIdx
impl Add<usize> for RevIdx {
type Output = RevIdx;
fn add(self, other: usize) -> Self::Output {
RevIdx((self.0 as usize + other) as u32)
}
}
// Convert a `RevIdx` into an open-ended iterator of RevIdx values
// starting at RevIdx's value. ie, RevIdx(2).into_iter() => RevIdx(2), RevIdx(3),...
impl<'a> IntoIterator for &'a RevIdx {
type Item = RevIdx;
type IntoIter = RevIdxRange;
fn into_iter(self) -> Self::IntoIter {
self.range()
}
}
/// An open-ended or bounded iterator over a range of RevIdx
#[derive(Copy, Clone, Debug)]
pub struct RevIdxRange(u32, u32);
impl Iterator for RevIdxRange {
type Item = RevIdx;
fn next(&mut self) -> Option<Self::Item> {
if self.0 < self.1 {
let ret = RevIdx(self.0);
self.0 += 1;
Some(ret)
} else {
None
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::str::FromStr;
#[test]
fn zero() {
assert_eq!(RevIdx::zero(), RevIdx(0))
}
#[test]
fn succ() {
assert_eq!(RevIdx::zero().succ(), RevIdx(1));
assert_eq!(RevIdx::zero().succ().succ(), RevIdx(2));
}
#[test]
fn pred() {
assert_eq!(RevIdx(10).pred(), RevIdx(9));
}
#[test]
#[should_panic]
fn bad_pred() {
println!("bad {:?}", RevIdx::zero().pred());
}
#[test]
fn range_to() {
let v: Vec<_> = RevIdx::zero().range_to(RevIdx(5)).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
);
}
#[test]
fn iter() {
let v: Vec<_> = RevIdx::zero().into_iter().take(5).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
)
}
#[test]
fn fromstr() {
let idx: RevIdx = FromStr::from_str("555").expect("Valid string");
assert_eq!(idx, RevIdx(555));
}
#[test]
fn fromstr_bad1() {
match RevIdx::from_str("abc123") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
#[test]
fn fromstr_bad2() {
match RevIdx::from_str("-1") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
} | random_line_split | |
revidx.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::{Add, Mul};
use std::str::FromStr;
use std::u32;
/// Index into a `RevLog`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RevIdx(u32);
// Implement `RevIdx`s methods
impl RevIdx {
/// Return index for first entry
pub fn zero() -> Self {
RevIdx(0)
}
/// Return successor index
pub fn succ(self) -> Self {
RevIdx(self.0 + 1)
}
/// Return previous index
///
/// Panics if index is zero.
pub fn pred(self) -> Self {
assert!(self.0 > 0);
RevIdx(self.0 - 1)
}
/// Return iterator for a range from index to `lim`.
pub fn range_to(&self, lim: Self) -> RevIdxRange {
RevIdxRange(self.0, lim.0)
}
/// Return an open ended iterator from index.
pub fn range(&self) -> RevIdxRange {
RevIdxRange(self.0, u32::MAX)
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
// Construct a `RevIdx` from a `u32`
impl From<u32> for RevIdx {
fn from(v: u32) -> Self {
RevIdx(v)
}
}
// Construct a `RevIdx` from a `usize`
// Panics if the usize is larger than u32::MAX
impl From<usize> for RevIdx {
fn from(v: usize) -> Self {
assert!(v <= u32::MAX as usize);
RevIdx(v as u32)
}
}
// Construct a `RevIdx` from a string (which may fail)
impl FromStr for RevIdx {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(RevIdx)
}
}
// Multiply operator for RevIdx * usize -> usize
// Used for constructing a byte offset for an index
impl Mul<usize> for RevIdx {
type Output = usize;
fn mul(self, other: usize) -> Self::Output {
self.0 as usize * other
}
}
// RevIdx + usize -> RevIdx
impl Add<usize> for RevIdx {
type Output = RevIdx;
fn add(self, other: usize) -> Self::Output {
RevIdx((self.0 as usize + other) as u32)
}
}
// Convert a `RevIdx` into an open-ended iterator of RevIdx values
// starting at RevIdx's value. ie, RevIdx(2).into_iter() => RevIdx(2), RevIdx(3),...
impl<'a> IntoIterator for &'a RevIdx {
type Item = RevIdx;
type IntoIter = RevIdxRange;
fn into_iter(self) -> Self::IntoIter {
self.range()
}
}
/// An open-ended or bounded iterator over a range of RevIdx
#[derive(Copy, Clone, Debug)]
pub struct RevIdxRange(u32, u32);
impl Iterator for RevIdxRange {
type Item = RevIdx;
fn next(&mut self) -> Option<Self::Item> {
if self.0 < self.1 {
let ret = RevIdx(self.0);
self.0 += 1;
Some(ret)
} else {
None
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::str::FromStr;
#[test]
fn zero() {
assert_eq!(RevIdx::zero(), RevIdx(0))
}
#[test]
fn succ() {
assert_eq!(RevIdx::zero().succ(), RevIdx(1));
assert_eq!(RevIdx::zero().succ().succ(), RevIdx(2));
}
#[test]
fn pred() {
assert_eq!(RevIdx(10).pred(), RevIdx(9));
}
#[test]
#[should_panic]
fn bad_pred() |
#[test]
fn range_to() {
let v: Vec<_> = RevIdx::zero().range_to(RevIdx(5)).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
);
}
#[test]
fn iter() {
let v: Vec<_> = RevIdx::zero().into_iter().take(5).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
)
}
#[test]
fn fromstr() {
let idx: RevIdx = FromStr::from_str("555").expect("Valid string");
assert_eq!(idx, RevIdx(555));
}
#[test]
fn fromstr_bad1() {
match RevIdx::from_str("abc123") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
#[test]
fn fromstr_bad2() {
match RevIdx::from_str("-1") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
}
| {
println!("bad {:?}", RevIdx::zero().pred());
} | identifier_body |
revidx.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::{Add, Mul};
use std::str::FromStr;
use std::u32;
/// Index into a `RevLog`
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RevIdx(u32);
// Implement `RevIdx`s methods
impl RevIdx {
/// Return index for first entry
pub fn zero() -> Self {
RevIdx(0)
}
/// Return successor index
pub fn succ(self) -> Self {
RevIdx(self.0 + 1)
}
/// Return previous index
///
/// Panics if index is zero.
pub fn pred(self) -> Self {
assert!(self.0 > 0);
RevIdx(self.0 - 1)
}
/// Return iterator for a range from index to `lim`.
pub fn range_to(&self, lim: Self) -> RevIdxRange {
RevIdxRange(self.0, lim.0)
}
/// Return an open ended iterator from index.
pub fn range(&self) -> RevIdxRange {
RevIdxRange(self.0, u32::MAX)
}
pub fn as_u32(&self) -> u32 {
self.0
}
}
// Construct a `RevIdx` from a `u32`
impl From<u32> for RevIdx {
fn from(v: u32) -> Self {
RevIdx(v)
}
}
// Construct a `RevIdx` from a `usize`
// Panics if the usize is larger than u32::MAX
impl From<usize> for RevIdx {
fn from(v: usize) -> Self {
assert!(v <= u32::MAX as usize);
RevIdx(v as u32)
}
}
// Construct a `RevIdx` from a string (which may fail)
impl FromStr for RevIdx {
type Err = <u32 as FromStr>::Err;
fn from_str(s: &str) -> Result<Self, Self::Err> {
u32::from_str(s).map(RevIdx)
}
}
// Multiply operator for RevIdx * usize -> usize
// Used for constructing a byte offset for an index
impl Mul<usize> for RevIdx {
type Output = usize;
fn mul(self, other: usize) -> Self::Output {
self.0 as usize * other
}
}
// RevIdx + usize -> RevIdx
impl Add<usize> for RevIdx {
type Output = RevIdx;
fn add(self, other: usize) -> Self::Output {
RevIdx((self.0 as usize + other) as u32)
}
}
// Convert a `RevIdx` into an open-ended iterator of RevIdx values
// starting at RevIdx's value. ie, RevIdx(2).into_iter() => RevIdx(2), RevIdx(3),...
impl<'a> IntoIterator for &'a RevIdx {
type Item = RevIdx;
type IntoIter = RevIdxRange;
fn into_iter(self) -> Self::IntoIter {
self.range()
}
}
/// An open-ended or bounded iterator over a range of RevIdx
#[derive(Copy, Clone, Debug)]
pub struct RevIdxRange(u32, u32);
impl Iterator for RevIdxRange {
type Item = RevIdx;
fn next(&mut self) -> Option<Self::Item> {
if self.0 < self.1 {
let ret = RevIdx(self.0);
self.0 += 1;
Some(ret)
} else {
None
}
}
}
#[cfg(test)]
mod test {
use super::*;
use std::str::FromStr;
#[test]
fn zero() {
assert_eq!(RevIdx::zero(), RevIdx(0))
}
#[test]
fn succ() {
assert_eq!(RevIdx::zero().succ(), RevIdx(1));
assert_eq!(RevIdx::zero().succ().succ(), RevIdx(2));
}
#[test]
fn pred() {
assert_eq!(RevIdx(10).pred(), RevIdx(9));
}
#[test]
#[should_panic]
fn bad_pred() {
println!("bad {:?}", RevIdx::zero().pred());
}
#[test]
fn range_to() {
let v: Vec<_> = RevIdx::zero().range_to(RevIdx(5)).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
);
}
#[test]
fn | () {
let v: Vec<_> = RevIdx::zero().into_iter().take(5).collect();
assert_eq!(
v,
vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)]
)
}
#[test]
fn fromstr() {
let idx: RevIdx = FromStr::from_str("555").expect("Valid string");
assert_eq!(idx, RevIdx(555));
}
#[test]
fn fromstr_bad1() {
match RevIdx::from_str("abc123") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
#[test]
fn fromstr_bad2() {
match RevIdx::from_str("-1") {
Ok(x) => panic!("unexpected success with {:?}", x),
Err(err) => println!("ok {:?}", err),
}
}
}
| iter | identifier_name |
init.rs | use std::sync::{Arc, Mutex};
use std::io;
use std::ptr;
use std::mem;
use std::thread;
use super::callback;
use super::Window;
use super::MonitorId;
use super::WindowWrapper;
use super::Context;
use Api;
use CreationError;
use CreationError::OsError;
use CursorState;
use GlAttributes;
use GlRequest;
use PixelFormatRequirements;
use WindowAttributes;
use std::ffi::{OsStr};
use std::os::windows::ffi::OsStrExt;
use std::sync::mpsc::channel;
use winapi;
use kernel32;
use dwmapi;
use user32;
use api::wgl::Context as WglContext;
use api::egl;
use api::egl::Context as EglContext;
use api::egl::ffi::egl::Egl;
#[derive(Clone)]
pub enum RawContext {
Egl(egl::ffi::egl::types::EGLContext),
Wgl(winapi::HGLRC),
}
unsafe impl Send for RawContext {}
unsafe impl Sync for RawContext {}
pub fn new_window(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<RawContext>, egl: Option<&Egl>)
-> Result<Window, CreationError>
{
let egl = egl.map(|e| e.clone());
let window = window.clone();
let pf_reqs = pf_reqs.clone();
let opengl = opengl.clone();
// initializing variables to be sent to the task
let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>();
let (tx, rx) = channel();
// `GetMessage` must be called in the same thread as CreateWindow, so we create a new thread
// dedicated to this window.
thread::spawn(move || {
unsafe {
// creating and sending the `Window`
match init(title, &window, &pf_reqs, &opengl, egl) {
Ok(w) => tx.send(Ok(w)).ok(),
Err(e) => |
};
// now that the `Window` struct is initialized, the main `Window::new()` function will
// return and this events loop will run in parallel
loop {
let mut msg = mem::uninitialized();
if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 {
break;
}
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg); // calls `callback` (see the callback module)
}
}
});
rx.recv().unwrap()
}
unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<RawContext>, egl: Option<Egl>)
-> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|sharelists| {
match sharelists {
RawContext::Wgl(c) => c,
_ => unimplemented!()
}
});
// registering the window class
let class_name = register_window_class();
// building a RECT object with coordinates
let mut rect = winapi::RECT {
left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG,
top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG,
};
// switching to fullscreen if necessary
// this means adjusting the window's position so that it overlaps the right monitor,
// and change the monitor's resolution if necessary
if window.monitor.is_some() {
let monitor = window.monitor.as_ref().unwrap();
try!(switch_to_fullscreen(&mut rect, monitor));
}
// computing the style and extended style of the window
let (ex_style, style) = if window.monitor.is_some() || window.decorations == false {
(winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN)
} else {
(winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE,
winapi::WS_OVERLAPPEDWINDOW | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN)
};
// adjusting the window coordinates using the style
user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style);
// creating the real window this time, by using the functions in `extra_functions`
let real_window = {
let (width, height) = if window.monitor.is_some() || window.dimensions.is_some() {
(Some(rect.right - rect.left), Some(rect.bottom - rect.top))
} else {
(None, None)
};
let (x, y) = if window.monitor.is_some() {
(Some(rect.left), Some(rect.top))
} else {
(None, None)
};
let style = if!window.visible {
style
} else {
style | winapi::WS_VISIBLE
};
let handle = user32::CreateWindowExW(ex_style | winapi::WS_EX_ACCEPTFILES,
class_name.as_ptr(),
title.as_ptr() as winapi::LPCWSTR,
style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN,
x.unwrap_or(winapi::CW_USEDEFAULT), y.unwrap_or(winapi::CW_USEDEFAULT),
width.unwrap_or(winapi::CW_USEDEFAULT), height.unwrap_or(winapi::CW_USEDEFAULT),
ptr::null_mut(), ptr::null_mut(), kernel32::GetModuleHandleW(ptr::null()),
ptr::null_mut());
if handle.is_null() {
return Err(OsError(format!("CreateWindowEx function failed: {}",
format!("{}", io::Error::last_os_error()))));
}
let hdc = user32::GetDC(handle);
if hdc.is_null() {
return Err(OsError(format!("GetDC function failed: {}",
format!("{}", io::Error::last_os_error()))));
}
WindowWrapper(handle, hdc)
};
// creating the OpenGL context
let context = match opengl.version {
GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => {
if let Some(egl) = egl {
if let Ok(c) = EglContext::new(egl, &pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()),
egl::NativeDisplay::Other(Some(ptr::null())))
.and_then(|p| p.finish(real_window.0))
{
Context::Egl(c)
} else {
try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
.map(Context::Wgl))
}
} else {
// falling back to WGL, which is always available
try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
.map(Context::Wgl))
}
},
_ => {
try!(WglContext::new(&pf_reqs, &opengl, real_window.0).map(Context::Wgl))
}
};
// making the window transparent
if window.transparent {
let bb = winapi::DWM_BLURBEHIND {
dwFlags: 0x1, // FIXME: DWM_BB_ENABLE;
fEnable: 1,
hRgnBlur: ptr::null_mut(),
fTransitionOnMaximized: 0,
};
dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb);
}
// calling SetForegroundWindow if fullscreen
if window.monitor.is_some() {
user32::SetForegroundWindow(real_window.0);
}
// Creating a mutex to track the current cursor state
let cursor_state = Arc::new(Mutex::new(CursorState::Normal));
// filling the CONTEXT_STASH task-local storage so that we can start receiving events
let events_receiver = {
let (tx, rx) = channel();
let mut tx = Some(tx);
callback::CONTEXT_STASH.with(|context_stash| {
let data = callback::ThreadLocalData {
win: real_window.0,
sender: tx.take().unwrap(),
cursor_state: cursor_state.clone()
};
(*context_stash.borrow_mut()) = Some(data);
});
rx
};
// building the struct
Ok(Window {
window: real_window,
context: context,
events_receiver: events_receiver,
cursor_state: cursor_state,
})
}
unsafe fn register_window_class() -> Vec<u16> {
let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>();
let class = winapi::WNDCLASSEXW {
cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT,
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(callback::callback),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleW(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
// We ignore errors because registering the same window class twice would trigger
// an error, and because errors here are detected during CreateWindowEx anyway.
// Also since there is no weird element in the struct, there is no reason for this
// call to fail.
user32::RegisterClassExW(&class);
class_name
}
unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorId)
-> Result<(), CreationError>
{
// adjusting the rect
{
let pos = monitor.get_position();
rect.left += pos.0 as winapi::LONG;
rect.right += pos.0 as winapi::LONG;
rect.top += pos.1 as winapi::LONG;
rect.bottom += pos.1 as winapi::LONG;
}
// changing device settings
let mut screen_settings: winapi::DEVMODEW = mem::zeroed();
screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD;
screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD;
screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD;
screen_settings.dmBitsPerPel = 32; // TODO:?
screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT;
let result = user32::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(),
&mut screen_settings, ptr::null_mut(),
winapi::CDS_FULLSCREEN, ptr::null_mut());
if result!= winapi::DISP_CHANGE_SUCCESSFUL {
return Err(OsError(format!("ChangeDisplaySettings failed: {}", result)));
}
Ok(())
}
| {
tx.send(Err(e)).ok();
return;
} | conditional_block |
init.rs | use std::sync::{Arc, Mutex};
use std::io;
use std::ptr;
use std::mem;
use std::thread;
use super::callback;
use super::Window;
use super::MonitorId;
use super::WindowWrapper;
use super::Context;
use Api;
use CreationError;
use CreationError::OsError;
use CursorState;
use GlAttributes;
use GlRequest;
use PixelFormatRequirements;
use WindowAttributes;
use std::ffi::{OsStr};
use std::os::windows::ffi::OsStrExt;
use std::sync::mpsc::channel;
use winapi;
use kernel32;
use dwmapi;
use user32;
use api::wgl::Context as WglContext;
use api::egl;
use api::egl::Context as EglContext;
use api::egl::ffi::egl::Egl;
#[derive(Clone)]
pub enum RawContext {
Egl(egl::ffi::egl::types::EGLContext),
Wgl(winapi::HGLRC),
}
unsafe impl Send for RawContext {}
unsafe impl Sync for RawContext {}
pub fn new_window(window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<RawContext>, egl: Option<&Egl>)
-> Result<Window, CreationError>
{
let egl = egl.map(|e| e.clone());
let window = window.clone();
let pf_reqs = pf_reqs.clone();
let opengl = opengl.clone();
// initializing variables to be sent to the task
let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>();
let (tx, rx) = channel();
// `GetMessage` must be called in the same thread as CreateWindow, so we create a new thread
// dedicated to this window.
thread::spawn(move || {
unsafe {
// creating and sending the `Window`
match init(title, &window, &pf_reqs, &opengl, egl) {
Ok(w) => tx.send(Ok(w)).ok(),
Err(e) => {
tx.send(Err(e)).ok();
return;
}
};
// now that the `Window` struct is initialized, the main `Window::new()` function will
// return and this events loop will run in parallel
loop {
let mut msg = mem::uninitialized();
if user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) == 0 {
break;
}
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg); // calls `callback` (see the callback module)
}
}
});
rx.recv().unwrap()
}
unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements,
opengl: &GlAttributes<RawContext>, egl: Option<Egl>)
-> Result<Window, CreationError>
{
let opengl = opengl.clone().map_sharing(|sharelists| {
match sharelists {
RawContext::Wgl(c) => c,
_ => unimplemented!()
}
});
// registering the window class
let class_name = register_window_class();
// building a RECT object with coordinates
let mut rect = winapi::RECT {
left: 0, right: window.dimensions.unwrap_or((1024, 768)).0 as winapi::LONG,
top: 0, bottom: window.dimensions.unwrap_or((1024, 768)).1 as winapi::LONG,
};
// switching to fullscreen if necessary
// this means adjusting the window's position so that it overlaps the right monitor,
// and change the monitor's resolution if necessary
if window.monitor.is_some() {
let monitor = window.monitor.as_ref().unwrap();
try!(switch_to_fullscreen(&mut rect, monitor));
}
// computing the style and extended style of the window
let (ex_style, style) = if window.monitor.is_some() || window.decorations == false {
(winapi::WS_EX_APPWINDOW, winapi::WS_POPUP | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN)
} else {
(winapi::WS_EX_APPWINDOW | winapi::WS_EX_WINDOWEDGE,
winapi::WS_OVERLAPPEDWINDOW | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN)
};
// adjusting the window coordinates using the style
user32::AdjustWindowRectEx(&mut rect, style, 0, ex_style);
// creating the real window this time, by using the functions in `extra_functions`
let real_window = {
let (width, height) = if window.monitor.is_some() || window.dimensions.is_some() {
(Some(rect.right - rect.left), Some(rect.bottom - rect.top))
} else {
(None, None)
};
let (x, y) = if window.monitor.is_some() {
(Some(rect.left), Some(rect.top))
} else {
(None, None)
};
let style = if!window.visible {
style
} else {
style | winapi::WS_VISIBLE
};
let handle = user32::CreateWindowExW(ex_style | winapi::WS_EX_ACCEPTFILES,
class_name.as_ptr(),
title.as_ptr() as winapi::LPCWSTR,
style | winapi::WS_CLIPSIBLINGS | winapi::WS_CLIPCHILDREN,
x.unwrap_or(winapi::CW_USEDEFAULT), y.unwrap_or(winapi::CW_USEDEFAULT),
width.unwrap_or(winapi::CW_USEDEFAULT), height.unwrap_or(winapi::CW_USEDEFAULT),
ptr::null_mut(), ptr::null_mut(), kernel32::GetModuleHandleW(ptr::null()),
ptr::null_mut());
if handle.is_null() {
return Err(OsError(format!("CreateWindowEx function failed: {}",
format!("{}", io::Error::last_os_error()))));
}
let hdc = user32::GetDC(handle);
if hdc.is_null() {
return Err(OsError(format!("GetDC function failed: {}",
format!("{}", io::Error::last_os_error()))));
}
WindowWrapper(handle, hdc)
};
// creating the OpenGL context
let context = match opengl.version {
GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => {
if let Some(egl) = egl {
if let Ok(c) = EglContext::new(egl, &pf_reqs, &opengl.clone().map_sharing(|_| unimplemented!()),
egl::NativeDisplay::Other(Some(ptr::null())))
.and_then(|p| p.finish(real_window.0))
{
Context::Egl(c)
} else {
try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
.map(Context::Wgl))
}
} else {
// falling back to WGL, which is always available
try!(WglContext::new(&pf_reqs, &opengl, real_window.0)
.map(Context::Wgl))
}
},
_ => {
try!(WglContext::new(&pf_reqs, &opengl, real_window.0).map(Context::Wgl))
}
};
// making the window transparent
if window.transparent {
let bb = winapi::DWM_BLURBEHIND {
dwFlags: 0x1, // FIXME: DWM_BB_ENABLE;
fEnable: 1,
hRgnBlur: ptr::null_mut(),
fTransitionOnMaximized: 0,
};
dwmapi::DwmEnableBlurBehindWindow(real_window.0, &bb);
}
// calling SetForegroundWindow if fullscreen
if window.monitor.is_some() {
user32::SetForegroundWindow(real_window.0);
}
// Creating a mutex to track the current cursor state
let cursor_state = Arc::new(Mutex::new(CursorState::Normal));
// filling the CONTEXT_STASH task-local storage so that we can start receiving events
let events_receiver = {
let (tx, rx) = channel();
let mut tx = Some(tx);
callback::CONTEXT_STASH.with(|context_stash| {
let data = callback::ThreadLocalData {
win: real_window.0,
sender: tx.take().unwrap(),
cursor_state: cursor_state.clone()
};
(*context_stash.borrow_mut()) = Some(data);
});
rx
};
// building the struct
Ok(Window {
window: real_window,
context: context,
events_receiver: events_receiver,
cursor_state: cursor_state,
})
}
unsafe fn | () -> Vec<u16> {
let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter())
.collect::<Vec<_>>();
let class = winapi::WNDCLASSEXW {
cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT,
style: winapi::CS_HREDRAW | winapi::CS_VREDRAW | winapi::CS_OWNDC,
lpfnWndProc: Some(callback::callback),
cbClsExtra: 0,
cbWndExtra: 0,
hInstance: kernel32::GetModuleHandleW(ptr::null()),
hIcon: ptr::null_mut(),
hCursor: ptr::null_mut(), // must be null in order for cursor state to work properly
hbrBackground: ptr::null_mut(),
lpszMenuName: ptr::null(),
lpszClassName: class_name.as_ptr(),
hIconSm: ptr::null_mut(),
};
// We ignore errors because registering the same window class twice would trigger
// an error, and because errors here are detected during CreateWindowEx anyway.
// Also since there is no weird element in the struct, there is no reason for this
// call to fail.
user32::RegisterClassExW(&class);
class_name
}
unsafe fn switch_to_fullscreen(rect: &mut winapi::RECT, monitor: &MonitorId)
-> Result<(), CreationError>
{
// adjusting the rect
{
let pos = monitor.get_position();
rect.left += pos.0 as winapi::LONG;
rect.right += pos.0 as winapi::LONG;
rect.top += pos.1 as winapi::LONG;
rect.bottom += pos.1 as winapi::LONG;
}
// changing device settings
let mut screen_settings: winapi::DEVMODEW = mem::zeroed();
screen_settings.dmSize = mem::size_of::<winapi::DEVMODEW>() as winapi::WORD;
screen_settings.dmPelsWidth = (rect.right - rect.left) as winapi::DWORD;
screen_settings.dmPelsHeight = (rect.bottom - rect.top) as winapi::DWORD;
screen_settings.dmBitsPerPel = 32; // TODO:?
screen_settings.dmFields = winapi::DM_BITSPERPEL | winapi::DM_PELSWIDTH | winapi::DM_PELSHEIGHT;
let result = user32::ChangeDisplaySettingsExW(monitor.get_adapter_name().as_ptr(),
&mut screen_settings, ptr::null_mut(),
winapi::CDS_FULLSCREEN, ptr::null_mut());
if result!= winapi::DISP_CHANGE_SUCCESSFUL {
return Err(OsError(format!("ChangeDisplaySettings failed: {}", result)));
}
Ok(())
}
| register_window_class | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.