code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
import { WindGusts24 } from "../../";
export = WindGusts24;
| markogresak/DefinitelyTyped | types/carbon__icons-react/lib/wind-gusts/24.d.ts | TypeScript | mit | 61 |
/**
* Copyright (c) 2010-2016, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.homematic.internal.model.adapter;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.commons.lang.StringUtils;
/**
* JAXB Adapter to trim a string value to null.
*
* @author Gerhard Riegler
* @since 1.5.0
*/
public class TrimToNullStringAdapter extends XmlAdapter<String, Object> {
/**
* {@inheritDoc}
*/
@Override
public Object unmarshal(String value) throws Exception {
return StringUtils.trimToNull(value);
}
/**
* {@inheritDoc}
*/
@Override
public String marshal(Object value) throws Exception {
if (value == null) {
return null;
}
return value.toString();
}
}
| evansj/openhab | bundles/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/model/adapter/TrimToNullStringAdapter.java | Java | epl-1.0 | 1,031 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
namespace ComponentBuilderHelpers
{
static String getStateId (const ValueTree& state)
{
return state [ComponentBuilder::idProperty].toString();
}
static Component* removeComponentWithID (OwnedArray<Component>& components, const String& compId)
{
jassert (compId.isNotEmpty());
for (int i = components.size(); --i >= 0;)
{
Component* const c = components.getUnchecked (i);
if (c->getComponentID() == compId)
return components.removeAndReturn (i);
}
return nullptr;
}
static Component* findComponentWithID (Component& c, const String& compId)
{
jassert (compId.isNotEmpty());
if (c.getComponentID() == compId)
return &c;
for (int i = c.getNumChildComponents(); --i >= 0;)
if (Component* const child = findComponentWithID (*c.getChildComponent (i), compId))
return child;
return nullptr;
}
static Component* createNewComponent (ComponentBuilder::TypeHandler& type,
const ValueTree& state, Component* parent)
{
Component* const c = type.addNewComponentFromState (state, parent);
jassert (c != nullptr && c->getParentComponent() == parent);
c->setComponentID (getStateId (state));
return c;
}
static void updateComponent (ComponentBuilder& builder, const ValueTree& state)
{
if (Component* topLevelComp = builder.getManagedComponent())
{
ComponentBuilder::TypeHandler* const type = builder.getHandlerForState (state);
const String uid (getStateId (state));
if (type == nullptr || uid.isEmpty())
{
// ..handle the case where a child of the actual state node has changed.
if (state.getParent().isValid())
updateComponent (builder, state.getParent());
}
else
{
if (Component* const changedComp = findComponentWithID (*topLevelComp, uid))
type->updateComponentFromState (changedComp, state);
}
}
}
}
//==============================================================================
const Identifier ComponentBuilder::idProperty ("id");
ComponentBuilder::ComponentBuilder()
: imageProvider (nullptr)
{
}
ComponentBuilder::ComponentBuilder (const ValueTree& state_)
: state (state_), imageProvider (nullptr)
{
state.addListener (this);
}
ComponentBuilder::~ComponentBuilder()
{
state.removeListener (this);
#if JUCE_DEBUG
// Don't delete the managed component!! The builder owns that component, and will delete
// it automatically when it gets deleted.
jassert (componentRef.get() == static_cast<Component*> (component));
#endif
}
Component* ComponentBuilder::getManagedComponent()
{
if (component == nullptr)
{
component = createComponent();
#if JUCE_DEBUG
componentRef = component;
#endif
}
return component;
}
Component* ComponentBuilder::createComponent()
{
jassert (types.size() > 0); // You need to register all the necessary types before you can load a component!
if (TypeHandler* const type = getHandlerForState (state))
return ComponentBuilderHelpers::createNewComponent (*type, state, nullptr);
jassertfalse; // trying to create a component from an unknown type of ValueTree
return nullptr;
}
void ComponentBuilder::registerTypeHandler (ComponentBuilder::TypeHandler* const type)
{
jassert (type != nullptr);
// Don't try to move your types around! Once a type has been added to a builder, the
// builder owns it, and you should leave it alone!
jassert (type->builder == nullptr);
types.add (type);
type->builder = this;
}
ComponentBuilder::TypeHandler* ComponentBuilder::getHandlerForState (const ValueTree& s) const
{
const Identifier targetType (s.getType());
for (int i = 0; i < types.size(); ++i)
{
TypeHandler* const t = types.getUnchecked(i);
if (t->type == targetType)
return t;
}
return nullptr;
}
int ComponentBuilder::getNumHandlers() const noexcept
{
return types.size();
}
ComponentBuilder::TypeHandler* ComponentBuilder::getHandler (const int index) const noexcept
{
return types [index];
}
void ComponentBuilder::registerStandardComponentTypes()
{
Drawable::registerDrawableTypeHandlers (*this);
}
void ComponentBuilder::setImageProvider (ImageProvider* newImageProvider) noexcept
{
imageProvider = newImageProvider;
}
ComponentBuilder::ImageProvider* ComponentBuilder::getImageProvider() const noexcept
{
return imageProvider;
}
void ComponentBuilder::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
{
ComponentBuilderHelpers::updateComponent (*this, tree);
}
void ComponentBuilder::valueTreeChildAdded (ValueTree& tree, ValueTree&)
{
ComponentBuilderHelpers::updateComponent (*this, tree);
}
void ComponentBuilder::valueTreeChildRemoved (ValueTree& tree, ValueTree&, int)
{
ComponentBuilderHelpers::updateComponent (*this, tree);
}
void ComponentBuilder::valueTreeChildOrderChanged (ValueTree& tree, int, int)
{
ComponentBuilderHelpers::updateComponent (*this, tree);
}
void ComponentBuilder::valueTreeParentChanged (ValueTree& tree)
{
ComponentBuilderHelpers::updateComponent (*this, tree);
}
//==============================================================================
ComponentBuilder::TypeHandler::TypeHandler (const Identifier& valueTreeType)
: type (valueTreeType), builder (nullptr)
{
}
ComponentBuilder::TypeHandler::~TypeHandler()
{
}
ComponentBuilder* ComponentBuilder::TypeHandler::getBuilder() const noexcept
{
// A type handler needs to be registered with a ComponentBuilder before using it!
jassert (builder != nullptr);
return builder;
}
void ComponentBuilder::updateChildComponents (Component& parent, const ValueTree& children)
{
using namespace ComponentBuilderHelpers;
const int numExistingChildComps = parent.getNumChildComponents();
Array<Component*> componentsInOrder;
componentsInOrder.ensureStorageAllocated (numExistingChildComps);
{
OwnedArray<Component> existingComponents;
existingComponents.ensureStorageAllocated (numExistingChildComps);
for (int i = 0; i < numExistingChildComps; ++i)
existingComponents.add (parent.getChildComponent (i));
const int newNumChildren = children.getNumChildren();
for (int i = 0; i < newNumChildren; ++i)
{
const ValueTree childState (children.getChild (i));
Component* c = removeComponentWithID (existingComponents, getStateId (childState));
if (c == nullptr)
{
if (TypeHandler* const type = getHandlerForState (childState))
c = ComponentBuilderHelpers::createNewComponent (*type, childState, &parent);
else
jassertfalse;
}
if (c != nullptr)
componentsInOrder.add (c);
}
// (remaining unused items in existingComponents get deleted here as it goes out of scope)
}
// Make sure the z-order is correct..
if (componentsInOrder.size() > 0)
{
componentsInOrder.getLast()->toFront (false);
for (int i = componentsInOrder.size() - 1; --i >= 0;)
componentsInOrder.getUnchecked(i)->toBehind (componentsInOrder.getUnchecked (i + 1));
}
}
| reuk/waveguide | wayverb/JuceLibraryCode/modules/juce_gui_basics/layout/juce_ComponentBuilder.cpp | C++ | gpl-2.0 | 8,800 |
var URL = require("../url2");
var tests = [
{
source: "",
target: "",
relative: ""
},
{
source: "foo/bar/",
target: "foo/bar/",
relative: ""
},
{
source: "foo/bar/baz",
target: "foo/bar/",
relative: "./"
},
{
source: "foo/bar/",
target: "/foo/bar/",
relative: "/foo/bar/"
},
{
source: "/foo/bar/baz",
target: "/foo/bar/quux",
relative: "quux"
},
{
source: "/foo/bar/baz",
target: "/foo/bar/quux/asdf",
relative: "quux/asdf"
},
{
source: "/foo/bar/baz",
target: "/foo/bar/quux/baz",
relative: "quux/baz"
},
{
source: "/foo/bar/baz",
target: "/foo/quux/baz",
relative: "../quux/baz"
},
{
source: "/foo/bar/baz",
target: "/foo/quux/baz?a=10",
relative: "../quux/baz?a=10"
},
{
source: "/foo/bar/baz?a=10",
target: "/foo/quux/baz?a=10",
relative: "../quux/baz?a=10"
},
{
source: "/foo/bar/baz?b=20",
target: "/foo/quux/baz?a=10",
relative: "../quux/baz?a=10"
},
{
source: "http://example.com",
target: "/foo/bar",
relative: "/foo/bar"
},
{
source: "",
target: "http://example.com/foo/bar",
relative: "http://example.com/foo/bar"
},
{
source: "",
target: "#foo",
relative: "#foo"
},
{
source: "",
target: "?a=10",
relative: "?a=10"
},
{
source: "?a=10",
target: "#foo",
relative: "?a=10#foo"
},
{
source: "file:///test.js",
target: "file:///test.js",
relative: "test.js"
},
{
source: "file:///test.js",
target: "file:///test/test.js",
relative: "test/test.js"
}
];
describe("relative", function () {
tests.forEach(function (test) {
(test.focus ? iit : it)(
test.label || (
"from " + JSON.stringify(test.source) + " " +
"to " + JSON.stringify(test.target)
),
function () {
expect(URL.relative(test.source, test.target))
.toBe(test.relative)
}
)
});
it("should format a url with a path property", function () {
expect(URL.format({path: "a/b"})).toEqual("a/b");
expect(URL.format({path: "a/b?c=d"})).toEqual("a/b?c=d");
});
});
| AlexanderDolgan/sputnik | wp-content/themes/node_modules/gulp.spritesmith/node_modules/url2/test/url2-spec.js | JavaScript | gpl-2.0 | 2,582 |
# barber patches to re-route raw compilation via ember compat handlebars
class Barber::Precompiler
def sources
[File.open("#{Rails.root}/vendor/assets/javascripts/handlebars.js"),
precompiler]
end
def precompiler
if !@precompiler
source = File.read("#{Rails.root}/app/assets/javascripts/discourse-common/lib/raw-handlebars.js.es6")
template = Tilt::ES6ModuleTranspilerTemplate.new {}
transpiled = template.babel_transpile(source)
# very hacky but lets us use ES6. I'm ashamed of this code -RW
transpiled.gsub!(/^export .*$/, '')
@precompiler = StringIO.new <<END
var __RawHandlebars;
(function() {
#{transpiled};
__RawHandlebars = RawHandlebars;
})();
Barber = {
precompile: function(string) {
return __RawHandlebars.precompile(string, false).toString();
}
};
END
end
@precompiler
end
end
module Discourse
module Ember
module Handlebars
module Helper
def precompile_handlebars(string)
"require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});"
end
def compile_handlebars(string)
"require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});"
end
end
end
end
end
class Ember::Handlebars::Template
include Discourse::Ember::Handlebars::Helper
def precompile_handlebars(string, input=nil)
"require('discourse-common/lib/raw-handlebars').template(#{Barber::Precompiler.compile(string)});"
end
def compile_handlebars(string, input=nil)
"require('discourse-common/lib/raw-handlebars').compile(#{indent(string).inspect});"
end
def global_template_target(namespace, module_name, config)
"#{namespace}[#{template_path(module_name, config).inspect}]"
end
# FIXME: Previously, ember-handlebars-templates uses the logical path which incorrectly
# returned paths with the `.raw` extension and our code is depending on the `.raw`
# to find the right template to use.
def actual_name(input)
actual_name = input[:name]
input[:filename].include?('.raw') ? "#{actual_name}.raw" : actual_name
end
end
| gsambrotta/discourse | lib/freedom_patches/raw_handlebars.rb | Ruby | gpl-2.0 | 2,215 |
<?php
/**
* @package Joomla.UnitTest
* @subpackage Linkedin
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Test class for JLinkedinCommunications.
*
* @package Joomla.UnitTest
* @subpackage Linkedin
*
* @since 13.1
*/
class JLinkedinCommunicationsTest extends TestCase
{
/**
* @var JRegistry Options for the Linkedin object.
* @since 13.1
*/
protected $options;
/**
* @var JHttp Mock http object.
* @since 13.1
*/
protected $client;
/**
* @var JInput The input object to use in retrieving GET/POST data.
* @since 13.1
*/
protected $input;
/**
* @var JLinkedinCommunications Object under test.
* @since 13.1
*/
protected $object;
/**
* @var JLinkedinOAuth Authentication object for the Twitter object.
* @since 13.1
*/
protected $oauth;
/**
* @var string Sample JSON string.
* @since 13.1
*/
protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
/**
* @var string Sample JSON error message.
* @since 13.1
*/
protected $errorString = '{"errorCode":401, "message": "Generic error"}';
/**
* Backup of the SERVER superglobal
*
* @var array
* @since 3.6
*/
protected $backupServer;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @return void
*/
protected function setUp()
{
parent::setUp();
$this->backupServer = $_SERVER;
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$key = "app_key";
$secret = "app_secret";
$my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php";
$this->options = new JRegistry;
$this->input = new JInput;
$this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock();
$this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input);
$this->oauth->setToken(array('key' => $key, 'secret' => $secret));
$this->object = new JLinkedinCommunications($this->options, $this->client, $this->oauth);
$this->options->set('consumer_key', $key);
$this->options->set('consumer_secret', $secret);
$this->options->set('callback', $my_url);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @return void
*
* @see \PHPUnit\Framework\TestCase::tearDown()
* @since 3.6
*/
protected function tearDown()
{
$_SERVER = $this->backupServer;
unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object);
parent::tearDown();
}
/**
* Tests the inviteByEmail method
*
* @return void
*
* @since 13.1
*/
public function testInviteByEmail()
{
$email = 'example@domain.com';
$first_name = 'Frist';
$last_name = 'Last';
$subject = 'Subject';
$body = 'body';
$connection = 'friend';
$path = '/v1/people/~/mailbox';
// Build the xml.
$xml = '<mailbox-item>
<recipients>
<recipient>
<person path="/people/email=' . $email . '">
<first-name>' . $first_name . '</first-name>
<last-name>' . $last_name . '</last-name>
</person>
</recipient>
</recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
<item-content>
<invitation-request>
<connect-type>' . $connection . '</connect-type>
</invitation-request>
</item-content>
</mailbox-item>';
$header['Content-Type'] = 'text/xml';
$returnData = new stdClass;
$returnData->code = 201;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('post', $xml, $header)
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection),
$this->equalTo($returnData)
);
}
/**
* Tests the inviteByEmail method - failure
*
* @return void
*
* @expectedException DomainException
* @since 13.1
*/
public function testInviteByEmailFailure()
{
$email = 'example@domain.com';
$first_name = 'Frist';
$last_name = 'Last';
$subject = 'Subject';
$body = 'body';
$connection = 'friend';
$path = '/v1/people/~/mailbox';
// Build the xml.
$xml = '<mailbox-item>
<recipients>
<recipient>
<person path="/people/email=' . $email . '">
<first-name>' . $first_name . '</first-name>
<last-name>' . $last_name . '</last-name>
</person>
</recipient>
</recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
<item-content>
<invitation-request>
<connect-type>' . $connection . '</connect-type>
</invitation-request>
</item-content>
</mailbox-item>';
$header['Content-Type'] = 'text/xml';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('post', $xml, $header)
->with($path)
->will($this->returnValue($returnData));
$this->object->inviteByEmail($email, $first_name, $last_name, $subject, $body, $connection);
}
/**
* Tests the inviteById method
*
* @return void
*
* @since 13.1
*/
public function testInviteById()
{
$id = 'lcnIwDU0S6';
$first_name = 'Frist';
$last_name = 'Last';
$subject = 'Subject';
$body = 'body';
$connection = 'friend';
$name = 'NAME_SEARCH';
$value = 'mwjY';
$path = '/v1/people-search:(people:(api-standard-profile-request))';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = '{"apiStandardProfileRequest": {"headers": {"_total": 1,"values": [{"name": "x-li-auth-token","value": "' .
$name . ':' . $value . '"}]}}}';
$data['format'] = 'json';
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->at(0))
->method('get')
->with($path)
->will($this->returnValue($returnData));
$path = '/v1/people/~/mailbox';
// Build the xml.
$xml = '<mailbox-item>
<recipients>
<recipient>
<person path="/people/id=' . $id . '">
</person>
</recipient>
</recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
<item-content>
<invitation-request>
<connect-type>' . $connection . '</connect-type>
<authorization>
<name>' . $name . '</name>
<value>' . $value . '</value>
</authorization>
</invitation-request>
</item-content>
</mailbox-item>';
$header['Content-Type'] = 'text/xml';
$returnData = new stdClass;
$returnData->code = 201;
$returnData->body = $this->sampleString;
$this->client->expects($this->at(1))
->method('post', $xml, $header)
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection),
$this->equalTo($returnData)
);
}
/**
* Tests the inviteById method - failure
*
* @return void
*
* @expectedException RuntimeException
* @since 13.1
*/
public function testInviteByIdFailure()
{
$id = 'lcnIwDU0S6';
$first_name = 'Frist';
$last_name = 'Last';
$subject = 'Subject';
$body = 'body';
$connection = 'friend';
$path = '/v1/people-search:(people:(api-standard-profile-request))';
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$data['format'] = 'json';
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->at(0))
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->object->inviteById($id, $first_name, $last_name, $subject, $body, $connection);
}
/**
* Tests the sendMessage method
*
* @return void
*
* @since 13.1
*/
public function testSendMessage()
{
$recipient = array('~', 'lcnIwDU0S6');
$subject = 'Subject';
$body = 'body';
$path = '/v1/people/~/mailbox';
// Build the xml.
$xml = '<mailbox-item>
<recipients>
<recipient>
<person path="/people/~"/>
</recipient>
<recipient>
<person path="/people/lcnIwDU0S6"/>
</recipient>
</recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
</mailbox-item>';
$header['Content-Type'] = 'text/xml';
$returnData = new stdClass;
$returnData->code = 201;
$returnData->body = $this->sampleString;
$this->client->expects($this->once())
->method('post', $xml, $header)
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->sendMessage($recipient, $subject, $body),
$this->equalTo($returnData)
);
}
/**
* Tests the sendMessage method - failure
*
* @return void
*
* @expectedException DomainException
* @since 13.1
*/
public function testSendMessageFailure()
{
$recipient = array('~', 'lcnIwDU0S6');
$subject = 'Subject';
$body = 'body';
$path = '/v1/people/~/mailbox';
// Build the xml.
$xml = '<mailbox-item>
<recipients>
<recipient>
<person path="/people/~"/>
</recipient>
<recipient>
<person path="/people/lcnIwDU0S6"/>
</recipient>
</recipients>
<subject>' . $subject . '</subject>
<body>' . $body . '</body>
</mailbox-item>';
$header['Content-Type'] = 'text/xml';
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$this->client->expects($this->once())
->method('post', $xml, $header)
->with($path)
->will($this->returnValue($returnData));
$this->object->sendMessage($recipient, $subject, $body);
}
}
| philip-sorokin/joomla-cms | tests/unit/suites/libraries/joomla/linkedin/JLinkedinCommunicationsTest.php | PHP | gpl-2.0 | 10,137 |
<?php
function _wpsc_get_exchange_rate( $from, $to ) {
if ( $from == $to ) {
return 1;
}
$key = "wpsc_exchange_{$from}_{$to}";
if ( $rate = get_transient( $key ) ) {
return (float) $rate;
}
$url = add_query_arg(
array(
'a' => '1',
'from' => $from,
'to' => $to
),
'http://www.google.com/finance/converter'
);
$url = apply_filters( '_wpsc_get_exchange_rate_service_endpoint', $url, $from, $to );
$response = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 10 ) ) );
if ( has_filter( '_wpsc_get_exchange_rate' ) ) {
return (float) apply_filters( '_wpsc_get_exchange_rate', $response, $from, $to );
}
if ( empty( $response ) ) {
return $response;
} else {
$rate = explode( 'bld>', $response );
$rate = explode( $to, $rate[1] );
$rate = trim( $rate[0] );
set_transient( $key, $rate, DAY_IN_SECONDS );
return (float) $rate;
}
}
function wpsc_convert_currency( $amt, $from, $to ) {
if ( empty( $from ) || empty( $to ) ) {
return $amt;
}
$rate = _wpsc_get_exchange_rate( $from, $to );
if ( is_wp_error( $rate ) ) {
return $rate;
}
return $rate * $amt;
}
function wpsc_string_to_float( $string ) {
global $wp_locale;
$decimal_separator = get_option(
'wpsc_decimal_separator',
$wp_locale->number_format['decimal_point']
);
$string = preg_replace( '/[^0-9\\' . $decimal_separator . ']/', '', $string );
$string = str_replace( $decimal_separator, '.', $string );
return (float) $string;
}
function wpsc_format_number( $number, $decimals = 2 ) {
global $wp_locale;
$decimal_separator = get_option(
'wpsc_decimal_separator',
$wp_locale->number_format['decimal_point']
);
$thousands_separator = get_option(
'wpsc_thousands_separator',
$wp_locale->number_format['thousands_sep']
);
$formatted = number_format(
(float) $number,
$decimals,
$decimal_separator,
$thousands_separator
);
return $formatted;
} | ericbarns/WP-e-Commerce | wpsc-includes/currency.helpers.php | PHP | gpl-2.0 | 1,953 |
import { Mongo } from "meteor/mongo";
/**
* Client side collections
*/
export const Countries = new Mongo.Collection(null);
| deetail/kimchi4u | client/collections/countries.js | JavaScript | gpl-3.0 | 128 |
from inspect import ismethod, isfunction
import os
import time
import traceback
from CodernityDB.database import RecordDeleted, RecordNotFound
from couchpotato import md5, get_db
from couchpotato.api import addApiView
from couchpotato.core.event import fireEvent, addEvent
from couchpotato.core.helpers.encoding import toUnicode, sp
from couchpotato.core.helpers.variable import getTitle, tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from .index import ReleaseIndex, ReleaseStatusIndex, ReleaseIDIndex, ReleaseDownloadIndex
from couchpotato.environment import Env
log = CPLog(__name__)
class Release(Plugin):
_database = {
'release': ReleaseIndex,
'release_status': ReleaseStatusIndex,
'release_identifier': ReleaseIDIndex,
'release_download': ReleaseDownloadIndex
}
def __init__(self):
addApiView('release.manual_download', self.manualDownload, docs = {
'desc': 'Send a release manually to the downloaders',
'params': {
'id': {'type': 'id', 'desc': 'ID of the release object in release-table'}
}
})
addApiView('release.delete', self.deleteView, docs = {
'desc': 'Delete releases',
'params': {
'id': {'type': 'id', 'desc': 'ID of the release object in release-table'}
}
})
addApiView('release.ignore', self.ignore, docs = {
'desc': 'Toggle ignore, for bad or wrong releases',
'params': {
'id': {'type': 'id', 'desc': 'ID of the release object in release-table'}
}
})
addEvent('release.add', self.add)
addEvent('release.download', self.download)
addEvent('release.try_download_result', self.tryDownloadResult)
addEvent('release.create_from_search', self.createFromSearch)
addEvent('release.delete', self.delete)
addEvent('release.clean', self.clean)
addEvent('release.update_status', self.updateStatus)
addEvent('release.with_status', self.withStatus)
addEvent('release.for_media', self.forMedia)
# Clean releases that didn't have activity in the last week
addEvent('app.load', self.cleanDone, priority = 1000)
fireEvent('schedule.interval', 'movie.clean_releases', self.cleanDone, hours = 12)
def cleanDone(self):
log.debug('Removing releases from dashboard')
now = time.time()
week = 604800
db = get_db()
# Get (and remove) parentless releases
releases = db.all('release', with_doc = False)
media_exist = []
reindex = 0
for release in releases:
if release.get('key') in media_exist:
continue
try:
try:
doc = db.get('id', release.get('_id'))
except RecordDeleted:
reindex += 1
continue
db.get('id', release.get('key'))
media_exist.append(release.get('key'))
try:
if doc.get('status') == 'ignore':
doc['status'] = 'ignored'
db.update(doc)
except:
log.error('Failed fixing mis-status tag: %s', traceback.format_exc())
except ValueError:
fireEvent('database.delete_corrupted', release.get('key'), traceback_error = traceback.format_exc(0))
reindex += 1
except RecordDeleted:
db.delete(doc)
log.debug('Deleted orphaned release: %s', doc)
reindex += 1
except:
log.debug('Failed cleaning up orphaned releases: %s', traceback.format_exc())
if reindex > 0:
db.reindex()
del media_exist
# get movies last_edit more than a week ago
medias = fireEvent('media.with_status', ['done', 'active'], single = True)
for media in medias:
if media.get('last_edit', 0) > (now - week):
continue
for rel in self.forMedia(media['_id']):
# Remove all available releases
if rel['status'] in ['available']:
self.delete(rel['_id'])
# Set all snatched and downloaded releases to ignored to make sure they are ignored when re-adding the media
elif rel['status'] in ['snatched', 'downloaded']:
self.updateStatus(rel['_id'], status = 'ignored')
if 'recent' in media.get('tags', []):
fireEvent('media.untag', media.get('_id'), 'recent', single = True)
def add(self, group, update_info = True, update_id = None):
try:
db = get_db()
release_identifier = '%s.%s.%s' % (group['identifier'], group['meta_data'].get('audio', 'unknown'), group['meta_data']['quality']['identifier'])
# Add movie if it doesn't exist
try:
media = db.get('media', 'imdb-%s' % group['identifier'], with_doc = True)['doc']
except:
media = fireEvent('movie.add', params = {
'identifier': group['identifier'],
'profile_id': None,
}, search_after = False, update_after = update_info, notify_after = False, status = 'done', single = True)
release = None
if update_id:
try:
release = db.get('id', update_id)
release.update({
'identifier': release_identifier,
'last_edit': int(time.time()),
'status': 'done',
})
except:
log.error('Failed updating existing release: %s', traceback.format_exc())
else:
# Add Release
if not release:
release = {
'_t': 'release',
'media_id': media['_id'],
'identifier': release_identifier,
'quality': group['meta_data']['quality'].get('identifier'),
'is_3d': group['meta_data']['quality'].get('is_3d', 0),
'last_edit': int(time.time()),
'status': 'done'
}
try:
r = db.get('release_identifier', release_identifier, with_doc = True)['doc']
r['media_id'] = media['_id']
except:
log.debug('Failed updating release by identifier "%s". Inserting new.', release_identifier)
r = db.insert(release)
# Update with ref and _id
release.update({
'_id': r['_id'],
'_rev': r['_rev'],
})
# Empty out empty file groups
release['files'] = dict((k, [toUnicode(x) for x in v]) for k, v in group['files'].items() if v)
db.update(release)
fireEvent('media.restatus', media['_id'], allowed_restatus = ['done'], single = True)
return True
except:
log.error('Failed: %s', traceback.format_exc())
return False
def deleteView(self, id = None, **kwargs):
return {
'success': self.delete(id)
}
def delete(self, release_id):
try:
db = get_db()
rel = db.get('id', release_id)
db.delete(rel)
return True
except RecordDeleted:
log.debug('Already deleted: %s', release_id)
return True
except:
log.error('Failed: %s', traceback.format_exc())
return False
def clean(self, release_id):
try:
db = get_db()
rel = db.get('id', release_id)
raw_files = rel.get('files')
if len(raw_files) == 0:
self.delete(rel['_id'])
else:
files = {}
for file_type in raw_files:
for release_file in raw_files.get(file_type, []):
if os.path.isfile(sp(release_file)):
if file_type not in files:
files[file_type] = []
files[file_type].append(release_file)
rel['files'] = files
db.update(rel)
return True
except:
log.error('Failed: %s', traceback.format_exc())
return False
def ignore(self, id = None, **kwargs):
db = get_db()
try:
if id:
rel = db.get('id', id, with_doc = True)
self.updateStatus(id, 'available' if rel['status'] in ['ignored', 'failed'] else 'ignored')
return {
'success': True
}
except:
log.error('Failed: %s', traceback.format_exc())
return {
'success': False
}
def manualDownload(self, id = None, **kwargs):
db = get_db()
try:
release = db.get('id', id)
item = release['info']
movie = db.get('id', release['media_id'])
fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Snatching "%s"' % item['name'])
# Get matching provider
provider = fireEvent('provider.belongs_to', item['url'], provider = item.get('provider'), single = True)
if item.get('protocol') != 'torrent_magnet':
item['download'] = provider.loginDownload if provider.urls.get('login') else provider.download
success = self.download(data = item, media = movie, manual = True)
if success:
fireEvent('notify.frontend', type = 'release.manual_download', data = True, message = 'Successfully snatched "%s"' % item['name'])
return {
'success': success == True
}
except:
log.error('Couldn\'t find release with id: %s: %s', (id, traceback.format_exc()))
return {
'success': False
}
def download(self, data, media, manual = False):
# Test to see if any downloaders are enabled for this type
downloader_enabled = fireEvent('download.enabled', manual, data, single = True)
if not downloader_enabled:
log.info('Tried to download, but none of the "%s" downloaders are enabled or gave an error', data.get('protocol'))
return False
# Download NZB or torrent file
filedata = None
if data.get('download') and (ismethod(data.get('download')) or isfunction(data.get('download'))):
try:
filedata = data.get('download')(url = data.get('url'), nzb_id = data.get('id'))
except:
log.error('Tried to download, but the "%s" provider gave an error: %s', (data.get('protocol'), traceback.format_exc()))
return False
if filedata == 'try_next':
return filedata
elif not filedata:
return False
# Send NZB or torrent file to downloader
download_result = fireEvent('download', data = data, media = media, manual = manual, filedata = filedata, single = True)
if not download_result:
log.info('Tried to download, but the "%s" downloader gave an error', data.get('protocol'))
return False
log.debug('Downloader result: %s', download_result)
try:
db = get_db()
try:
rls = db.get('release_identifier', md5(data['url']), with_doc = True)['doc']
except:
log.error('No release found to store download information in')
return False
renamer_enabled = Env.setting('enabled', 'renamer')
# Save download-id info if returned
if isinstance(download_result, dict):
rls['download_info'] = download_result
db.update(rls)
log_movie = '%s (%s) in %s' % (getTitle(media), media['info'].get('year'), rls['quality'])
snatch_message = 'Snatched "%s": %s from %s' % (data.get('name'), log_movie, (data.get('provider', '') + data.get('provider_extra', '')))
log.info(snatch_message)
fireEvent('%s.snatched' % data['type'], message = snatch_message, data = media)
# Mark release as snatched
if renamer_enabled:
self.updateStatus(rls['_id'], status = 'snatched')
# If renamer isn't used, mark media done if finished or release downloaded
else:
if media['status'] == 'active':
profile = db.get('id', media['profile_id'])
if fireEvent('quality.isfinish', {'identifier': rls['quality'], 'is_3d': rls.get('is_3d', False)}, profile, single = True):
log.info('Renamer disabled, marking media as finished: %s', log_movie)
# Mark release done
self.updateStatus(rls['_id'], status = 'done')
# Mark media done
fireEvent('media.restatus', media['_id'], single = True)
return True
# Assume release downloaded
self.updateStatus(rls['_id'], status = 'downloaded')
except:
log.error('Failed storing download status: %s', traceback.format_exc())
return False
return True
def tryDownloadResult(self, results, media, quality_custom):
wait_for = False
let_through = False
filtered_results = []
minimum_seeders = tryInt(Env.setting('minimum_seeders', section = 'torrent', default = 1))
# Filter out ignored and other releases we don't want
for rel in results:
if rel['status'] in ['ignored', 'failed']:
log.info('Ignored: %s', rel['name'])
continue
if rel['score'] < quality_custom.get('minimum_score'):
log.info('Ignored, score "%s" to low, need at least "%s": %s', (rel['score'], quality_custom.get('minimum_score'), rel['name']))
continue
if rel['size'] <= 50:
log.info('Ignored, size "%sMB" to low: %s', (rel['size'], rel['name']))
continue
if 'seeders' in rel and rel.get('seeders') < minimum_seeders:
log.info('Ignored, not enough seeders, has %s needs %s: %s', (rel.get('seeders'), minimum_seeders, rel['name']))
continue
# If a single release comes through the "wait for", let through all
rel['wait_for'] = False
if quality_custom.get('index') != 0 and quality_custom.get('wait_for', 0) > 0 and rel.get('age') <= quality_custom.get('wait_for', 0):
rel['wait_for'] = True
else:
let_through = True
filtered_results.append(rel)
# Loop through filtered results
for rel in filtered_results:
# Only wait if not a single release is old enough
if rel.get('wait_for') and not let_through:
log.info('Ignored, waiting %s days: %s', (quality_custom.get('wait_for') - rel.get('age'), rel['name']))
wait_for = True
continue
downloaded = fireEvent('release.download', data = rel, media = media, single = True)
if downloaded is True:
return True
elif downloaded != 'try_next':
break
return wait_for
def createFromSearch(self, search_results, media, quality):
try:
db = get_db()
found_releases = []
is_3d = False
try: is_3d = quality['custom']['3d']
except: pass
for rel in search_results:
rel_identifier = md5(rel['url'])
release = {
'_t': 'release',
'identifier': rel_identifier,
'media_id': media.get('_id'),
'quality': quality.get('identifier'),
'is_3d': is_3d,
'status': rel.get('status', 'available'),
'last_edit': int(time.time()),
'info': {}
}
# Add downloader info if provided
try:
release['download_info'] = rel['download_info']
del rel['download_info']
except:
pass
try:
rls = db.get('release_identifier', rel_identifier, with_doc = True)['doc']
except:
rls = db.insert(release)
rls.update(release)
# Update info, but filter out functions
for info in rel:
try:
if not isinstance(rel[info], (str, unicode, int, long, float)):
continue
rls['info'][info] = toUnicode(rel[info]) if isinstance(rel[info], (str, unicode)) else rel[info]
except:
log.debug('Couldn\'t add %s to ReleaseInfo: %s', (info, traceback.format_exc()))
db.update(rls)
# Update release in search_results
rel['status'] = rls.get('status')
if rel['status'] == 'available':
found_releases.append(rel_identifier)
return found_releases
except:
log.error('Failed: %s', traceback.format_exc())
return []
def updateStatus(self, release_id, status = None):
if not status: return False
try:
db = get_db()
rel = db.get('id', release_id)
if rel and rel.get('status') != status:
release_name = None
if rel.get('files'):
for file_type in rel.get('files', {}):
if file_type == 'movie':
for release_file in rel['files'][file_type]:
release_name = os.path.basename(release_file)
break
if not release_name and rel.get('info'):
release_name = rel['info'].get('name')
#update status in Db
log.debug('Marking release %s as %s', (release_name, status))
rel['status'] = status
rel['last_edit'] = int(time.time())
db.update(rel)
#Update all movie info as there is no release update function
fireEvent('notify.frontend', type = 'release.update_status', data = rel)
return True
except:
log.error('Failed: %s', traceback.format_exc())
return False
def withStatus(self, status, with_doc = True):
db = get_db()
status = list(status if isinstance(status, (list, tuple)) else [status])
for s in status:
for ms in db.get_many('release_status', s):
if with_doc:
try:
doc = db.get('id', ms['_id'])
yield doc
except RecordNotFound:
log.debug('Record not found, skipping: %s', ms['_id'])
else:
yield ms
def forMedia(self, media_id):
db = get_db()
raw_releases = db.get_many('release', media_id)
releases = []
for r in raw_releases:
try:
doc = db.get('id', r.get('_id'))
releases.append(doc)
except RecordDeleted:
pass
except (ValueError, EOFError):
fireEvent('database.delete_corrupted', r.get('_id'), traceback_error = traceback.format_exc(0))
releases = sorted(releases, key = lambda k: k.get('info', {}).get('score', 0), reverse = True)
# Sort based on preferred search method
download_preference = self.conf('preferred_method', section = 'searcher')
if download_preference != 'both':
releases = sorted(releases, key = lambda k: k.get('info', {}).get('protocol', '')[:3], reverse = (download_preference == 'torrent'))
return releases or []
| coderb0t/CouchPotatoServer | couchpotato/core/plugins/release/main.py | Python | gpl-3.0 | 20,734 |
package aws
import (
"fmt"
"log"
"math"
"regexp"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
events "github.com/aws/aws-sdk-go/service/cloudwatchevents"
"github.com/hashicorp/terraform/helper/validation"
)
func resourceAwsCloudWatchEventTarget() *schema.Resource {
return &schema.Resource{
Create: resourceAwsCloudWatchEventTargetCreate,
Read: resourceAwsCloudWatchEventTargetRead,
Update: resourceAwsCloudWatchEventTargetUpdate,
Delete: resourceAwsCloudWatchEventTargetDelete,
Schema: map[string]*schema.Schema{
"rule": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventRuleName,
},
"target_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
ValidateFunc: validateCloudWatchEventTargetId,
},
"arn": {
Type: schema.TypeString,
Required: true,
},
"input": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"input_path"},
// We could be normalizing the JSON here,
// but for built-in targets input may not be JSON
},
"input_path": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"input"},
},
"role_arn": {
Type: schema.TypeString,
Optional: true,
},
"run_command_targets": {
Type: schema.TypeList,
Optional: true,
MaxItems: 5,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"key": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 128),
},
"values": {
Type: schema.TypeList,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
"ecs_target": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"task_count": {
Type: schema.TypeInt,
Optional: true,
ValidateFunc: validation.IntBetween(1, math.MaxInt32),
},
"task_definition_arn": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 1600),
},
},
},
},
"input_transformer": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"input_paths": {
Type: schema.TypeMap,
Optional: true,
},
"input_template": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringLenBetween(1, 8192),
},
},
},
},
},
}
}
func resourceAwsCloudWatchEventTargetCreate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
rule := d.Get("rule").(string)
var targetId string
if v, ok := d.GetOk("target_id"); ok {
targetId = v.(string)
} else {
targetId = resource.UniqueId()
d.Set("target_id", targetId)
}
input := buildPutTargetInputStruct(d)
log.Printf("[DEBUG] Creating CloudWatch Event Target: %s", input)
out, err := conn.PutTargets(input)
if err != nil {
return fmt.Errorf("Creating CloudWatch Event Target failed: %s", err)
}
if len(out.FailedEntries) > 0 {
return fmt.Errorf("Creating CloudWatch Event Target failed: %s",
out.FailedEntries)
}
id := rule + "-" + targetId
d.SetId(id)
log.Printf("[INFO] CloudWatch Event Target %q created", d.Id())
return resourceAwsCloudWatchEventTargetRead(d, meta)
}
func resourceAwsCloudWatchEventTargetRead(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
t, err := findEventTargetById(
d.Get("target_id").(string),
d.Get("rule").(string),
nil, conn)
if err != nil {
if regexp.MustCompile(" not found$").MatchString(err.Error()) {
log.Printf("[WARN] Removing CloudWatch Event Target %q because it's gone.", d.Id())
d.SetId("")
return nil
}
if awsErr, ok := err.(awserr.Error); ok {
// This should never happen, but it's useful
// for recovering from https://github.com/hashicorp/terraform/issues/5389
if awsErr.Code() == "ValidationException" {
log.Printf("[WARN] Removing CloudWatch Event Target %q because it never existed.", d.Id())
d.SetId("")
return nil
}
if awsErr.Code() == "ResourceNotFoundException" {
log.Printf("[WARN] CloudWatch Event Target (%q) not found. Removing it from state.", d.Id())
d.SetId("")
return nil
}
}
return err
}
log.Printf("[DEBUG] Found Event Target: %s", t)
d.Set("arn", t.Arn)
d.Set("target_id", t.Id)
d.Set("input", t.Input)
d.Set("input_path", t.InputPath)
d.Set("role_arn", t.RoleArn)
if t.RunCommandParameters != nil {
if err := d.Set("run_command_targets", flattenAwsCloudWatchEventTargetRunParameters(t.RunCommandParameters)); err != nil {
return fmt.Errorf("[DEBUG] Error setting run_command_targets error: %#v", err)
}
}
if t.EcsParameters != nil {
if err := d.Set("ecs_target", flattenAwsCloudWatchEventTargetEcsParameters(t.EcsParameters)); err != nil {
return fmt.Errorf("[DEBUG] Error setting ecs_target error: %#v", err)
}
}
if t.InputTransformer != nil {
if err := d.Set("input_transformer", flattenAwsCloudWatchInputTransformer(t.InputTransformer)); err != nil {
return fmt.Errorf("[DEBUG] Error setting input_transformer error: %#v", err)
}
}
return nil
}
func findEventTargetById(id, rule string, nextToken *string, conn *events.CloudWatchEvents) (*events.Target, error) {
input := events.ListTargetsByRuleInput{
Rule: aws.String(rule),
NextToken: nextToken,
Limit: aws.Int64(100), // Set limit to allowed maximum to prevent API throttling
}
log.Printf("[DEBUG] Reading CloudWatch Event Target: %s", input)
out, err := conn.ListTargetsByRule(&input)
if err != nil {
return nil, err
}
for _, t := range out.Targets {
if *t.Id == id {
return t, nil
}
}
if out.NextToken != nil {
return findEventTargetById(id, rule, nextToken, conn)
}
return nil, fmt.Errorf("CloudWatch Event Target %q (%q) not found", id, rule)
}
func resourceAwsCloudWatchEventTargetUpdate(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input := buildPutTargetInputStruct(d)
log.Printf("[DEBUG] Updating CloudWatch Event Target: %s", input)
_, err := conn.PutTargets(input)
if err != nil {
return fmt.Errorf("Updating CloudWatch Event Target failed: %s", err)
}
return resourceAwsCloudWatchEventTargetRead(d, meta)
}
func resourceAwsCloudWatchEventTargetDelete(d *schema.ResourceData, meta interface{}) error {
conn := meta.(*AWSClient).cloudwatcheventsconn
input := events.RemoveTargetsInput{
Ids: []*string{aws.String(d.Get("target_id").(string))},
Rule: aws.String(d.Get("rule").(string)),
}
log.Printf("[INFO] Deleting CloudWatch Event Target: %s", input)
_, err := conn.RemoveTargets(&input)
if err != nil {
return fmt.Errorf("Error deleting CloudWatch Event Target: %s", err)
}
log.Println("[INFO] CloudWatch Event Target deleted")
d.SetId("")
return nil
}
func buildPutTargetInputStruct(d *schema.ResourceData) *events.PutTargetsInput {
e := &events.Target{
Arn: aws.String(d.Get("arn").(string)),
Id: aws.String(d.Get("target_id").(string)),
}
if v, ok := d.GetOk("input"); ok {
e.Input = aws.String(v.(string))
}
if v, ok := d.GetOk("input_path"); ok {
e.InputPath = aws.String(v.(string))
}
if v, ok := d.GetOk("role_arn"); ok {
e.RoleArn = aws.String(v.(string))
}
if v, ok := d.GetOk("run_command_targets"); ok {
e.RunCommandParameters = expandAwsCloudWatchEventTargetRunParameters(v.([]interface{}))
}
if v, ok := d.GetOk("ecs_target"); ok {
e.EcsParameters = expandAwsCloudWatchEventTargetEcsParameters(v.([]interface{}))
}
if v, ok := d.GetOk("input_transformer"); ok {
e.InputTransformer = expandAwsCloudWatchEventTransformerParameters(v.([]interface{}))
}
input := events.PutTargetsInput{
Rule: aws.String(d.Get("rule").(string)),
Targets: []*events.Target{e},
}
return &input
}
func expandAwsCloudWatchEventTargetRunParameters(config []interface{}) *events.RunCommandParameters {
commands := make([]*events.RunCommandTarget, 0)
for _, c := range config {
param := c.(map[string]interface{})
command := &events.RunCommandTarget{
Key: aws.String(param["key"].(string)),
Values: expandStringList(param["values"].([]interface{})),
}
commands = append(commands, command)
}
command := &events.RunCommandParameters{
RunCommandTargets: commands,
}
return command
}
func expandAwsCloudWatchEventTargetEcsParameters(config []interface{}) *events.EcsParameters {
ecsParameters := &events.EcsParameters{}
for _, c := range config {
param := c.(map[string]interface{})
ecsParameters.TaskCount = aws.Int64(int64(param["task_count"].(int)))
ecsParameters.TaskDefinitionArn = aws.String(param["task_definition_arn"].(string))
}
return ecsParameters
}
func expandAwsCloudWatchEventTransformerParameters(config []interface{}) *events.InputTransformer {
transformerParameters := &events.InputTransformer{}
inputPathsMaps := map[string]*string{}
for _, c := range config {
param := c.(map[string]interface{})
inputPaths := param["input_paths"].(map[string]interface{})
for k, v := range inputPaths {
inputPathsMaps[k] = aws.String(v.(string))
}
transformerParameters.InputTemplate = aws.String(param["input_template"].(string))
}
transformerParameters.InputPathsMap = inputPathsMaps
return transformerParameters
}
func flattenAwsCloudWatchEventTargetRunParameters(runCommand *events.RunCommandParameters) []map[string]interface{} {
result := make([]map[string]interface{}, 0)
for _, x := range runCommand.RunCommandTargets {
config := make(map[string]interface{})
config["key"] = *x.Key
config["values"] = flattenStringList(x.Values)
result = append(result, config)
}
return result
}
func flattenAwsCloudWatchEventTargetEcsParameters(ecsParameters *events.EcsParameters) []map[string]interface{} {
config := make(map[string]interface{})
config["task_count"] = *ecsParameters.TaskCount
config["task_definition_arn"] = *ecsParameters.TaskDefinitionArn
result := []map[string]interface{}{config}
return result
}
func flattenAwsCloudWatchInputTransformer(inputTransformer *events.InputTransformer) []map[string]interface{} {
config := make(map[string]interface{})
inputPathsMap := make(map[string]string)
for k, v := range inputTransformer.InputPathsMap {
inputPathsMap[k] = *v
}
config["input_template"] = *inputTransformer.InputTemplate
config["input_paths"] = inputPathsMap
result := []map[string]interface{}{config}
return result
}
| hartzell/terraform | vendor/github.com/terraform-providers/terraform-provider-aws/aws/resource_aws_cloudwatch_event_target.go | GO | mpl-2.0 | 11,014 |
from edxmako.shortcuts import render_to_string
from pipeline.conf import settings
from pipeline.packager import Packager
from pipeline.utils import guess_type
from static_replace import try_staticfiles_lookup
def compressed_css(package_name):
package = settings.PIPELINE_CSS.get(package_name, {})
if package:
package = {package_name: package}
packager = Packager(css_packages=package, js_packages={})
package = packager.package_for('css', package_name)
if settings.PIPELINE:
return render_css(package, package.output_filename)
else:
paths = packager.compile(package.paths)
return render_individual_css(package, paths)
def render_css(package, path):
template_name = package.template_name or "mako/css.html"
context = package.extra_context
url = try_staticfiles_lookup(path)
context.update({
'type': guess_type(path, 'text/css'),
'url': url,
})
return render_to_string(template_name, context)
def render_individual_css(package, paths):
tags = [render_css(package, path) for path in paths]
return '\n'.join(tags)
def compressed_js(package_name):
package = settings.PIPELINE_JS.get(package_name, {})
if package:
package = {package_name: package}
packager = Packager(css_packages={}, js_packages=package)
package = packager.package_for('js', package_name)
if settings.PIPELINE:
return render_js(package, package.output_filename)
else:
paths = packager.compile(package.paths)
templates = packager.pack_templates(package)
return render_individual_js(package, paths, templates)
def render_js(package, path):
template_name = package.template_name or "mako/js.html"
context = package.extra_context
context.update({
'type': guess_type(path, 'text/javascript'),
'url': try_staticfiles_lookup(path)
})
return render_to_string(template_name, context)
def render_inline_js(package, js):
context = package.extra_context
context.update({
'source': js
})
return render_to_string("mako/inline_js.html", context)
def render_individual_js(package, paths, templates=None):
tags = [render_js(package, js) for js in paths]
if templates:
tags.append(render_inline_js(package, templates))
return '\n'.join(tags)
| liuqr/edx-xiaodun | common/djangoapps/pipeline_mako/__init__.py | Python | agpl-3.0 | 2,354 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.hbase;
/**
* Encapsulates the information for a delete operation.
*/
public class DeleteRequest {
private byte[] rowId;
private byte[] columnFamily;
private byte[] columnQualifier;
private String visibilityLabel;
public DeleteRequest(byte[] rowId, byte[] columnFamily, byte[] columnQualifier, String visibilityLabel) {
this.rowId = rowId;
this.columnFamily = columnFamily;
this.columnQualifier = columnQualifier;
this.visibilityLabel = visibilityLabel;
}
public byte[] getRowId() {
return rowId;
}
public byte[] getColumnFamily() {
return columnFamily;
}
public byte[] getColumnQualifier() {
return columnQualifier;
}
public String getVisibilityLabel() {
return visibilityLabel;
}
@Override
public String toString() {
return new StringBuilder()
.append(String.format("Row ID: %s\n", new String(rowId)))
.append(String.format("Column Family: %s\n", new String(columnFamily)))
.append(String.format("Column Qualifier: %s\n", new String(columnQualifier)))
.append(visibilityLabel != null ? String.format("Visibility Label: %s", visibilityLabel) : "")
.toString();
}
}
| ijokarumawak/nifi | nifi-nar-bundles/nifi-standard-services/nifi-hbase-client-service-api/src/main/java/org/apache/nifi/hbase/DeleteRequest.java | Java | apache-2.0 | 2,100 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Differencing
{
/// <summary>
/// Represents an edit operation on a sequence of values.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
internal struct SequenceEdit : IEquatable<SequenceEdit>
{
private readonly int _oldIndex;
private readonly int _newIndex;
internal SequenceEdit(int oldIndex, int newIndex)
{
Debug.Assert(oldIndex >= -1);
Debug.Assert(newIndex >= -1);
Debug.Assert(newIndex != -1 || oldIndex != -1);
_oldIndex = oldIndex;
_newIndex = newIndex;
}
/// <summary>
/// The kind of edit: <see cref="EditKind.Delete"/>, <see cref="EditKind.Insert"/>, or <see cref="EditKind.Update"/>.
/// </summary>
public EditKind Kind
{
get
{
if (_oldIndex == -1)
{
return EditKind.Insert;
}
if (_newIndex == -1)
{
return EditKind.Delete;
}
return EditKind.Update;
}
}
/// <summary>
/// Index in the old sequence, or -1 if the edit is insert.
/// </summary>
public int OldIndex => _oldIndex;
/// <summary>
/// Index in the new sequence, or -1 if the edit is delete.
/// </summary>
public int NewIndex => _newIndex;
public bool Equals(SequenceEdit other)
{
return _oldIndex == other._oldIndex
&& _newIndex == other._newIndex;
}
public override bool Equals(object obj)
=> obj is SequenceEdit && Equals((SequenceEdit)obj);
public override int GetHashCode()
=> Hash.Combine(_oldIndex, _newIndex);
private string GetDebuggerDisplay()
{
var result = Kind.ToString();
switch (Kind)
{
case EditKind.Delete:
return result + " (" + _oldIndex + ")";
case EditKind.Insert:
return result + " (" + _newIndex + ")";
case EditKind.Update:
return result + " (" + _oldIndex + " -> " + _newIndex + ")";
}
return result;
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly SequenceEdit _sequenceEdit;
public TestAccessor(SequenceEdit sequenceEdit)
=> _sequenceEdit = sequenceEdit;
internal string GetDebuggerDisplay()
=> _sequenceEdit.GetDebuggerDisplay();
}
}
}
| physhi/roslyn | src/Workspaces/Core/Portable/Differencing/SequenceEdit.cs | C# | apache-2.0 | 3,081 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package icmp
import (
"fmt"
"net"
"reflect"
"testing"
"golang.org/x/net/internal/iana"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
func TestMarshalAndParseExtension(t *testing.T) {
fn := func(t *testing.T, proto int, typ Type, hdr, obj []byte, te Extension) error {
b, err := te.Marshal(proto)
if err != nil {
return err
}
if !reflect.DeepEqual(b, obj) {
return fmt.Errorf("got %#v; want %#v", b, obj)
}
switch typ {
case ipv4.ICMPTypeExtendedEchoRequest, ipv6.ICMPTypeExtendedEchoRequest:
exts, l, err := parseExtensions(typ, append(hdr, obj...), 0)
if err != nil {
return err
}
if l != 0 {
return fmt.Errorf("got %d; want 0", l)
}
if !reflect.DeepEqual(exts, []Extension{te}) {
return fmt.Errorf("got %#v; want %#v", exts[0], te)
}
default:
for i, wire := range []struct {
data []byte // original datagram
inlattr int // length of padded original datagram, a hint
outlattr int // length of padded original datagram, a want
err error
}{
{nil, 0, -1, errNoExtension},
{make([]byte, 127), 128, -1, errNoExtension},
{make([]byte, 128), 127, -1, errNoExtension},
{make([]byte, 128), 128, -1, errNoExtension},
{make([]byte, 128), 129, -1, errNoExtension},
{append(make([]byte, 128), append(hdr, obj...)...), 127, 128, nil},
{append(make([]byte, 128), append(hdr, obj...)...), 128, 128, nil},
{append(make([]byte, 128), append(hdr, obj...)...), 129, 128, nil},
{append(make([]byte, 512), append(hdr, obj...)...), 511, -1, errNoExtension},
{append(make([]byte, 512), append(hdr, obj...)...), 512, 512, nil},
{append(make([]byte, 512), append(hdr, obj...)...), 513, -1, errNoExtension},
} {
exts, l, err := parseExtensions(typ, wire.data, wire.inlattr)
if err != wire.err {
return fmt.Errorf("#%d: got %v; want %v", i, err, wire.err)
}
if wire.err != nil {
continue
}
if l != wire.outlattr {
return fmt.Errorf("#%d: got %d; want %d", i, l, wire.outlattr)
}
if !reflect.DeepEqual(exts, []Extension{te}) {
return fmt.Errorf("#%d: got %#v; want %#v", i, exts[0], te)
}
}
}
return nil
}
t.Run("MPLSLabelStack", func(t *testing.T) {
for _, et := range []struct {
proto int
typ Type
hdr []byte
obj []byte
ext Extension
}{
// MPLS label stack with no label
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x04, 0x01, 0x01,
},
ext: &MPLSLabelStack{
Class: classMPLSLabelStack,
Type: typeIncomingMPLSLabelStack,
},
},
// MPLS label stack with a single label
{
proto: iana.ProtocolIPv6ICMP,
typ: ipv6.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x08, 0x01, 0x01,
0x03, 0xe8, 0xe9, 0xff,
},
ext: &MPLSLabelStack{
Class: classMPLSLabelStack,
Type: typeIncomingMPLSLabelStack,
Labels: []MPLSLabel{
{
Label: 16014,
TC: 0x4,
S: true,
TTL: 255,
},
},
},
},
// MPLS label stack with multiple labels
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x0c, 0x01, 0x01,
0x03, 0xe8, 0xde, 0xfe,
0x03, 0xe8, 0xe1, 0xff,
},
ext: &MPLSLabelStack{
Class: classMPLSLabelStack,
Type: typeIncomingMPLSLabelStack,
Labels: []MPLSLabel{
{
Label: 16013,
TC: 0x7,
S: false,
TTL: 254,
},
{
Label: 16014,
TC: 0,
S: true,
TTL: 255,
},
},
},
},
} {
if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil {
t.Error(err)
}
}
})
t.Run("InterfaceInfo", func(t *testing.T) {
for _, et := range []struct {
proto int
typ Type
hdr []byte
obj []byte
ext Extension
}{
// Interface information with no attribute
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x04, 0x02, 0x00,
},
ext: &InterfaceInfo{
Class: classInterfaceInfo,
},
},
// Interface information with ifIndex and name
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x10, 0x02, 0x0a,
0x00, 0x00, 0x00, 0x10,
0x08, byte('e'), byte('n'), byte('1'),
byte('0'), byte('1'), 0x00, 0x00,
},
ext: &InterfaceInfo{
Class: classInterfaceInfo,
Type: 0x0a,
Interface: &net.Interface{
Index: 16,
Name: "en101",
},
},
},
// Interface information with ifIndex, IPAddr, name and MTU
{
proto: iana.ProtocolIPv6ICMP,
typ: ipv6.ICMPTypeDestinationUnreachable,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x28, 0x02, 0x0f,
0x00, 0x00, 0x00, 0x0f,
0x00, 0x02, 0x00, 0x00,
0xfe, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01,
0x08, byte('e'), byte('n'), byte('1'),
byte('0'), byte('1'), 0x00, 0x00,
0x00, 0x00, 0x20, 0x00,
},
ext: &InterfaceInfo{
Class: classInterfaceInfo,
Type: 0x0f,
Interface: &net.Interface{
Index: 15,
Name: "en101",
MTU: 8192,
},
Addr: &net.IPAddr{
IP: net.ParseIP("fe80::1"),
Zone: "en101",
},
},
},
} {
if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil {
t.Error(err)
}
}
})
t.Run("InterfaceIdent", func(t *testing.T) {
for _, et := range []struct {
proto int
typ Type
hdr []byte
obj []byte
ext Extension
}{
// Interface identification by name
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeExtendedEchoRequest,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x0c, 0x03, 0x01,
byte('e'), byte('n'), byte('1'), byte('0'),
byte('1'), 0x00, 0x00, 0x00,
},
ext: &InterfaceIdent{
Class: classInterfaceIdent,
Type: typeInterfaceByName,
Name: "en101",
},
},
// Interface identification by index
{
proto: iana.ProtocolIPv6ICMP,
typ: ipv6.ICMPTypeExtendedEchoRequest,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x08, 0x03, 0x02,
0x00, 0x00, 0x03, 0x8f,
},
ext: &InterfaceIdent{
Class: classInterfaceIdent,
Type: typeInterfaceByIndex,
Index: 911,
},
},
// Interface identification by address
{
proto: iana.ProtocolICMP,
typ: ipv4.ICMPTypeExtendedEchoRequest,
hdr: []byte{
0x20, 0x00, 0x00, 0x00,
},
obj: []byte{
0x00, 0x10, 0x03, 0x03,
byte(iana.AddrFamily48bitMAC >> 8), byte(iana.AddrFamily48bitMAC & 0x0f), 0x06, 0x00,
0x01, 0x23, 0x45, 0x67,
0x89, 0xab, 0x00, 0x00,
},
ext: &InterfaceIdent{
Class: classInterfaceIdent,
Type: typeInterfaceByAddress,
AFI: iana.AddrFamily48bitMAC,
Addr: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab},
},
},
} {
if err := fn(t, et.proto, et.typ, et.hdr, et.obj, et.ext); err != nil {
t.Error(err)
}
}
})
}
func TestParseInterfaceName(t *testing.T) {
ifi := InterfaceInfo{Interface: &net.Interface{}}
for i, tt := range []struct {
b []byte
error
}{
{[]byte{0, 'e', 'n', '0'}, errInvalidExtension},
{[]byte{4, 'e', 'n', '0'}, nil},
{[]byte{7, 'e', 'n', '0', 0xff, 0xff, 0xff, 0xff}, errInvalidExtension},
{[]byte{8, 'e', 'n', '0', 0xff, 0xff, 0xff}, errMessageTooShort},
} {
if _, err := ifi.parseName(tt.b); err != tt.error {
t.Errorf("#%d: got %v; want %v", i, err, tt.error)
}
}
}
| muzining/net | x/net/icmp/extension_test.go | GO | bsd-3-clause | 8,186 |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <iomanip>
// quoted
#include <iomanip>
#include <sstream>
#include <string>
#include <cassert>
#if _LIBCPP_STD_VER > 11
bool is_skipws ( const std::istream *is ) {
return ( is->flags() & std::ios_base::skipws ) != 0;
}
bool is_skipws ( const std::wistream *is ) {
return ( is->flags() & std::ios_base::skipws ) != 0;
}
void both_ways ( const char *p ) {
std::string str(p);
auto q = std::quoted(str);
std::stringstream ss;
bool skippingws = is_skipws ( &ss );
ss << q;
ss >> q;
}
void round_trip ( const char *p ) {
std::stringstream ss;
bool skippingws = is_skipws ( &ss );
ss << std::quoted(p);
std::string s;
ss >> std::quoted(s);
assert ( s == p );
assert ( skippingws == is_skipws ( &ss ));
}
void round_trip_ws ( const char *p ) {
std::stringstream ss;
std::noskipws ( ss );
bool skippingws = is_skipws ( &ss );
ss << std::quoted(p);
std::string s;
ss >> std::quoted(s);
assert ( s == p );
assert ( skippingws == is_skipws ( &ss ));
}
void round_trip_d ( const char *p, char delim ) {
std::stringstream ss;
ss << std::quoted(p, delim);
std::string s;
ss >> std::quoted(s, delim);
assert ( s == p );
}
void round_trip_e ( const char *p, char escape ) {
std::stringstream ss;
ss << std::quoted(p, '"', escape );
std::string s;
ss >> std::quoted(s, '"', escape );
assert ( s == p );
}
std::string quote ( const char *p, char delim='"', char escape='\\' ) {
std::stringstream ss;
ss << std::quoted(p, delim, escape);
std::string s;
ss >> s; // no quote
return s;
}
std::string unquote ( const char *p, char delim='"', char escape='\\' ) {
std::stringstream ss;
ss << p;
std::string s;
ss >> std::quoted(s, delim, escape);
return s;
}
void test_padding () {
{
std::stringstream ss;
ss << std::left << std::setw(10) << std::setfill('!') << std::quoted("abc", '`');
assert ( ss.str() == "`abc`!!!!!" );
}
{
std::stringstream ss;
ss << std::right << std::setw(10) << std::setfill('!') << std::quoted("abc", '`');
assert ( ss.str() == "!!!!!`abc`" );
}
}
void round_trip ( const wchar_t *p ) {
std::wstringstream ss;
bool skippingws = is_skipws ( &ss );
ss << std::quoted(p);
std::wstring s;
ss >> std::quoted(s);
assert ( s == p );
assert ( skippingws == is_skipws ( &ss ));
}
void round_trip_ws ( const wchar_t *p ) {
std::wstringstream ss;
std::noskipws ( ss );
bool skippingws = is_skipws ( &ss );
ss << std::quoted(p);
std::wstring s;
ss >> std::quoted(s);
assert ( s == p );
assert ( skippingws == is_skipws ( &ss ));
}
void round_trip_d ( const wchar_t *p, wchar_t delim ) {
std::wstringstream ss;
ss << std::quoted(p, delim);
std::wstring s;
ss >> std::quoted(s, delim);
assert ( s == p );
}
void round_trip_e ( const wchar_t *p, wchar_t escape ) {
std::wstringstream ss;
ss << std::quoted(p, wchar_t('"'), escape );
std::wstring s;
ss >> std::quoted(s, wchar_t('"'), escape );
assert ( s == p );
}
std::wstring quote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) {
std::wstringstream ss;
ss << std::quoted(p, delim, escape);
std::wstring s;
ss >> s; // no quote
return s;
}
std::wstring unquote ( const wchar_t *p, wchar_t delim='"', wchar_t escape='\\' ) {
std::wstringstream ss;
ss << p;
std::wstring s;
ss >> std::quoted(s, delim, escape);
return s;
}
int main()
{
both_ways ( "" ); // This is a compilation check
round_trip ( "" );
round_trip_ws ( "" );
round_trip_d ( "", 'q' );
round_trip_e ( "", 'q' );
round_trip ( L"" );
round_trip_ws ( L"" );
round_trip_d ( L"", 'q' );
round_trip_e ( L"", 'q' );
round_trip ( "Hi" );
round_trip_ws ( "Hi" );
round_trip_d ( "Hi", '!' );
round_trip_e ( "Hi", '!' );
assert ( quote ( "Hi", '!' ) == "!Hi!" );
assert ( quote ( "Hi!", '!' ) == R"(!Hi\!!)" );
round_trip ( L"Hi" );
round_trip_ws ( L"Hi" );
round_trip_d ( L"Hi", '!' );
round_trip_e ( L"Hi", '!' );
assert ( quote ( L"Hi", '!' ) == L"!Hi!" );
assert ( quote ( L"Hi!", '!' ) == LR"(!Hi\!!)" );
round_trip ( "Hi Mom" );
round_trip_ws ( "Hi Mom" );
round_trip ( L"Hi Mom" );
round_trip_ws ( L"Hi Mom" );
assert ( quote ( "" ) == "\"\"" );
assert ( quote ( L"" ) == L"\"\"" );
assert ( quote ( "a" ) == "\"a\"" );
assert ( quote ( L"a" ) == L"\"a\"" );
// missing end quote - must not hang
assert ( unquote ( "\"abc" ) == "abc" );
assert ( unquote ( L"\"abc" ) == L"abc" );
assert ( unquote ( "abc" ) == "abc" ); // no delimiter
assert ( unquote ( L"abc" ) == L"abc" ); // no delimiter
assert ( unquote ( "abc def" ) == "abc" ); // no delimiter
assert ( unquote ( L"abc def" ) == L"abc" ); // no delimiter
assert ( unquote ( "" ) == "" ); // nothing there
assert ( unquote ( L"" ) == L"" ); // nothing there
test_padding ();
}
#else
int main() {}
#endif
| mxOBS/deb-pkg_trusty_chromium-browser | third_party/libc++/trunk/test/input.output/iostream.format/quoted.manip/quoted.pass.cpp | C++ | bsd-3-clause | 5,616 |
/*
* Planck.js v0.1.34
*
* Copyright (c) 2016-2017 Ali Shakiba http://shakiba.me/planck.js
* Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
/*
* Stage.js
*
* @copyright 2017 Ali Shakiba http://shakiba.me/stage.js
* @license The MIT License
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.planck=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var planck = require("../lib/");
var Stage = require("stage-js/platform/web");
module.exports = planck;
planck.testbed = function(opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = null;
}
Stage(function(stage, canvas) {
stage.on(Stage.Mouse.START, function() {
window.focus();
document.activeElement && document.activeElement.blur();
canvas.focus();
});
stage.MAX_ELAPSE = 1e3 / 30;
var Vec2 = planck.Vec2;
var testbed = {};
var paused = false;
stage.on("resume", function() {
paused = false;
testbed._resume && testbed._resume();
});
stage.on("pause", function() {
paused = true;
testbed._pause && testbed._pause();
});
testbed.isPaused = function() {
return paused;
};
testbed.togglePause = function() {
paused ? testbed.play() : testbed.pause();
};
testbed.pause = function() {
stage.pause();
};
testbed.resume = function() {
stage.resume();
testbed.focus();
};
testbed.focus = function() {
document.activeElement && document.activeElement.blur();
canvas.focus();
};
testbed.focus = function() {
document.activeElement && document.activeElement.blur();
canvas.focus();
};
testbed.debug = false;
testbed.width = 80;
testbed.height = 60;
testbed.x = 0;
testbed.y = -10;
testbed.ratio = 16;
testbed.hz = 60;
testbed.speed = 1;
testbed.activeKeys = {};
testbed.background = "#222222";
var statusText = "";
var statusMap = {};
function statusSet(name, value) {
if (typeof value !== "function" && typeof value !== "object") {
statusMap[name] = value;
}
}
function statusMerge(obj) {
for (var key in obj) {
statusSet(key, obj[key]);
}
}
testbed.status = function(a, b) {
if (typeof b !== "undefined") {
statusSet(a, b);
} else if (a && typeof a === "object") {
statusMerge(a);
} else if (typeof a === "string") {
statusText = a;
}
testbed._status && testbed._status(statusText, statusMap);
};
testbed.info = function(text) {
testbed._info && testbed._info(text);
};
var lastDrawHash = "", drawHash = "";
(function() {
var drawingTexture = new Stage.Texture();
stage.append(Stage.image(drawingTexture));
var buffer = [];
stage.tick(function() {
buffer.length = 0;
}, true);
drawingTexture.draw = function(ctx) {
ctx.save();
ctx.transform(1, 0, 0, -1, -testbed.x, -testbed.y);
ctx.lineWidth = 2 / testbed.ratio;
ctx.lineCap = "round";
for (var drawing = buffer.shift(); drawing; drawing = buffer.shift()) {
drawing(ctx, testbed.ratio);
}
ctx.restore();
};
testbed.drawPoint = function(p, r, color) {
buffer.push(function(ctx, ratio) {
ctx.beginPath();
ctx.arc(p.x, p.y, 5 / ratio, 0, 2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "point" + p.x + "," + p.y + "," + r + "," + color;
};
testbed.drawCircle = function(p, r, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.arc(p.x, p.y, r, 0, 2 * Math.PI);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "circle" + p.x + "," + p.y + "," + r + "," + color;
};
testbed.drawSegment = function(a, b, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(a.x, a.y);
ctx.lineTo(b.x, b.y);
ctx.strokeStyle = color;
ctx.stroke();
});
drawHash += "segment" + a.x + "," + a.y + "," + b.x + "," + b.y + "," + color;
};
testbed.drawPolygon = function(points, color) {
if (!points || !points.length) {
return;
}
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (var i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
});
drawHash += "segment";
for (var i = 1; i < points.length; i++) {
drawHash += points[i].x + "," + points[i].y + ",";
}
drawHash += color;
};
testbed.drawAABB = function(aabb, color) {
buffer.push(function(ctx) {
ctx.beginPath();
ctx.moveTo(aabb.lowerBound.x, aabb.lowerBound.y);
ctx.lineTo(aabb.upperBound.x, aabb.lowerBound.y);
ctx.lineTo(aabb.upperBound.x, aabb.upperBound.y);
ctx.lineTo(aabb.lowerBound.x, aabb.upperBound.y);
ctx.strokeStyle = color;
ctx.closePath();
ctx.stroke();
});
drawHash += "aabb";
drawHash += aabb.lowerBound.x + "," + aabb.lowerBound.y + ",";
drawHash += aabb.upperBound.x + "," + aabb.upperBound.y + ",";
drawHash += color;
};
testbed.color = function(r, g, b) {
r = r * 256 | 0;
g = g * 256 | 0;
b = b * 256 | 0;
return "rgb(" + r + ", " + g + ", " + b + ")";
};
})();
var world = callback(testbed);
var viewer = new Viewer(world, testbed);
var lastX = 0, lastY = 0;
stage.tick(function(dt, t) {
if (lastX !== testbed.x || lastY !== testbed.y) {
viewer.offset(-testbed.x, -testbed.y);
lastX = testbed.x, lastY = testbed.y;
}
});
viewer.tick(function(dt, t) {
if (typeof testbed.step === "function") {
testbed.step(dt, t);
}
if (targetBody) {
testbed.drawSegment(targetBody.getPosition(), mouseMove, "rgba(255,255,255,0.2)");
}
if (lastDrawHash !== drawHash) {
lastDrawHash = drawHash;
stage.touch();
}
drawHash = "";
return true;
});
viewer.scale(1, -1);
stage.background(testbed.background);
stage.viewbox(testbed.width, testbed.height);
stage.pin("alignX", -.5);
stage.pin("alignY", -.5);
stage.prepend(viewer);
function findBody(point) {
var body;
var aabb = planck.AABB(point, point);
world.queryAABB(aabb, function(fixture) {
if (body) {
return;
}
if (!fixture.getBody().isDynamic() || !fixture.testPoint(point)) {
return;
}
body = fixture.getBody();
return true;
});
return body;
}
var mouseGround = world.createBody();
var mouseJoint;
var targetBody;
var mouseMove = {
x: 0,
y: 0
};
viewer.attr("spy", true).on(Stage.Mouse.START, function(point) {
if (targetBody) {
return;
}
var body = findBody(point);
if (!body) {
return;
}
if (testbed.mouseForce) {
targetBody = body;
} else {
mouseJoint = planck.MouseJoint({
maxForce: 1e3
}, mouseGround, body, Vec2(point));
world.createJoint(mouseJoint);
}
}).on(Stage.Mouse.MOVE, function(point) {
if (mouseJoint) {
mouseJoint.setTarget(point);
}
mouseMove.x = point.x;
mouseMove.y = point.y;
}).on(Stage.Mouse.END, function(point) {
if (mouseJoint) {
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
if (targetBody) {
var force = Vec2.sub(point, targetBody.getPosition());
targetBody.applyForceToCenter(force.mul(testbed.mouseForce), true);
targetBody = null;
}
}).on(Stage.Mouse.CANCEL, function(point) {
if (mouseJoint) {
world.destroyJoint(mouseJoint);
mouseJoint = null;
}
if (targetBody) {
targetBody = null;
}
});
window.addEventListener("keydown", function(e) {
switch (e.keyCode) {
case "P".charCodeAt(0):
testbed.togglePause();
break;
}
}, false);
var downKeys = {};
window.addEventListener("keydown", function(e) {
var keyCode = e.keyCode;
downKeys[keyCode] = true;
updateActiveKeys(keyCode, true);
testbed.keydown && testbed.keydown(keyCode, String.fromCharCode(keyCode));
});
window.addEventListener("keyup", function(e) {
var keyCode = e.keyCode;
downKeys[keyCode] = false;
updateActiveKeys(keyCode, false);
testbed.keyup && testbed.keyup(keyCode, String.fromCharCode(keyCode));
});
var activeKeys = testbed.activeKeys;
function updateActiveKeys(keyCode, down) {
var char = String.fromCharCode(keyCode);
if (/\w/.test(char)) {
activeKeys[char] = down;
}
activeKeys.right = downKeys[39] || activeKeys["D"];
activeKeys.left = downKeys[37] || activeKeys["A"];
activeKeys.up = downKeys[38] || activeKeys["W"];
activeKeys.down = downKeys[40] || activeKeys["S"];
activeKeys.fire = downKeys[32] || downKeys[13];
}
});
};
Viewer._super = Stage;
Viewer.prototype = Stage._create(Viewer._super.prototype);
function Viewer(world, opts) {
Viewer._super.call(this);
this.label("Planck");
opts = opts || {};
var options = this._options = {};
this._options.speed = opts.speed || 1;
this._options.hz = opts.hz || 60;
if (Math.abs(this._options.hz) < 1) {
this._options.hz = 1 / this._options.hz;
}
this._options.ratio = opts.ratio || 16;
this._options.lineWidth = 2 / this._options.ratio;
this._world = world;
var timeStep = 1 / this._options.hz;
var elapsedTime = 0;
this.tick(function(dt) {
dt = dt * .001 * options.speed;
elapsedTime += dt;
while (elapsedTime > timeStep) {
world.step(timeStep);
elapsedTime -= timeStep;
}
this.renderWorld();
return true;
}, true);
world.on("remove-fixture", function(obj) {
obj.ui && obj.ui.remove();
});
world.on("remove-joint", function(obj) {
obj.ui && obj.ui.remove();
});
}
Viewer.prototype.renderWorld = function(world) {
var world = this._world;
var viewer = this;
for (var b = world.getBodyList(); b; b = b.getNext()) {
for (var f = b.getFixtureList(); f; f = f.getNext()) {
if (!f.ui) {
if (f.render && f.render.stroke) {
this._options.strokeStyle = f.render.stroke;
} else if (b.render && b.render.stroke) {
this._options.strokeStyle = b.render.stroke;
} else if (b.isDynamic()) {
this._options.strokeStyle = "rgba(255,255,255,0.9)";
} else if (b.isKinematic()) {
this._options.strokeStyle = "rgba(255,255,255,0.7)";
} else if (b.isStatic()) {
this._options.strokeStyle = "rgba(255,255,255,0.5)";
}
if (f.render && f.render.fill) {
this._options.fillStyle = f.render.fill;
} else if (b.render && b.render.fill) {
this._options.fillStyle = b.render.fill;
} else {
this._options.fillStyle = "";
}
var type = f.getType();
var shape = f.getShape();
if (type == "circle") {
f.ui = viewer.drawCircle(shape, this._options);
}
if (type == "edge") {
f.ui = viewer.drawEdge(shape, this._options);
}
if (type == "polygon") {
f.ui = viewer.drawPolygon(shape, this._options);
}
if (type == "chain") {
f.ui = viewer.drawChain(shape, this._options);
}
if (f.ui) {
f.ui.appendTo(viewer);
}
}
if (f.ui) {
var p = b.getPosition(), r = b.getAngle();
if (f.ui.__lastX !== p.x || f.ui.__lastY !== p.y || f.ui.__lastR !== r) {
f.ui.__lastX = p.x;
f.ui.__lastY = p.y;
f.ui.__lastR = r;
f.ui.offset(p.x, p.y);
f.ui.rotate(r);
}
}
}
}
for (var j = world.getJointList(); j; j = j.getNext()) {
var type = j.getType();
var a = j.getAnchorA();
var b = j.getAnchorB();
if (!j.ui) {
this._options.strokeStyle = "rgba(255,255,255,0.2)";
j.ui = viewer.drawJoint(j, this._options);
j.ui.pin("handle", .5);
if (j.ui) {
j.ui.appendTo(viewer);
}
}
if (j.ui) {
var cx = (a.x + b.x) * .5;
var cy = (a.y + b.y) * .5;
var dx = a.x - b.x;
var dy = a.y - b.y;
var d = Math.sqrt(dx * dx + dy * dy);
j.ui.width(d);
j.ui.rotate(Math.atan2(dy, dx));
j.ui.offset(cx, cy);
}
}
};
Viewer.prototype.drawJoint = function(joint, options) {
var lw = options.lineWidth;
var ratio = options.ratio;
var length = 10;
var texture = Stage.canvas(function(ctx) {
this.size(length + 2 * lw, 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
ctx.moveTo(lw, lw);
ctx.lineTo(lw + length, lw);
ctx.lineCap = "round";
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
var image = Stage.image(texture).stretch();
return image;
};
Viewer.prototype.drawCircle = function(shape, options) {
var lw = options.lineWidth;
var ratio = options.ratio;
var r = shape.m_radius;
var cx = r + lw;
var cy = r + lw;
var w = r * 2 + lw * 2;
var h = r * 2 + lw * 2;
var texture = Stage.canvas(function(ctx) {
this.size(w, h, ratio);
ctx.scale(ratio, ratio);
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
}
ctx.lineTo(cx, cy);
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
var image = Stage.image(texture).offset(shape.m_p.x - cx, shape.m_p.y - cy);
var node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawEdge = function(edge, options) {
var lw = options.lineWidth;
var ratio = options.ratio;
var v1 = edge.m_vertex1;
var v2 = edge.m_vertex2;
var dx = v2.x - v1.x;
var dy = v2.y - v1.y;
var length = Math.sqrt(dx * dx + dy * dy);
var texture = Stage.canvas(function(ctx) {
this.size(length + 2 * lw, 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
ctx.moveTo(lw, lw);
ctx.lineTo(lw + length, lw);
ctx.lineCap = "round";
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
var minX = Math.min(v1.x, v2.x);
var minY = Math.min(v1.y, v2.y);
var image = Stage.image(texture);
image.rotate(Math.atan2(dy, dx));
image.offset(minX - lw, minY - lw);
var node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawPolygon = function(shape, options) {
var lw = options.lineWidth;
var ratio = options.ratio;
var vertices = shape.m_vertices;
if (!vertices.length) {
return;
}
var minX = Infinity, minY = Infinity;
var maxX = -Infinity, maxY = -Infinity;
for (var i = 0; i < vertices.length; ++i) {
var v = vertices[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y);
}
var width = maxX - minX;
var height = maxY - minY;
var texture = Stage.canvas(function(ctx) {
this.size(width + 2 * lw, height + 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
for (var i = 0; i < vertices.length; ++i) {
var v = vertices[i];
var x = v.x - minX + lw;
var y = v.y - minY + lw;
if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
if (vertices.length > 2) {
ctx.closePath();
}
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
ctx.closePath();
}
ctx.lineCap = "round";
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
var image = Stage.image(texture);
image.offset(minX - lw, minY - lw);
var node = Stage.create().append(image);
return node;
};
Viewer.prototype.drawChain = function(shape, options) {
var lw = options.lineWidth;
var ratio = options.ratio;
var vertices = shape.m_vertices;
if (!vertices.length) {
return;
}
var minX = Infinity, minY = Infinity;
var maxX = -Infinity, maxY = -Infinity;
for (var i = 0; i < vertices.length; ++i) {
var v = vertices[i];
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y);
}
var width = maxX - minX;
var height = maxY - minY;
var texture = Stage.canvas(function(ctx) {
this.size(width + 2 * lw, height + 2 * lw, ratio);
ctx.scale(ratio, ratio);
ctx.beginPath();
for (var i = 0; i < vertices.length; ++i) {
var v = vertices[i];
var x = v.x - minX + lw;
var y = v.y - minY + lw;
if (i == 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
if (vertices.length > 2) {}
if (options.fillStyle) {
ctx.fillStyle = options.fillStyle;
ctx.fill();
ctx.closePath();
}
ctx.lineCap = "round";
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
ctx.stroke();
});
var image = Stage.image(texture);
image.offset(minX - lw, minY - lw);
var node = Stage.create().append(image);
return node;
};
},{"../lib/":27,"stage-js/platform/web":82}],2:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Body;
var common = require("./util/common");
var options = require("./util/options");
var Vec2 = require("./common/Vec2");
var Rot = require("./common/Rot");
var Math = require("./common/Math");
var Sweep = require("./common/Sweep");
var Transform = require("./common/Transform");
var Velocity = require("./common/Velocity");
var Position = require("./common/Position");
var Fixture = require("./Fixture");
var Shape = require("./Shape");
var World = require("./World");
var staticBody = Body.STATIC = "static";
var kinematicBody = Body.KINEMATIC = "kinematic";
var dynamicBody = Body.DYNAMIC = "dynamic";
var BodyDef = {
type: staticBody,
position: Vec2.zero(),
angle: 0,
linearVelocity: Vec2.zero(),
angularVelocity: 0,
linearDamping: 0,
angularDamping: 0,
fixedRotation: false,
bullet: false,
gravityScale: 1,
allowSleep: true,
awake: true,
active: true,
userData: null
};
function Body(world, def) {
def = options(def, BodyDef);
ASSERT && common.assert(Vec2.isValid(def.position));
ASSERT && common.assert(Vec2.isValid(def.linearVelocity));
ASSERT && common.assert(Math.isFinite(def.angle));
ASSERT && common.assert(Math.isFinite(def.angularVelocity));
ASSERT && common.assert(Math.isFinite(def.angularDamping) && def.angularDamping >= 0);
ASSERT && common.assert(Math.isFinite(def.linearDamping) && def.linearDamping >= 0);
this.m_world = world;
this.m_awakeFlag = def.awake;
this.m_autoSleepFlag = def.allowSleep;
this.m_bulletFlag = def.bullet;
this.m_fixedRotationFlag = def.fixedRotation;
this.m_activeFlag = def.active;
this.m_islandFlag = false;
this.m_toiFlag = false;
this.m_userData = def.userData;
this.m_type = def.type;
if (this.m_type == dynamicBody) {
this.m_mass = 1;
this.m_invMass = 1;
} else {
this.m_mass = 0;
this.m_invMass = 0;
}
this.m_I = 0;
this.m_invI = 0;
this.m_xf = Transform.identity();
this.m_xf.p = Vec2.clone(def.position);
this.m_xf.q.setAngle(def.angle);
this.m_sweep = new Sweep();
this.m_sweep.setTransform(this.m_xf);
this.c_velocity = new Velocity();
this.c_position = new Position();
this.m_force = Vec2.zero();
this.m_torque = 0;
this.m_linearVelocity = Vec2.clone(def.linearVelocity);
this.m_angularVelocity = def.angularVelocity;
this.m_linearDamping = def.linearDamping;
this.m_angularDamping = def.angularDamping;
this.m_gravityScale = def.gravityScale;
this.m_sleepTime = 0;
this.m_jointList = null;
this.m_contactList = null;
this.m_fixtureList = null;
this.m_prev = null;
this.m_next = null;
}
Body.prototype.isWorldLocked = function() {
return this.m_world && this.m_world.isLocked() ? true : false;
};
Body.prototype.getWorld = function() {
return this.m_world;
};
Body.prototype.getNext = function() {
return this.m_next;
};
Body.prototype.setUserData = function(data) {
this.m_userData = data;
};
Body.prototype.getUserData = function() {
return this.m_userData;
};
Body.prototype.getFixtureList = function() {
return this.m_fixtureList;
};
Body.prototype.getJointList = function() {
return this.m_jointList;
};
Body.prototype.getContactList = function() {
return this.m_contactList;
};
Body.prototype.isStatic = function() {
return this.m_type == staticBody;
};
Body.prototype.isDynamic = function() {
return this.m_type == dynamicBody;
};
Body.prototype.isKinematic = function() {
return this.m_type == kinematicBody;
};
Body.prototype.setStatic = function() {
this.setType(staticBody);
return this;
};
Body.prototype.setDynamic = function() {
this.setType(dynamicBody);
return this;
};
Body.prototype.setKinematic = function() {
this.setType(kinematicBody);
return this;
};
Body.prototype.getType = function() {
return this.m_type;
};
Body.prototype.setType = function(type) {
ASSERT && common.assert(type === staticBody || type === kinematicBody || type === dynamicBody);
ASSERT && common.assert(this.isWorldLocked() == false);
if (this.isWorldLocked() == true) {
return;
}
if (this.m_type == type) {
return;
}
this.m_type = type;
this.resetMassData();
if (this.m_type == staticBody) {
this.m_linearVelocity.setZero();
this.m_angularVelocity = 0;
this.m_sweep.forward();
this.synchronizeFixtures();
}
this.setAwake(true);
this.m_force.setZero();
this.m_torque = 0;
var ce = this.m_contactList;
while (ce) {
var ce0 = ce;
ce = ce.next;
this.m_world.destroyContact(ce0.contact);
}
this.m_contactList = null;
var broadPhase = this.m_world.m_broadPhase;
for (var f = this.m_fixtureList; f; f = f.m_next) {
var proxyCount = f.m_proxyCount;
for (var i = 0; i < proxyCount; ++i) {
broadPhase.touchProxy(f.m_proxies[i].proxyId);
}
}
};
Body.prototype.isBullet = function() {
return this.m_bulletFlag;
};
Body.prototype.setBullet = function(flag) {
this.m_bulletFlag = !!flag;
};
Body.prototype.isSleepingAllowed = function() {
return this.m_autoSleepFlag;
};
Body.prototype.setSleepingAllowed = function(flag) {
this.m_autoSleepFlag = !!flag;
if (this.m_autoSleepFlag == false) {
this.setAwake(true);
}
};
Body.prototype.isAwake = function() {
return this.m_awakeFlag;
};
Body.prototype.setAwake = function(flag) {
if (flag) {
if (this.m_awakeFlag == false) {
this.m_awakeFlag = true;
this.m_sleepTime = 0;
}
} else {
this.m_awakeFlag = false;
this.m_sleepTime = 0;
this.m_linearVelocity.setZero();
this.m_angularVelocity = 0;
this.m_force.setZero();
this.m_torque = 0;
}
};
Body.prototype.isActive = function() {
return this.m_activeFlag;
};
Body.prototype.setActive = function(flag) {
ASSERT && common.assert(this.isWorldLocked() == false);
if (flag == this.m_activeFlag) {
return;
}
this.m_activeFlag = !!flag;
if (this.m_activeFlag) {
var broadPhase = this.m_world.m_broadPhase;
for (var f = this.m_fixtureList; f; f = f.m_next) {
f.createProxies(broadPhase, this.m_xf);
}
} else {
var broadPhase = this.m_world.m_broadPhase;
for (var f = this.m_fixtureList; f; f = f.m_next) {
f.destroyProxies(broadPhase);
}
var ce = this.m_contactList;
while (ce) {
var ce0 = ce;
ce = ce.next;
this.m_world.destroyContact(ce0.contact);
}
this.m_contactList = null;
}
};
Body.prototype.isFixedRotation = function() {
return this.m_fixedRotationFlag;
};
Body.prototype.setFixedRotation = function(flag) {
if (this.m_fixedRotationFlag == flag) {
return;
}
this.m_fixedRotationFlag = !!flag;
this.m_angularVelocity = 0;
this.resetMassData();
};
Body.prototype.getTransform = function() {
return this.m_xf;
};
Body.prototype.setTransform = function(position, angle) {
ASSERT && common.assert(this.isWorldLocked() == false);
if (this.isWorldLocked() == true) {
return;
}
this.m_xf.set(position, angle);
this.m_sweep.setTransform(this.m_xf);
var broadPhase = this.m_world.m_broadPhase;
for (var f = this.m_fixtureList; f; f = f.m_next) {
f.synchronize(broadPhase, this.m_xf, this.m_xf);
}
};
Body.prototype.synchronizeTransform = function() {
this.m_sweep.getTransform(this.m_xf, 1);
};
Body.prototype.synchronizeFixtures = function() {
var xf = Transform.identity();
this.m_sweep.getTransform(xf, 0);
var broadPhase = this.m_world.m_broadPhase;
for (var f = this.m_fixtureList; f; f = f.m_next) {
f.synchronize(broadPhase, xf, this.m_xf);
}
};
Body.prototype.advance = function(alpha) {
this.m_sweep.advance(alpha);
this.m_sweep.c.set(this.m_sweep.c0);
this.m_sweep.a = this.m_sweep.a0;
this.m_sweep.getTransform(this.m_xf, 1);
};
Body.prototype.getPosition = function() {
return this.m_xf.p;
};
Body.prototype.setPosition = function(p) {
this.setTransform(p, this.m_sweep.a);
};
Body.prototype.getAngle = function() {
return this.m_sweep.a;
};
Body.prototype.setAngle = function(angle) {
this.setTransform(this.m_xf.p, angle);
};
Body.prototype.getWorldCenter = function() {
return this.m_sweep.c;
};
Body.prototype.getLocalCenter = function() {
return this.m_sweep.localCenter;
};
Body.prototype.getLinearVelocity = function() {
return this.m_linearVelocity;
};
Body.prototype.getLinearVelocityFromWorldPoint = function(worldPoint) {
var localCenter = Vec2.sub(worldPoint, this.m_sweep.c);
return Vec2.add(this.m_linearVelocity, Vec2.cross(this.m_angularVelocity, localCenter));
};
Body.prototype.getLinearVelocityFromLocalPoint = function(localPoint) {
return this.getLinearVelocityFromWorldPoint(this.getWorldPoint(localPoint));
};
Body.prototype.setLinearVelocity = function(v) {
if (this.m_type == staticBody) {
return;
}
if (Vec2.dot(v, v) > 0) {
this.setAwake(true);
}
this.m_linearVelocity.set(v);
};
Body.prototype.getAngularVelocity = function() {
return this.m_angularVelocity;
};
Body.prototype.setAngularVelocity = function(w) {
if (this.m_type == staticBody) {
return;
}
if (w * w > 0) {
this.setAwake(true);
}
this.m_angularVelocity = w;
};
Body.prototype.getLinearDamping = function() {
return this.m_linearDamping;
};
Body.prototype.setLinearDamping = function(linearDamping) {
this.m_linearDamping = linearDamping;
};
Body.prototype.getAngularDamping = function() {
return this.m_angularDamping;
};
Body.prototype.setAngularDamping = function(angularDamping) {
this.m_angularDamping = angularDamping;
};
Body.prototype.getGravityScale = function() {
return this.m_gravityScale;
};
Body.prototype.setGravityScale = function(scale) {
this.m_gravityScale = scale;
};
Body.prototype.getMass = function() {
return this.m_mass;
};
Body.prototype.getInertia = function() {
return this.m_I + this.m_mass * Vec2.dot(this.m_sweep.localCenter, this.m_sweep.localCenter);
};
function MassData() {
this.mass = 0;
this.center = Vec2.zero();
this.I = 0;
}
Body.prototype.getMassData = function(data) {
data.mass = this.m_mass;
data.I = this.getInertia();
data.center.set(this.m_sweep.localCenter);
};
Body.prototype.resetMassData = function() {
this.m_mass = 0;
this.m_invMass = 0;
this.m_I = 0;
this.m_invI = 0;
this.m_sweep.localCenter.setZero();
if (this.isStatic() || this.isKinematic()) {
this.m_sweep.c0.set(this.m_xf.p);
this.m_sweep.c.set(this.m_xf.p);
this.m_sweep.a0 = this.m_sweep.a;
return;
}
ASSERT && common.assert(this.isDynamic());
var localCenter = Vec2.zero();
for (var f = this.m_fixtureList; f; f = f.m_next) {
if (f.m_density == 0) {
continue;
}
var massData = new MassData();
f.getMassData(massData);
this.m_mass += massData.mass;
localCenter.wAdd(massData.mass, massData.center);
this.m_I += massData.I;
}
if (this.m_mass > 0) {
this.m_invMass = 1 / this.m_mass;
localCenter.mul(this.m_invMass);
} else {
this.m_mass = 1;
this.m_invMass = 1;
}
if (this.m_I > 0 && this.m_fixedRotationFlag == false) {
this.m_I -= this.m_mass * Vec2.dot(localCenter, localCenter);
ASSERT && common.assert(this.m_I > 0);
this.m_invI = 1 / this.m_I;
} else {
this.m_I = 0;
this.m_invI = 0;
}
var oldCenter = Vec2.clone(this.m_sweep.c);
this.m_sweep.setLocalCenter(localCenter, this.m_xf);
this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter)));
};
Body.prototype.setMassData = function(massData) {
ASSERT && common.assert(this.isWorldLocked() == false);
if (this.isWorldLocked() == true) {
return;
}
if (this.m_type != dynamicBody) {
return;
}
this.m_invMass = 0;
this.m_I = 0;
this.m_invI = 0;
this.m_mass = massData.mass;
if (this.m_mass <= 0) {
this.m_mass = 1;
}
this.m_invMass = 1 / this.m_mass;
if (massData.I > 0 && this.m_fixedRotationFlag == false) {
this.m_I = massData.I - this.m_mass * Vec2.dot(massData.center, massData.center);
ASSERT && common.assert(this.m_I > 0);
this.m_invI = 1 / this.m_I;
}
var oldCenter = Vec2.clone(this.m_sweep.c);
this.m_sweep.setLocalCenter(massData.center, this.m_xf);
this.m_linearVelocity.add(Vec2.cross(this.m_angularVelocity, Vec2.sub(this.m_sweep.c, oldCenter)));
};
Body.prototype.applyForce = function(force, point, wake) {
if (this.m_type != dynamicBody) {
return;
}
if (wake && this.m_awakeFlag == false) {
this.setAwake(true);
}
if (this.m_awakeFlag) {
this.m_force.add(force);
this.m_torque += Vec2.cross(Vec2.sub(point, this.m_sweep.c), force);
}
};
Body.prototype.applyForceToCenter = function(force, wake) {
if (this.m_type != dynamicBody) {
return;
}
if (wake && this.m_awakeFlag == false) {
this.setAwake(true);
}
if (this.m_awakeFlag) {
this.m_force.add(force);
}
};
Body.prototype.applyTorque = function(torque, wake) {
if (this.m_type != dynamicBody) {
return;
}
if (wake && this.m_awakeFlag == false) {
this.setAwake(true);
}
if (this.m_awakeFlag) {
this.m_torque += torque;
}
};
Body.prototype.applyLinearImpulse = function(impulse, point, wake) {
if (this.m_type != dynamicBody) {
return;
}
if (wake && this.m_awakeFlag == false) {
this.setAwake(true);
}
if (this.m_awakeFlag) {
this.m_linearVelocity.wAdd(this.m_invMass, impulse);
this.m_angularVelocity += this.m_invI * Vec2.cross(Vec2.sub(point, this.m_sweep.c), impulse);
}
};
Body.prototype.applyAngularImpulse = function(impulse, wake) {
if (this.m_type != dynamicBody) {
return;
}
if (wake && this.m_awakeFlag == false) {
this.setAwake(true);
}
if (this.m_awakeFlag) {
this.m_angularVelocity += this.m_invI * impulse;
}
};
Body.prototype.shouldCollide = function(that) {
if (this.m_type != dynamicBody && that.m_type != dynamicBody) {
return false;
}
for (var jn = this.m_jointList; jn; jn = jn.next) {
if (jn.other == that) {
if (jn.joint.m_collideConnected == false) {
return false;
}
}
}
return true;
};
Body.prototype.createFixture = function(shape, fixdef) {
ASSERT && common.assert(this.isWorldLocked() == false);
if (this.isWorldLocked() == true) {
return null;
}
var fixture = new Fixture(this, shape, fixdef);
if (this.m_activeFlag) {
var broadPhase = this.m_world.m_broadPhase;
fixture.createProxies(broadPhase, this.m_xf);
}
fixture.m_next = this.m_fixtureList;
this.m_fixtureList = fixture;
if (fixture.m_density > 0) {
this.resetMassData();
}
this.m_world.m_newFixture = true;
return fixture;
};
Body.prototype.destroyFixture = function(fixture) {
ASSERT && common.assert(this.isWorldLocked() == false);
if (this.isWorldLocked() == true) {
return;
}
ASSERT && common.assert(fixture.m_body == this);
var node = this.m_fixtureList;
var found = false;
while (node != null) {
if (node == fixture) {
node = fixture.m_next;
found = true;
break;
}
node = node.m_next;
}
ASSERT && common.assert(found);
var edge = this.m_contactList;
while (edge) {
var c = edge.contact;
edge = edge.next;
var fixtureA = c.getFixtureA();
var fixtureB = c.getFixtureB();
if (fixture == fixtureA || fixture == fixtureB) {
this.m_world.destroyContact(c);
}
}
if (this.m_activeFlag) {
var broadPhase = this.m_world.m_broadPhase;
fixture.destroyProxies(broadPhase);
}
fixture.m_body = null;
fixture.m_next = null;
this.m_world.publish("remove-fixture", fixture);
this.resetMassData();
};
Body.prototype.getWorldPoint = function(localPoint) {
return Transform.mul(this.m_xf, localPoint);
};
Body.prototype.getWorldVector = function(localVector) {
return Rot.mul(this.m_xf.q, localVector);
};
Body.prototype.getLocalPoint = function(worldPoint) {
return Transform.mulT(this.m_xf, worldPoint);
};
Body.prototype.getLocalVector = function(worldVector) {
return Rot.mulT(this.m_xf.q, worldVector);
};
},{"./Fixture":4,"./Shape":8,"./World":10,"./common/Math":18,"./common/Position":19,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/Velocity":25,"./util/common":51,"./util/options":53}],3:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var DEBUG_SOLVER = false;
var common = require("./util/common");
var Math = require("./common/Math");
var Vec2 = require("./common/Vec2");
var Transform = require("./common/Transform");
var Mat22 = require("./common/Mat22");
var Rot = require("./common/Rot");
var Settings = require("./Settings");
var Manifold = require("./Manifold");
var Distance = require("./collision/Distance");
module.exports = Contact;
function ContactEdge(contact) {
this.contact = contact;
this.prev;
this.next;
this.other;
}
function Contact(fA, indexA, fB, indexB, evaluateFcn) {
this.m_nodeA = new ContactEdge(this);
this.m_nodeB = new ContactEdge(this);
this.m_fixtureA = fA;
this.m_fixtureB = fB;
this.m_indexA = indexA;
this.m_indexB = indexB;
this.m_evaluateFcn = evaluateFcn;
this.m_manifold = new Manifold();
this.m_prev = null;
this.m_next = null;
this.m_toi = 1;
this.m_toiCount = 0;
this.m_toiFlag = false;
this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction);
this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution);
this.m_tangentSpeed = 0;
this.m_enabledFlag = true;
this.m_islandFlag = false;
this.m_touchingFlag = false;
this.m_filterFlag = false;
this.m_bulletHitFlag = false;
this.v_points = [];
this.v_normal = Vec2.zero();
this.v_normalMass = new Mat22();
this.v_K = new Mat22();
this.v_pointCount;
this.v_tangentSpeed;
this.v_friction;
this.v_restitution;
this.v_invMassA;
this.v_invMassB;
this.v_invIA;
this.v_invIB;
this.p_localPoints = [];
this.p_localNormal = Vec2.zero();
this.p_localPoint = Vec2.zero();
this.p_localCenterA = Vec2.zero();
this.p_localCenterB = Vec2.zero();
this.p_type;
this.p_radiusA;
this.p_radiusB;
this.p_pointCount;
this.p_invMassA;
this.p_invMassB;
this.p_invIA;
this.p_invIB;
}
Contact.prototype.initConstraint = function(step) {
var fixtureA = this.m_fixtureA;
var fixtureB = this.m_fixtureB;
var shapeA = fixtureA.getShape();
var shapeB = fixtureB.getShape();
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
var manifold = this.getManifold();
var pointCount = manifold.pointCount;
ASSERT && common.assert(pointCount > 0);
this.v_invMassA = bodyA.m_invMass;
this.v_invMassB = bodyB.m_invMass;
this.v_invIA = bodyA.m_invI;
this.v_invIB = bodyB.m_invI;
this.v_friction = this.m_friction;
this.v_restitution = this.m_restitution;
this.v_tangentSpeed = this.m_tangentSpeed;
this.v_pointCount = pointCount;
DEBUG && common.debug("pc", this.v_pointCount, pointCount);
this.v_K.setZero();
this.v_normalMass.setZero();
this.p_invMassA = bodyA.m_invMass;
this.p_invMassB = bodyB.m_invMass;
this.p_invIA = bodyA.m_invI;
this.p_invIB = bodyB.m_invI;
this.p_localCenterA = Vec2.clone(bodyA.m_sweep.localCenter);
this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter);
this.p_radiusA = shapeA.m_radius;
this.p_radiusB = shapeB.m_radius;
this.p_type = manifold.type;
this.p_localNormal = Vec2.clone(manifold.localNormal);
this.p_localPoint = Vec2.clone(manifold.localPoint);
this.p_pointCount = pointCount;
for (var j = 0; j < pointCount; ++j) {
var cp = manifold.points[j];
var vcp = this.v_points[j] = new VelocityConstraintPoint();
if (step.warmStarting) {
vcp.normalImpulse = step.dtRatio * cp.normalImpulse;
vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse;
} else {
vcp.normalImpulse = 0;
vcp.tangentImpulse = 0;
}
vcp.rA.setZero();
vcp.rB.setZero();
vcp.normalMass = 0;
vcp.tangentMass = 0;
vcp.velocityBias = 0;
this.p_localPoints[j] = Vec2.clone(cp.localPoint);
}
};
Contact.prototype.getManifold = function() {
return this.m_manifold;
};
Contact.prototype.getWorldManifold = function(worldManifold) {
var bodyA = this.m_fixtureA.getBody();
var bodyB = this.m_fixtureB.getBody();
var shapeA = this.m_fixtureA.getShape();
var shapeB = this.m_fixtureB.getShape();
return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius);
};
Contact.prototype.setEnabled = function(flag) {
this.m_enabledFlag = !!flag;
};
Contact.prototype.isEnabled = function() {
return this.m_enabledFlag;
};
Contact.prototype.isTouching = function() {
return this.m_touchingFlag;
};
Contact.prototype.getNext = function() {
return this.m_next;
};
Contact.prototype.getFixtureA = function() {
return this.m_fixtureA;
};
Contact.prototype.getFixtureB = function() {
return this.m_fixtureB;
};
Contact.prototype.getChildIndexA = function() {
return this.m_indexA;
};
Contact.prototype.getChildIndexB = function() {
return this.m_indexB;
};
Contact.prototype.flagForFiltering = function() {
this.m_filterFlag = true;
};
Contact.prototype.setFriction = function(friction) {
this.m_friction = friction;
};
Contact.prototype.getFriction = function() {
return this.m_friction;
};
Contact.prototype.resetFriction = function() {
this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction);
};
Contact.prototype.setRestitution = function(restitution) {
this.m_restitution = restitution;
};
Contact.prototype.getRestitution = function() {
return this.m_restitution;
};
Contact.prototype.resetRestitution = function() {
this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution);
};
Contact.prototype.setTangentSpeed = function(speed) {
this.m_tangentSpeed = speed;
};
Contact.prototype.getTangentSpeed = function() {
return this.m_tangentSpeed;
};
Contact.prototype.evaluate = function(manifold, xfA, xfB) {
this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB);
};
Contact.prototype.update = function(listener) {
this.m_enabledFlag = true;
var touching = false;
var wasTouching = this.m_touchingFlag;
var sensorA = this.m_fixtureA.isSensor();
var sensorB = this.m_fixtureB.isSensor();
var sensor = sensorA || sensorB;
var bodyA = this.m_fixtureA.getBody();
var bodyB = this.m_fixtureB.getBody();
var xfA = bodyA.getTransform();
var xfB = bodyB.getTransform();
if (sensor) {
var shapeA = this.m_fixtureA.getShape();
var shapeB = this.m_fixtureB.getShape();
touching = Distance.testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB);
this.m_manifold.pointCount = 0;
} else {
var oldManifold = this.m_manifold;
this.m_manifold = new Manifold();
this.evaluate(this.m_manifold, xfA, xfB);
touching = this.m_manifold.pointCount > 0;
for (var i = 0; i < this.m_manifold.pointCount; ++i) {
var nmp = this.m_manifold.points[i];
nmp.normalImpulse = 0;
nmp.tangentImpulse = 0;
for (var j = 0; j < oldManifold.pointCount; ++j) {
var omp = oldManifold.points[j];
if (omp.id.key == nmp.id.key) {
nmp.normalImpulse = omp.normalImpulse;
nmp.tangentImpulse = omp.tangentImpulse;
break;
}
}
}
if (touching != wasTouching) {
bodyA.setAwake(true);
bodyB.setAwake(true);
}
}
this.m_touchingFlag = touching;
if (wasTouching == false && touching == true && listener) {
listener.beginContact(this);
}
if (wasTouching == true && touching == false && listener) {
listener.endContact(this);
}
if (sensor == false && touching && listener) {
listener.preSolve(this, oldManifold);
}
};
Contact.prototype.solvePositionConstraint = function(step) {
return this._solvePositionConstraint(step, false);
};
Contact.prototype.solvePositionConstraintTOI = function(step, toiA, toiB) {
return this._solvePositionConstraint(step, true, toiA, toiB);
};
Contact.prototype._solvePositionConstraint = function(step, toi, toiA, toiB) {
var fixtureA = this.m_fixtureA;
var fixtureB = this.m_fixtureB;
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
var velocityA = bodyA.c_velocity;
var velocityB = bodyB.c_velocity;
var positionA = bodyA.c_position;
var positionB = bodyB.c_position;
var localCenterA = Vec2.clone(this.p_localCenterA);
var localCenterB = Vec2.clone(this.p_localCenterB);
var mA = 0;
var iA = 0;
if (!toi || (bodyA == toiA || bodyA == toiB)) {
mA = this.p_invMassA;
iA = this.p_invIA;
}
var mB = 0;
var iB = 0;
if (!toi || (bodyB == toiA || bodyB == toiB)) {
mB = this.p_invMassB;
iB = this.p_invIB;
}
var cA = Vec2.clone(positionA.c);
var aA = positionA.a;
var cB = Vec2.clone(positionB.c);
var aB = positionB.a;
var minSeparation = 0;
for (var j = 0; j < this.p_pointCount; ++j) {
var xfA = Transform.identity();
var xfB = Transform.identity();
xfA.q.set(aA);
xfB.q.set(aB);
xfA.p = Vec2.sub(cA, Rot.mul(xfA.q, localCenterA));
xfB.p = Vec2.sub(cB, Rot.mul(xfB.q, localCenterB));
var normal, point, separation;
switch (this.p_type) {
case Manifold.e_circles:
var pointA = Transform.mul(xfA, this.p_localPoint);
var pointB = Transform.mul(xfB, this.p_localPoints[0]);
normal = Vec2.sub(pointB, pointA);
normal.normalize();
point = Vec2.wAdd(.5, pointA, .5, pointB);
separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB;
break;
case Manifold.e_faceA:
normal = Rot.mul(xfA.q, this.p_localNormal);
var planePoint = Transform.mul(xfA, this.p_localPoint);
var clipPoint = Transform.mul(xfB, this.p_localPoints[j]);
separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB;
point = clipPoint;
break;
case Manifold.e_faceB:
normal = Rot.mul(xfB.q, this.p_localNormal);
var planePoint = Transform.mul(xfB, this.p_localPoint);
var clipPoint = Transform.mul(xfA, this.p_localPoints[j]);
separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB;
point = clipPoint;
normal.mul(-1);
break;
}
var rA = Vec2.sub(point, cA);
var rB = Vec2.sub(point, cB);
minSeparation = Math.min(minSeparation, separation);
var baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte;
var linearSlop = Settings.linearSlop;
var maxLinearCorrection = Settings.maxLinearCorrection;
var C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0);
var rnA = Vec2.cross(rA, normal);
var rnB = Vec2.cross(rB, normal);
var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
var impulse = K > 0 ? -C / K : 0;
var P = Vec2.mul(impulse, normal);
cA.wSub(mA, P);
aA -= iA * Vec2.cross(rA, P);
cB.wAdd(mB, P);
aB += iB * Vec2.cross(rB, P);
}
positionA.c.set(cA);
positionA.a = aA;
positionB.c.set(cB);
positionB.a = aB;
return minSeparation;
};
function VelocityConstraintPoint() {
this.rA = Vec2.zero();
this.rB = Vec2.zero();
this.normalImpulse = 0;
this.tangentImpulse = 0;
this.normalMass = 0;
this.tangentMass = 0;
this.velocityBias = 0;
}
Contact.prototype.initVelocityConstraint = function(step) {
var fixtureA = this.m_fixtureA;
var fixtureB = this.m_fixtureB;
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
var velocityA = bodyA.c_velocity;
var velocityB = bodyB.c_velocity;
var positionA = bodyA.c_position;
var positionB = bodyB.c_position;
var radiusA = this.p_radiusA;
var radiusB = this.p_radiusB;
var manifold = this.getManifold();
var mA = this.v_invMassA;
var mB = this.v_invMassB;
var iA = this.v_invIA;
var iB = this.v_invIB;
var localCenterA = Vec2.clone(this.p_localCenterA);
var localCenterB = Vec2.clone(this.p_localCenterB);
var cA = Vec2.clone(positionA.c);
var aA = positionA.a;
var vA = Vec2.clone(velocityA.v);
var wA = velocityA.w;
var cB = Vec2.clone(positionB.c);
var aB = positionB.a;
var vB = Vec2.clone(velocityB.v);
var wB = velocityB.w;
ASSERT && common.assert(manifold.pointCount > 0);
var xfA = Transform.identity();
var xfB = Transform.identity();
xfA.q.set(aA);
xfB.q.set(aB);
xfA.p.wSet(1, cA, -1, Rot.mul(xfA.q, localCenterA));
xfB.p.wSet(1, cB, -1, Rot.mul(xfB.q, localCenterB));
var worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB);
this.v_normal.set(worldManifold.normal);
for (var j = 0; j < this.v_pointCount; ++j) {
var vcp = this.v_points[j];
vcp.rA.set(Vec2.sub(worldManifold.points[j], cA));
vcp.rB.set(Vec2.sub(worldManifold.points[j], cB));
DEBUG && common.debug("vcp.rA", worldManifold.points[j].x, worldManifold.points[j].y, cA.x, cA.y, vcp.rA.x, vcp.rA.y);
var rnA = Vec2.cross(vcp.rA, this.v_normal);
var rnB = Vec2.cross(vcp.rB, this.v_normal);
var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0;
var tangent = Vec2.cross(this.v_normal, 1);
var rtA = Vec2.cross(vcp.rA, tangent);
var rtB = Vec2.cross(vcp.rB, tangent);
var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0;
vcp.velocityBias = 0;
var vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA));
if (vRel < -Settings.velocityThreshold) {
vcp.velocityBias = -this.v_restitution * vRel;
}
}
if (this.v_pointCount == 2 && step.blockSolve) {
var vcp1 = this.v_points[0];
var vcp2 = this.v_points[1];
var rn1A = Vec2.cross(vcp1.rA, this.v_normal);
var rn1B = Vec2.cross(vcp1.rB, this.v_normal);
var rn2A = Vec2.cross(vcp2.rA, this.v_normal);
var rn2B = Vec2.cross(vcp2.rB, this.v_normal);
var k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
var k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
var k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
var k_maxConditionNumber = 1e3;
DEBUG && common.debug("k1x2: ", k11, k22, k12, mA, mB, iA, rn1A, rn2A, iB, rn1B, rn2B);
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) {
this.v_K.ex.set(k11, k12);
this.v_K.ey.set(k12, k22);
this.v_normalMass.set(this.v_K.getInverse());
} else {
this.v_pointCount = 1;
}
}
positionA.c.set(cA);
positionA.a = aA;
velocityA.v.set(vA);
velocityA.w = wA;
positionB.c.set(cB);
positionB.a = aB;
velocityB.v.set(vB);
velocityB.w = wB;
};
Contact.prototype.warmStartConstraint = function(step) {
var fixtureA = this.m_fixtureA;
var fixtureB = this.m_fixtureB;
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
var velocityA = bodyA.c_velocity;
var velocityB = bodyB.c_velocity;
var positionA = bodyA.c_position;
var positionB = bodyB.c_position;
var mA = this.v_invMassA;
var iA = this.v_invIA;
var mB = this.v_invMassB;
var iB = this.v_invIB;
var vA = Vec2.clone(velocityA.v);
var wA = velocityA.w;
var vB = Vec2.clone(velocityB.v);
var wB = velocityB.w;
var normal = this.v_normal;
var tangent = Vec2.cross(normal, 1);
for (var j = 0; j < this.v_pointCount; ++j) {
var vcp = this.v_points[j];
var P = Vec2.wAdd(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent);
DEBUG && common.debug(iA, iB, vcp.rA.x, vcp.rA.y, vcp.rB.x, vcp.rB.y, P.x, P.y);
wA -= iA * Vec2.cross(vcp.rA, P);
vA.wSub(mA, P);
wB += iB * Vec2.cross(vcp.rB, P);
vB.wAdd(mB, P);
}
velocityA.v.set(vA);
velocityA.w = wA;
velocityB.v.set(vB);
velocityB.w = wB;
};
Contact.prototype.storeConstraintImpulses = function(step) {
var manifold = this.m_manifold;
for (var j = 0; j < this.v_pointCount; ++j) {
manifold.points[j].normalImpulse = this.v_points[j].normalImpulse;
manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse;
}
};
Contact.prototype.solveVelocityConstraint = function(step) {
var bodyA = this.m_fixtureA.m_body;
var bodyB = this.m_fixtureB.m_body;
var velocityA = bodyA.c_velocity;
var positionA = bodyA.c_position;
var velocityB = bodyB.c_velocity;
var positionB = bodyB.c_position;
var mA = this.v_invMassA;
var iA = this.v_invIA;
var mB = this.v_invMassB;
var iB = this.v_invIB;
var vA = Vec2.clone(velocityA.v);
var wA = velocityA.w;
var vB = Vec2.clone(velocityB.v);
var wB = velocityB.w;
var normal = this.v_normal;
var tangent = Vec2.cross(normal, 1);
var friction = this.v_friction;
ASSERT && common.assert(this.v_pointCount == 1 || this.v_pointCount == 2);
for (var j = 0; j < this.v_pointCount; ++j) {
var vcp = this.v_points[j];
var dv = Vec2.zero();
dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB));
dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA));
var vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed;
var lambda = vcp.tangentMass * -vt;
var maxFriction = friction * vcp.normalImpulse;
var newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction);
lambda = newImpulse - vcp.tangentImpulse;
vcp.tangentImpulse = newImpulse;
var P = Vec2.mul(lambda, tangent);
vA.wSub(mA, P);
wA -= iA * Vec2.cross(vcp.rA, P);
vB.wAdd(mB, P);
wB += iB * Vec2.cross(vcp.rB, P);
}
if (this.v_pointCount == 1 || step.blockSolve == false) {
for (var i = 0; i < this.v_pointCount; ++i) {
var vcp = this.v_points[i];
var dv = Vec2.zero();
dv.wAdd(1, vB, 1, Vec2.cross(wB, vcp.rB));
dv.wSub(1, vA, 1, Vec2.cross(wA, vcp.rA));
var vn = Vec2.dot(dv, normal);
var lambda = -vcp.normalMass * (vn - vcp.velocityBias);
var newImpulse = Math.max(vcp.normalImpulse + lambda, 0);
lambda = newImpulse - vcp.normalImpulse;
vcp.normalImpulse = newImpulse;
var P = Vec2.mul(lambda, normal);
vA.wSub(mA, P);
wA -= iA * Vec2.cross(vcp.rA, P);
vB.wAdd(mB, P);
wB += iB * Vec2.cross(vcp.rB, P);
}
} else {
var vcp1 = this.v_points[0];
var vcp2 = this.v_points[1];
var a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse);
ASSERT && common.assert(a.x >= 0 && a.y >= 0);
var dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA));
var dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA));
var vn1 = Vec2.dot(dv1, normal);
var vn2 = Vec2.dot(dv2, normal);
var b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias);
b.sub(Mat22.mul(this.v_K, a));
var k_errorTol = .001;
for (;;) {
var x = Vec2.neg(Mat22.mul(this.v_normalMass, b));
if (x.x >= 0 && x.y >= 0) {
var d = Vec2.sub(x, a);
var P1 = Vec2.mul(d.x, normal);
var P2 = Vec2.mul(d.y, normal);
vA.wSub(mA, P1, mA, P2);
wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2));
vB.wAdd(mB, P1, mB, P2);
wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2));
vcp1.normalImpulse = x.x;
vcp2.normalImpulse = x.y;
if (DEBUG_SOLVER) {
dv1 = vB + Vec2.cross(wB, vcp1.rB) - vA - Vec2.cross(wA, vcp1.rA);
dv2 = vB + Vec2.cross(wB, vcp2.rB) - vA - Vec2.cross(wA, vcp2.rA);
vn1 = Dot(dv1, normal);
vn2 = Dot(dv2, normal);
ASSERT && common.assert(Abs(vn1 - vcp1.velocityBias) < k_errorTol);
ASSERT && common.assert(Abs(vn2 - vcp2.velocityBias) < k_errorTol);
}
break;
}
x.x = -vcp1.normalMass * b.x;
x.y = 0;
vn1 = 0;
vn2 = this.v_K.ex.y * x.x + b.y;
if (x.x >= 0 && vn2 >= 0) {
var d = Vec2.sub(x, a);
var P1 = Vec2.mul(d.x, normal);
var P2 = Vec2.mul(d.y, normal);
vA.wSub(mA, P1, mA, P2);
wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2));
vB.wAdd(mB, P1, mB, P2);
wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2));
vcp1.normalImpulse = x.x;
vcp2.normalImpulse = x.y;
if (DEBUG_SOLVER) {
var dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB));
var dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA));
var dv1 = Vec2.sub(dv1B, dv1A);
vn1 = Vec2.dot(dv1, normal);
ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol);
}
break;
}
x.x = 0;
x.y = -vcp2.normalMass * b.y;
vn1 = this.v_K.ey.x * x.y + b.x;
vn2 = 0;
if (x.y >= 0 && vn1 >= 0) {
var d = Vec2.sub(x, a);
var P1 = Vec2.mul(d.x, normal);
var P2 = Vec2.mul(d.y, normal);
vA.wSub(mA, P1, mA, P2);
wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2));
vB.wAdd(mB, P1, mB, P2);
wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2));
vcp1.normalImpulse = x.x;
vcp2.normalImpulse = x.y;
if (DEBUG_SOLVER) {
var dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB));
var dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA));
var dv1 = Vec2.sub(dv2B, dv2A);
vn2 = Vec2.dot(dv2, normal);
ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol);
}
break;
}
x.x = 0;
x.y = 0;
vn1 = b.x;
vn2 = b.y;
if (vn1 >= 0 && vn2 >= 0) {
var d = Vec2.sub(x, a);
var P1 = Vec2.mul(d.x, normal);
var P2 = Vec2.mul(d.y, normal);
vA.wSub(mA, P1, mA, P2);
wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2));
vB.wAdd(mB, P1, mB, P2);
wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2));
vcp1.normalImpulse = x.x;
vcp2.normalImpulse = x.y;
break;
}
break;
}
}
velocityA.v.set(vA);
velocityA.w = wA;
velocityB.v.set(vB);
velocityB.w = wB;
};
function mixFriction(friction1, friction2) {
return Math.sqrt(friction1 * friction2);
}
function mixRestitution(restitution1, restitution2) {
return restitution1 > restitution2 ? restitution1 : restitution2;
}
var s_registers = [];
Contact.addType = function(type1, type2, callback) {
s_registers[type1] = s_registers[type1] || {};
s_registers[type1][type2] = callback;
};
Contact.create = function(fixtureA, indexA, fixtureB, indexB) {
var typeA = fixtureA.getType();
var typeB = fixtureB.getType();
var contact, evaluateFcn;
if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) {
contact = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn);
} else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) {
contact = new Contact(fixtureB, indexB, fixtureA, indexA, evaluateFcn);
} else {
return null;
}
fixtureA = contact.getFixtureA();
fixtureB = contact.getFixtureB();
indexA = contact.getChildIndexA();
indexB = contact.getChildIndexB();
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
contact.m_nodeA.contact = contact;
contact.m_nodeA.other = bodyB;
contact.m_nodeA.prev = null;
contact.m_nodeA.next = bodyA.m_contactList;
if (bodyA.m_contactList != null) {
bodyA.m_contactList.prev = contact.m_nodeA;
}
bodyA.m_contactList = contact.m_nodeA;
contact.m_nodeB.contact = contact;
contact.m_nodeB.other = bodyA;
contact.m_nodeB.prev = null;
contact.m_nodeB.next = bodyB.m_contactList;
if (bodyB.m_contactList != null) {
bodyB.m_contactList.prev = contact.m_nodeB;
}
bodyB.m_contactList = contact.m_nodeB;
if (fixtureA.isSensor() == false && fixtureB.isSensor() == false) {
bodyA.setAwake(true);
bodyB.setAwake(true);
}
return contact;
};
Contact.destroy = function(contact, listener) {
var fixtureA = contact.m_fixtureA;
var fixtureB = contact.m_fixtureB;
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
if (contact.isTouching()) {
listener.endContact(contact);
}
if (contact.m_nodeA.prev) {
contact.m_nodeA.prev.next = contact.m_nodeA.next;
}
if (contact.m_nodeA.next) {
contact.m_nodeA.next.prev = contact.m_nodeA.prev;
}
if (contact.m_nodeA == bodyA.m_contactList) {
bodyA.m_contactList = contact.m_nodeA.next;
}
if (contact.m_nodeB.prev) {
contact.m_nodeB.prev.next = contact.m_nodeB.next;
}
if (contact.m_nodeB.next) {
contact.m_nodeB.next.prev = contact.m_nodeB.prev;
}
if (contact.m_nodeB == bodyB.m_contactList) {
bodyB.m_contactList = contact.m_nodeB.next;
}
if (contact.m_manifold.pointCount > 0 && fixtureA.isSensor() == false && fixtureB.isSensor() == false) {
bodyA.setAwake(true);
bodyB.setAwake(true);
}
var typeA = fixtureA.getType();
var typeB = fixtureB.getType();
var destroyFcn = s_registers[typeA][typeB].destroyFcn;
if (typeof destroyFcn === "function") {
destroyFcn(contact);
}
};
},{"./Manifold":6,"./Settings":7,"./collision/Distance":13,"./common/Mat22":16,"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],4:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Fixture;
var common = require("./util/common");
var options = require("./util/options");
var Vec2 = require("./common/Vec2");
var AABB = require("./collision/AABB");
var FixtureDef = {
userData: null,
friction: .2,
restitution: 0,
density: 0,
isSensor: false,
filterGroupIndex: 0,
filterCategoryBits: 1,
filterMaskBits: 65535
};
function FixtureProxy(fixture, childIndex) {
this.aabb = new AABB();
this.fixture = fixture;
this.childIndex = childIndex;
this.proxyId;
}
function Fixture(body, shape, def) {
if (shape.shape) {
def = shape;
shape = shape.shape;
} else if (typeof def === "number") {
def = {
density: def
};
}
def = options(def, FixtureDef);
this.m_body = body;
this.m_friction = def.friction;
this.m_restitution = def.restitution;
this.m_density = def.density;
this.m_isSensor = def.isSensor;
this.m_filterGroupIndex = def.filterGroupIndex;
this.m_filterCategoryBits = def.filterCategoryBits;
this.m_filterMaskBits = def.filterMaskBits;
this.m_shape = shape;
this.m_next = null;
this.m_proxies = [];
this.m_proxyCount = 0;
var childCount = this.m_shape.getChildCount();
for (var i = 0; i < childCount; ++i) {
this.m_proxies[i] = new FixtureProxy(this, i);
}
this.m_userData = def.userData;
}
Fixture.prototype.getType = function() {
return this.m_shape.getType();
};
Fixture.prototype.getShape = function() {
return this.m_shape;
};
Fixture.prototype.isSensor = function() {
return this.m_isSensor;
};
Fixture.prototype.setSensor = function(sensor) {
if (sensor != this.m_isSensor) {
this.m_body.setAwake(true);
this.m_isSensor = sensor;
}
};
Fixture.prototype.getUserData = function() {
return this.m_userData;
};
Fixture.prototype.setUserData = function(data) {
this.m_userData = data;
};
Fixture.prototype.getBody = function() {
return this.m_body;
};
Fixture.prototype.getNext = function() {
return this.m_next;
};
Fixture.prototype.getDensity = function() {
return this.m_density;
};
Fixture.prototype.setDensity = function(density) {
ASSERT && common.assert(Math.isFinite(density) && density >= 0);
this.m_density = density;
};
Fixture.prototype.getFriction = function() {
return this.m_friction;
};
Fixture.prototype.setFriction = function(friction) {
this.m_friction = friction;
};
Fixture.prototype.getRestitution = function() {
return this.m_restitution;
};
Fixture.prototype.setRestitution = function(restitution) {
this.m_restitution = restitution;
};
Fixture.prototype.testPoint = function(p) {
return this.m_shape.testPoint(this.m_body.getTransform(), p);
};
Fixture.prototype.rayCast = function(output, input, childIndex) {
return this.m_shape.rayCast(output, input, this.m_body.getTransform(), childIndex);
};
Fixture.prototype.getMassData = function(massData) {
this.m_shape.computeMass(massData, this.m_density);
};
Fixture.prototype.getAABB = function(childIndex) {
ASSERT && common.assert(0 <= childIndex && childIndex < this.m_proxyCount);
return this.m_proxies[childIndex].aabb;
};
Fixture.prototype.createProxies = function(broadPhase, xf) {
ASSERT && common.assert(this.m_proxyCount == 0);
this.m_proxyCount = this.m_shape.getChildCount();
for (var i = 0; i < this.m_proxyCount; ++i) {
var proxy = this.m_proxies[i];
this.m_shape.computeAABB(proxy.aabb, xf, i);
proxy.proxyId = broadPhase.createProxy(proxy.aabb, proxy);
}
};
Fixture.prototype.destroyProxies = function(broadPhase) {
for (var i = 0; i < this.m_proxyCount; ++i) {
var proxy = this.m_proxies[i];
broadPhase.destroyProxy(proxy.proxyId);
proxy.proxyId = null;
}
this.m_proxyCount = 0;
};
Fixture.prototype.synchronize = function(broadPhase, xf1, xf2) {
for (var i = 0; i < this.m_proxyCount; ++i) {
var proxy = this.m_proxies[i];
var aabb1 = new AABB();
var aabb2 = new AABB();
this.m_shape.computeAABB(aabb1, xf1, proxy.childIndex);
this.m_shape.computeAABB(aabb2, xf2, proxy.childIndex);
proxy.aabb.combine(aabb1, aabb2);
var displacement = Vec2.sub(xf2.p, xf1.p);
broadPhase.moveProxy(proxy.proxyId, proxy.aabb, displacement);
}
};
Fixture.prototype.setFilterData = function(filter) {
this.m_filterGroupIndex = filter.groupIndex;
this.m_filterCategoryBits = filter.categoryBits;
this.m_filterMaskBits = filter.maskBits;
this.refilter();
};
Fixture.prototype.getFilterGroupIndex = function() {
return this.m_filterGroupIndex;
};
Fixture.prototype.getFilterCategoryBits = function() {
return this.m_filterCategoryBits;
};
Fixture.prototype.getFilterMaskBits = function() {
return this.m_filterMaskBits;
};
Fixture.prototype.refilter = function() {
if (this.m_body == null) {
return;
}
var edge = this.m_body.getContactList();
while (edge) {
var contact = edge.contact;
var fixtureA = contact.getFixtureA();
var fixtureB = contact.getFixtureB();
if (fixtureA == this || fixtureB == this) {
contact.flagForFiltering();
}
edge = edge.next;
}
var world = this.m_body.getWorld();
if (world == null) {
return;
}
var broadPhase = world.m_broadPhase;
for (var i = 0; i < this.m_proxyCount; ++i) {
broadPhase.touchProxy(this.m_proxies[i].proxyId);
}
};
Fixture.prototype.shouldCollide = function(that) {
if (that.m_filterGroupIndex == this.m_filterGroupIndex && that.m_filterGroupIndex != 0) {
return that.m_filterGroupIndex > 0;
}
var collide = (that.m_filterMaskBits & this.m_filterCategoryBits) != 0 && (that.m_filterCategoryBits & this.m_filterMaskBits) != 0;
return collide;
};
},{"./collision/AABB":11,"./common/Vec2":23,"./util/common":51,"./util/options":53}],5:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Joint;
var common = require("./util/common");
function JointEdge() {
this.other = null;
this.joint = null;
this.prev = null;
this.next = null;
}
var JointDef = {
userData: null,
collideConnected: false
};
function Joint(def, bodyA, bodyB) {
bodyA = def.bodyA || bodyA;
bodyB = def.bodyB || bodyB;
ASSERT && common.assert(bodyA);
ASSERT && common.assert(bodyB);
ASSERT && common.assert(bodyA != bodyB);
this.m_type = "unknown-joint";
this.m_bodyA = bodyA;
this.m_bodyB = bodyB;
this.m_index = 0;
this.m_collideConnected = !!def.collideConnected;
this.m_prev = null;
this.m_next = null;
this.m_edgeA = new JointEdge();
this.m_edgeB = new JointEdge();
this.m_islandFlag = false;
this.m_userData = def.userData;
}
Joint.prototype.isActive = function() {
return this.m_bodyA.isActive() && this.m_bodyB.isActive();
};
Joint.prototype.getType = function() {
return this.m_type;
};
Joint.prototype.getBodyA = function() {
return this.m_bodyA;
};
Joint.prototype.getBodyB = function() {
return this.m_bodyB;
};
Joint.prototype.getNext = function() {
return this.m_next;
};
Joint.prototype.getUserData = function() {
return this.m_userData;
};
Joint.prototype.setUserData = function(data) {
this.m_userData = data;
};
Joint.prototype.getCollideConnected = function() {
return this.m_collideConnected;
};
Joint.prototype.getAnchorA = function() {};
Joint.prototype.getAnchorB = function() {};
Joint.prototype.getReactionForce = function(inv_dt) {};
Joint.prototype.getReactionTorque = function(inv_dt) {};
Joint.prototype.shiftOrigin = function(newOrigin) {};
Joint.prototype.initVelocityConstraints = function(step) {};
Joint.prototype.solveVelocityConstraints = function(step) {};
Joint.prototype.solvePositionConstraints = function(step) {};
},{"./util/common":51}],6:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("./util/common");
var Vec2 = require("./common/Vec2");
var Transform = require("./common/Transform");
var Math = require("./common/Math");
var Rot = require("./common/Rot");
module.exports = Manifold;
module.exports.clipSegmentToLine = clipSegmentToLine;
module.exports.clipVertex = ClipVertex;
module.exports.getPointStates = getPointStates;
module.exports.PointState = PointState;
Manifold.e_circles = 0;
Manifold.e_faceA = 1;
Manifold.e_faceB = 2;
Manifold.e_vertex = 0;
Manifold.e_face = 1;
function Manifold() {
this.type;
this.localNormal = Vec2.zero();
this.localPoint = Vec2.zero();
this.points = [ new ManifoldPoint(), new ManifoldPoint() ];
this.pointCount = 0;
}
function ManifoldPoint() {
this.localPoint = Vec2.zero();
this.normalImpulse = 0;
this.tangentImpulse = 0;
this.id = new ContactID();
}
function ContactID() {
this.cf = new ContactFeature();
this.key;
}
ContactID.prototype.set = function(o) {
this.key = o.key;
this.cf.set(o.cf);
};
function ContactFeature() {
this.indexA;
this.indexB;
this.typeA;
this.typeB;
}
ContactFeature.prototype.set = function(o) {
this.indexA = o.indexA;
this.indexB = o.indexB;
this.typeA = o.typeA;
this.typeB = o.typeB;
};
function WorldManifold() {
this.normal;
this.points = [];
this.separations = [];
}
Manifold.prototype.getWorldManifold = function(wm, xfA, radiusA, xfB, radiusB) {
if (this.pointCount == 0) {
return;
}
wm = wm || new WorldManifold();
var normal = wm.normal;
var points = wm.points;
var separations = wm.separations;
switch (this.type) {
case Manifold.e_circles:
normal = Vec2.neo(1, 0);
var pointA = Transform.mul(xfA, this.localPoint);
var pointB = Transform.mul(xfB, this.points[0].localPoint);
var dist = Vec2.sub(pointB, pointA);
if (Vec2.lengthSquared(dist) > Math.EPSILON * Math.EPSILON) {
normal.set(dist);
normal.normalize();
}
points[0] = Vec2.mid(pointA, pointB);
separations[0] = -radiusB - radiusA;
points.length = 1;
separations.length = 1;
break;
case Manifold.e_faceA:
normal = Rot.mul(xfA.q, this.localNormal);
var planePoint = Transform.mul(xfA, this.localPoint);
DEBUG && common.debug("faceA", this.localPoint.x, this.localPoint.y, this.localNormal.x, this.localNormal.y, normal.x, normal.y);
for (var i = 0; i < this.pointCount; ++i) {
var clipPoint = Transform.mul(xfB, this.points[i].localPoint);
var cA = Vec2.clone(clipPoint).wAdd(radiusA - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal);
var cB = Vec2.clone(clipPoint).wSub(radiusB, normal);
points[i] = Vec2.mid(cA, cB);
separations[i] = Vec2.dot(Vec2.sub(cB, cA), normal);
DEBUG && common.debug(i, this.points[i].localPoint.x, this.points[i].localPoint.y, planePoint.x, planePoint.y, xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s, xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s, radiusA, radiusB, clipPoint.x, clipPoint.y, cA.x, cA.y, cB.x, cB.y, separations[i], points[i].x, points[i].y);
}
points.length = this.pointCount;
separations.length = this.pointCount;
break;
case Manifold.e_faceB:
normal = Rot.mul(xfB.q, this.localNormal);
var planePoint = Transform.mul(xfB, this.localPoint);
for (var i = 0; i < this.pointCount; ++i) {
var clipPoint = Transform.mul(xfA, this.points[i].localPoint);
var cB = Vec2.zero().wSet(1, clipPoint, radiusB - Vec2.dot(Vec2.sub(clipPoint, planePoint), normal), normal);
var cA = Vec2.zero().wSet(1, clipPoint, -radiusA, normal);
points[i] = Vec2.mid(cA, cB);
separations[i] = Vec2.dot(Vec2.sub(cA, cB), normal);
}
points.length = this.pointCount;
separations.length = this.pointCount;
normal.mul(-1);
break;
}
wm.normal = normal;
wm.points = points;
wm.separations = separations;
return wm;
};
var PointState = {
nullState: 0,
addState: 1,
persistState: 2,
removeState: 3
};
function getPointStates(state1, state2, manifold1, manifold2) {
for (var i = 0; i < manifold1.pointCount; ++i) {
var id = manifold1.points[i].id;
state1[i] = PointState.removeState;
for (var j = 0; j < manifold2.pointCount; ++j) {
if (manifold2.points[j].id.key == id.key) {
state1[i] = PointState.persistState;
break;
}
}
}
for (var i = 0; i < manifold2.pointCount; ++i) {
var id = manifold2.points[i].id;
state2[i] = PointState.addState;
for (var j = 0; j < manifold1.pointCount; ++j) {
if (manifold1.points[j].id.key == id.key) {
state2[i] = PointState.persistState;
break;
}
}
}
}
function ClipVertex() {
this.v = Vec2.zero();
this.id = new ContactID();
}
ClipVertex.prototype.set = function(o) {
this.v.set(o.v);
this.id.set(o.id);
};
function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) {
var numOut = 0;
var distance0 = Vec2.dot(normal, vIn[0].v) - offset;
var distance1 = Vec2.dot(normal, vIn[1].v) - offset;
if (distance0 <= 0) vOut[numOut++].set(vIn[0]);
if (distance1 <= 0) vOut[numOut++].set(vIn[1]);
if (distance0 * distance1 < 0) {
var interp = distance0 / (distance0 - distance1);
vOut[numOut].v.wSet(1 - interp, vIn[0].v, interp, vIn[1].v);
vOut[numOut].id.cf.indexA = vertexIndexA;
vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB;
vOut[numOut].id.cf.typeA = ContactFeature.e_vertex;
vOut[numOut].id.cf.typeB = ContactFeature.e_face;
++numOut;
}
return numOut;
}
},{"./common/Math":18,"./common/Rot":20,"./common/Transform":22,"./common/Vec2":23,"./util/common":51}],7:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var Settings = exports;
Settings.maxManifoldPoints = 2;
Settings.maxPolygonVertices = 12;
Settings.aabbExtension = .1;
Settings.aabbMultiplier = 2;
Settings.linearSlop = .005;
Settings.linearSlopSquared = Settings.linearSlop * Settings.linearSlop;
Settings.angularSlop = 2 / 180 * Math.PI;
Settings.polygonRadius = 2 * Settings.linearSlop;
Settings.maxSubSteps = 8;
Settings.maxTOIContacts = 32;
Settings.maxTOIIterations = 20;
Settings.maxDistnceIterations = 20;
Settings.velocityThreshold = 1;
Settings.maxLinearCorrection = .2;
Settings.maxAngularCorrection = 8 / 180 * Math.PI;
Settings.maxTranslation = 2;
Settings.maxTranslationSquared = Settings.maxTranslation * Settings.maxTranslation;
Settings.maxRotation = .5 * Math.PI;
Settings.maxRotationSquared = Settings.maxRotation * Settings.maxRotation;
Settings.baumgarte = .2;
Settings.toiBaugarte = .75;
Settings.timeToSleep = .5;
Settings.linearSleepTolerance = .01;
Settings.linearSleepToleranceSqr = Math.pow(Settings.linearSleepTolerance, 2);
Settings.angularSleepTolerance = 2 / 180 * Math.PI;
Settings.angularSleepToleranceSqr = Math.pow(Settings.angularSleepTolerance, 2);
},{}],8:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Shape;
var Math = require("./common/Math");
function Shape() {
this.m_type;
this.m_radius;
}
Shape.isValid = function(shape) {
return !!shape;
};
Shape.prototype.getRadius = function() {
return this.m_radius;
};
Shape.prototype.getType = function() {
return this.m_type;
};
Shape.prototype._clone = function() {};
Shape.prototype.getChildCount = function() {};
Shape.prototype.testPoint = function(xf, p) {};
Shape.prototype.rayCast = function(output, input, transform, childIndex) {};
Shape.prototype.computeAABB = function(aabb, xf, childIndex) {};
Shape.prototype.computeMass = function(massData, density) {};
Shape.prototype.computeDistanceProxy = function(proxy) {};
},{"./common/Math":18}],9:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Solver;
module.exports.TimeStep = TimeStep;
var Settings = require("./Settings");
var common = require("./util/common");
var Timer = require("./util/Timer");
var Vec2 = require("./common/Vec2");
var Math = require("./common/Math");
var Body = require("./Body");
var Contact = require("./Contact");
var Joint = require("./Joint");
var TimeOfImpact = require("./collision/TimeOfImpact");
var TOIInput = TimeOfImpact.Input;
var TOIOutput = TimeOfImpact.Output;
var Distance = require("./collision/Distance");
var DistanceInput = Distance.Input;
var DistanceOutput = Distance.Output;
var DistanceProxy = Distance.Proxy;
var SimplexCache = Distance.Cache;
function Profile() {
this.solveInit;
this.solveVelocity;
this.solvePosition;
}
function TimeStep(dt) {
this.dt = 0;
this.inv_dt = 0;
this.velocityIterations = 0;
this.positionIterations = 0;
this.warmStarting = false;
this.blockSolve = true;
this.inv_dt0 = 0;
this.dtRatio = 1;
}
TimeStep.prototype.reset = function(dt) {
if (this.dt > 0) {
this.inv_dt0 = this.inv_dt;
}
this.dt = dt;
this.inv_dt = dt == 0 ? 0 : 1 / dt;
this.dtRatio = dt * this.inv_dt0;
};
function Solver(world) {
this.m_world = world;
this.m_profile = new Profile();
this.m_stack = [];
this.m_bodies = [];
this.m_contacts = [];
this.m_joints = [];
}
Solver.prototype.clear = function() {
this.m_stack.length = 0;
this.m_bodies.length = 0;
this.m_contacts.length = 0;
this.m_joints.length = 0;
};
Solver.prototype.addBody = function(body) {
ASSERT && common.assert(body instanceof Body, "Not a Body!", body);
this.m_bodies.push(body);
};
Solver.prototype.addContact = function(contact) {
ASSERT && common.assert(contact instanceof Contact, "Not a Contact!", contact);
this.m_contacts.push(contact);
};
Solver.prototype.addJoint = function(joint) {
ASSERT && common.assert(joint instanceof Joint, "Not a Joint!", joint);
this.m_joints.push(joint);
};
Solver.prototype.solveWorld = function(step) {
var world = this.m_world;
var profile = this.m_profile;
profile.solveInit = 0;
profile.solveVelocity = 0;
profile.solvePosition = 0;
for (var b = world.m_bodyList; b; b = b.m_next) {
b.m_islandFlag = false;
}
for (var c = world.m_contactList; c; c = c.m_next) {
c.m_islandFlag = false;
}
for (var j = world.m_jointList; j; j = j.m_next) {
j.m_islandFlag = false;
}
var stack = this.m_stack;
var loop = -1;
for (var seed = world.m_bodyList; seed; seed = seed.m_next) {
loop++;
if (seed.m_islandFlag) {
continue;
}
if (seed.isAwake() == false || seed.isActive() == false) {
continue;
}
if (seed.isStatic()) {
continue;
}
this.clear();
stack.push(seed);
seed.m_islandFlag = true;
while (stack.length > 0) {
var b = stack.pop();
ASSERT && common.assert(b.isActive() == true);
this.addBody(b);
b.setAwake(true);
if (b.isStatic()) {
continue;
}
for (var ce = b.m_contactList; ce; ce = ce.next) {
var contact = ce.contact;
if (contact.m_islandFlag) {
continue;
}
if (contact.isEnabled() == false || contact.isTouching() == false) {
continue;
}
var sensorA = contact.m_fixtureA.m_isSensor;
var sensorB = contact.m_fixtureB.m_isSensor;
if (sensorA || sensorB) {
continue;
}
this.addContact(contact);
contact.m_islandFlag = true;
var other = ce.other;
if (other.m_islandFlag) {
continue;
}
stack.push(other);
other.m_islandFlag = true;
}
for (var je = b.m_jointList; je; je = je.next) {
if (je.joint.m_islandFlag == true) {
continue;
}
var other = je.other;
if (other.isActive() == false) {
continue;
}
this.addJoint(je.joint);
je.joint.m_islandFlag = true;
if (other.m_islandFlag) {
continue;
}
stack.push(other);
other.m_islandFlag = true;
}
}
this.solveIsland(step);
for (var i = 0; i < this.m_bodies.length; ++i) {
var b = this.m_bodies[i];
if (b.isStatic()) {
b.m_islandFlag = false;
}
}
}
};
Solver.prototype.solveIsland = function(step) {
var world = this.m_world;
var profile = this.m_profile;
var gravity = world.m_gravity;
var allowSleep = world.m_allowSleep;
var timer = Timer.now();
var h = step.dt;
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
var c = Vec2.clone(body.m_sweep.c);
var a = body.m_sweep.a;
var v = Vec2.clone(body.m_linearVelocity);
var w = body.m_angularVelocity;
body.m_sweep.c0.set(body.m_sweep.c);
body.m_sweep.a0 = body.m_sweep.a;
DEBUG && common.debug("P: ", a, c.x, c.y, w, v.x, v.y);
if (body.isDynamic()) {
v.wAdd(h * body.m_gravityScale, gravity);
v.wAdd(h * body.m_invMass, body.m_force);
w += h * body.m_invI * body.m_torque;
DEBUG && common.debug("N: " + h, body.m_gravityScale, gravity.x, gravity.y, body.m_invMass, body.m_force.x, body.m_force.y);
v.mul(1 / (1 + h * body.m_linearDamping));
w *= 1 / (1 + h * body.m_angularDamping);
}
common.debug("A: ", a, c.x, c.y, w, v.x, v.y);
body.c_position.c = c;
body.c_position.a = a;
body.c_velocity.v = v;
body.c_velocity.w = w;
}
timer = Timer.now();
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.initConstraint(step);
}
DEBUG && this.printBodies("M: ");
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.initVelocityConstraint(step);
}
DEBUG && this.printBodies("R: ");
if (step.warmStarting) {
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.warmStartConstraint(step);
}
}
DEBUG && this.printBodies("Q: ");
for (var i = 0; i < this.m_joints.length; ++i) {
var joint = this.m_joints[i];
joint.initVelocityConstraints(step);
}
DEBUG && this.printBodies("E: ");
profile.solveInit = Timer.diff(timer);
timer = Timer.now();
for (var i = 0; i < step.velocityIterations; ++i) {
DEBUG && common.debug("--", i);
for (var j = 0; j < this.m_joints.length; ++j) {
var joint = this.m_joints[j];
joint.solveVelocityConstraints(step);
}
for (var j = 0; j < this.m_contacts.length; ++j) {
var contact = this.m_contacts[j];
contact.solveVelocityConstraint(step);
}
}
DEBUG && this.printBodies("D: ");
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.storeConstraintImpulses(step);
}
profile.solveVelocity = Timer.diff(timer);
DEBUG && this.printBodies("C: ");
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
var c = Vec2.clone(body.c_position.c);
var a = body.c_position.a;
var v = Vec2.clone(body.c_velocity.v);
var w = body.c_velocity.w;
var translation = Vec2.mul(h, v);
if (Vec2.lengthSquared(translation) > Settings.maxTranslationSquared) {
var ratio = Settings.maxTranslation / translation.length();
v.mul(ratio);
}
var rotation = h * w;
if (rotation * rotation > Settings.maxRotationSquared) {
var ratio = Settings.maxRotation / Math.abs(rotation);
w *= ratio;
}
c.wAdd(h, v);
a += h * w;
body.c_position.c.set(c);
body.c_position.a = a;
body.c_velocity.v.set(v);
body.c_velocity.w = w;
}
DEBUG && this.printBodies("B: ");
timer = Timer.now();
var positionSolved = false;
for (var i = 0; i < step.positionIterations; ++i) {
var minSeparation = 0;
for (var j = 0; j < this.m_contacts.length; ++j) {
var contact = this.m_contacts[j];
var separation = contact.solvePositionConstraint(step);
minSeparation = Math.min(minSeparation, separation);
}
var contactsOkay = minSeparation >= -3 * Settings.linearSlop;
var jointsOkay = true;
for (var j = 0; j < this.m_joints.length; ++j) {
var joint = this.m_joints[j];
var jointOkay = joint.solvePositionConstraints(step);
jointsOkay = jointsOkay && jointOkay;
}
if (contactsOkay && jointsOkay) {
positionSolved = true;
break;
}
}
DEBUG && this.printBodies("L: ");
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
body.m_sweep.c.set(body.c_position.c);
body.m_sweep.a = body.c_position.a;
body.m_linearVelocity.set(body.c_velocity.v);
body.m_angularVelocity = body.c_velocity.w;
body.synchronizeTransform();
}
profile.solvePosition = Timer.diff(timer);
this.postSolveIsland();
if (allowSleep) {
var minSleepTime = Infinity;
var linTolSqr = Settings.linearSleepToleranceSqr;
var angTolSqr = Settings.angularSleepToleranceSqr;
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
if (body.isStatic()) {
continue;
}
if (body.m_autoSleepFlag == false || body.m_angularVelocity * body.m_angularVelocity > angTolSqr || Vec2.lengthSquared(body.m_linearVelocity) > linTolSqr) {
body.m_sleepTime = 0;
minSleepTime = 0;
} else {
body.m_sleepTime += h;
minSleepTime = Math.min(minSleepTime, body.m_sleepTime);
}
}
if (minSleepTime >= Settings.timeToSleep && positionSolved) {
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
body.setAwake(false);
}
}
}
};
Solver.prototype.printBodies = function(tag) {
for (var i = 0; i < this.m_bodies.length; ++i) {
var b = this.m_bodies[i];
common.debug(tag, b.c_position.a, b.c_position.c.x, b.c_position.c.y, b.c_velocity.w, b.c_velocity.v.x, b.c_velocity.v.y);
}
};
var s_subStep = new TimeStep();
Solver.prototype.solveWorldTOI = function(step) {
DEBUG && common.debug("TOI++++++World");
var world = this.m_world;
var profile = this.m_profile;
DEBUG && common.debug("Z:", world.m_stepComplete);
if (world.m_stepComplete) {
for (var b = world.m_bodyList; b; b = b.m_next) {
b.m_islandFlag = false;
b.m_sweep.alpha0 = 0;
DEBUG && common.debug("b.alpha0:", b.m_sweep.alpha0);
}
for (var c = world.m_contactList; c; c = c.m_next) {
c.m_toiFlag = false;
c.m_islandFlag = false;
c.m_toiCount = 0;
c.m_toi = 1;
}
}
if (DEBUG) for (var c = world.m_contactList; c; c = c.m_next) {
DEBUG && common.debug("X:", c.m_toiFlag);
}
for (;;) {
DEBUG && common.debug(";;");
var minContact = null;
var minAlpha = 1;
for (var c = world.m_contactList; c; c = c.m_next) {
DEBUG && common.debug("alpha0::", c.getFixtureA().getBody().m_sweep.alpha0, c.getFixtureB().getBody().m_sweep.alpha0);
if (c.isEnabled() == false) {
continue;
}
DEBUG && common.debug("toiCount:", c.m_toiCount, Settings.maxSubSteps);
if (c.m_toiCount > Settings.maxSubSteps) {
continue;
}
DEBUG && common.debug("toiFlag:", c.m_toiFlag);
var alpha = 1;
if (c.m_toiFlag) {
alpha = c.m_toi;
} else {
var fA = c.getFixtureA();
var fB = c.getFixtureB();
DEBUG && common.debug("sensor:", fA.isSensor(), fB.isSensor());
if (fA.isSensor() || fB.isSensor()) {
continue;
}
var bA = fA.getBody();
var bB = fB.getBody();
ASSERT && common.assert(bA.isDynamic() || bB.isDynamic());
var activeA = bA.isAwake() && !bA.isStatic();
var activeB = bB.isAwake() && !bB.isStatic();
DEBUG && common.debug("awakestatic:", bA.isAwake(), bA.isStatic());
DEBUG && common.debug("awakestatic:", bB.isAwake(), bB.isStatic());
DEBUG && common.debug("active:", activeA, activeB);
if (activeA == false && activeB == false) {
continue;
}
DEBUG && common.debug("alpha:", alpha, bA.m_sweep.alpha0, bB.m_sweep.alpha0);
var collideA = bA.isBullet() || !bA.isDynamic();
var collideB = bB.isBullet() || !bB.isDynamic();
DEBUG && common.debug("collide:", collideA, collideB);
if (collideA == false && collideB == false) {
continue;
}
var alpha0 = bA.m_sweep.alpha0;
if (bA.m_sweep.alpha0 < bB.m_sweep.alpha0) {
alpha0 = bB.m_sweep.alpha0;
bA.m_sweep.advance(alpha0);
} else if (bB.m_sweep.alpha0 < bA.m_sweep.alpha0) {
alpha0 = bA.m_sweep.alpha0;
bB.m_sweep.advance(alpha0);
}
DEBUG && common.debug("alpha0:", alpha0, bA.m_sweep.alpha0, bB.m_sweep.alpha0);
ASSERT && common.assert(alpha0 < 1);
var indexA = c.getChildIndexA();
var indexB = c.getChildIndexB();
var sweepA = bA.m_sweep;
var sweepB = bB.m_sweep;
DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0);
DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0);
var input = new TOIInput();
input.proxyA.set(fA.getShape(), indexA);
input.proxyB.set(fB.getShape(), indexB);
input.sweepA.set(bA.m_sweep);
input.sweepB.set(bB.m_sweep);
input.tMax = 1;
var output = new TOIOutput();
TimeOfImpact(output, input);
var beta = output.t;
DEBUG && common.debug("state:", output.state, TOIOutput.e_touching);
if (output.state == TOIOutput.e_touching) {
alpha = Math.min(alpha0 + (1 - alpha0) * beta, 1);
} else {
alpha = 1;
}
c.m_toi = alpha;
c.m_toiFlag = true;
}
DEBUG && common.debug("minAlpha:", minAlpha, alpha);
if (alpha < minAlpha) {
minContact = c;
minAlpha = alpha;
}
}
DEBUG && common.debug("minContact:", minContact == null, 1 - 10 * Math.EPSILON < minAlpha, minAlpha);
if (minContact == null || 1 - 10 * Math.EPSILON < minAlpha) {
world.m_stepComplete = true;
break;
}
var fA = minContact.getFixtureA();
var fB = minContact.getFixtureB();
var bA = fA.getBody();
var bB = fB.getBody();
var backup1 = bA.m_sweep.clone();
var backup2 = bB.m_sweep.clone();
bA.advance(minAlpha);
bB.advance(minAlpha);
minContact.update(world);
minContact.m_toiFlag = false;
++minContact.m_toiCount;
if (minContact.isEnabled() == false || minContact.isTouching() == false) {
minContact.setEnabled(false);
bA.m_sweep.set(backup1);
bB.m_sweep.set(backup2);
bA.synchronizeTransform();
bB.synchronizeTransform();
continue;
}
bA.setAwake(true);
bB.setAwake(true);
this.clear();
this.addBody(bA);
this.addBody(bB);
this.addContact(minContact);
bA.m_islandFlag = true;
bB.m_islandFlag = true;
minContact.m_islandFlag = true;
var bodies = [ bA, bB ];
for (var i = 0; i < bodies.length; ++i) {
var body = bodies[i];
if (body.isDynamic()) {
for (var ce = body.m_contactList; ce; ce = ce.next) {
var contact = ce.contact;
if (contact.m_islandFlag) {
continue;
}
var other = ce.other;
if (other.isDynamic() && !body.isBullet() && !other.isBullet()) {
continue;
}
var sensorA = contact.m_fixtureA.m_isSensor;
var sensorB = contact.m_fixtureB.m_isSensor;
if (sensorA || sensorB) {
continue;
}
var backup = other.m_sweep.clone();
if (other.m_islandFlag == false) {
other.advance(minAlpha);
}
contact.update(world);
if (contact.isEnabled() == false || contact.isTouching() == false) {
other.m_sweep.set(backup);
other.synchronizeTransform();
continue;
}
contact.m_islandFlag = true;
this.addContact(contact);
if (other.m_islandFlag) {
continue;
}
other.m_islandFlag = true;
if (!other.isStatic()) {
other.setAwake(true);
}
this.addBody(other);
}
}
}
s_subStep.reset((1 - minAlpha) * step.dt);
s_subStep.dtRatio = 1;
s_subStep.positionIterations = 20;
s_subStep.velocityIterations = step.velocityIterations;
s_subStep.warmStarting = false;
this.solveIslandTOI(s_subStep, bA, bB);
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
body.m_islandFlag = false;
if (!body.isDynamic()) {
continue;
}
body.synchronizeFixtures();
for (var ce = body.m_contactList; ce; ce = ce.next) {
ce.contact.m_toiFlag = false;
ce.contact.m_islandFlag = false;
}
}
world.findNewContacts();
if (world.m_subStepping) {
world.m_stepComplete = false;
break;
}
}
if (DEBUG) for (var b = world.m_bodyList; b; b = b.m_next) {
var c = b.m_sweep.c;
var a = b.m_sweep.a;
var v = b.m_linearVelocity;
var w = b.m_angularVelocity;
DEBUG && common.debug("== ", a, c.x, c.y, w, v.x, v.y);
}
};
Solver.prototype.solveIslandTOI = function(subStep, toiA, toiB) {
DEBUG && common.debug("TOI++++++Island");
var world = this.m_world;
var profile = this.m_profile;
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
body.c_position.c.set(body.m_sweep.c);
body.c_position.a = body.m_sweep.a;
body.c_velocity.v.set(body.m_linearVelocity);
body.c_velocity.w = body.m_angularVelocity;
}
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.initConstraint(subStep);
}
for (var i = 0; i < subStep.positionIterations; ++i) {
var minSeparation = 0;
for (var j = 0; j < this.m_contacts.length; ++j) {
var contact = this.m_contacts[j];
var separation = contact.solvePositionConstraintTOI(subStep, toiA, toiB);
minSeparation = Math.min(minSeparation, separation);
}
var contactsOkay = minSeparation >= -1.5 * Settings.linearSlop;
if (contactsOkay) {
break;
}
}
if (false) {
for (var i = 0; i < this.m_contacts.length; ++i) {
var c = this.m_contacts[i];
var fA = c.getFixtureA();
var fB = c.getFixtureB();
var bA = fA.getBody();
var bB = fB.getBody();
var indexA = c.getChildIndexA();
var indexB = c.getChildIndexB();
var input = new DistanceInput();
input.proxyA.set(fA.getShape(), indexA);
input.proxyB.set(fB.getShape(), indexB);
input.transformA = bA.getTransform();
input.transformB = bB.getTransform();
input.useRadii = false;
var output = new DistanceOutput();
var cache = new SimplexCache();
Distance(output, cache, input);
if (output.distance == 0 || cache.count == 3) {
cache.count += 0;
}
}
}
toiA.m_sweep.c0.set(toiA.c_position.c);
toiA.m_sweep.a0 = toiA.c_position.a;
toiB.m_sweep.c0.set(toiB.c_position.c);
toiB.m_sweep.a0 = toiB.c_position.a;
for (var i = 0; i < this.m_contacts.length; ++i) {
var contact = this.m_contacts[i];
contact.initVelocityConstraint(subStep);
}
for (var i = 0; i < subStep.velocityIterations; ++i) {
for (var j = 0; j < this.m_contacts.length; ++j) {
var contact = this.m_contacts[j];
contact.solveVelocityConstraint(subStep);
}
}
var h = subStep.dt;
for (var i = 0; i < this.m_bodies.length; ++i) {
var body = this.m_bodies[i];
var c = Vec2.clone(body.c_position.c);
var a = body.c_position.a;
var v = Vec2.clone(body.c_velocity.v);
var w = body.c_velocity.w;
var translation = Vec2.mul(h, v);
if (Vec2.dot(translation, translation) > Settings.maxTranslationSquared) {
var ratio = Settings.maxTranslation / translation.length();
v.mul(ratio);
}
var rotation = h * w;
if (rotation * rotation > Settings.maxRotationSquared) {
var ratio = Settings.maxRotation / Math.abs(rotation);
w *= ratio;
}
c.wAdd(h, v);
a += h * w;
body.c_position.c = c;
body.c_position.a = a;
body.c_velocity.v = v;
body.c_velocity.w = w;
body.m_sweep.c = c;
body.m_sweep.a = a;
body.m_linearVelocity = v;
body.m_angularVelocity = w;
body.synchronizeTransform();
}
this.postSolveIsland();
DEBUG && common.debug("TOI------Island");
};
function ContactImpulse() {
this.normalImpulses = [];
this.tangentImpulses = [];
}
Solver.prototype.postSolveIsland = function() {
var impulse = new ContactImpulse();
for (var c = 0; c < this.m_contacts.length; ++c) {
var contact = this.m_contacts[c];
for (var p = 0; p < contact.v_points.length; ++p) {
impulse.normalImpulses.push(contact.v_points[p].normalImpulse);
impulse.tangentImpulses.push(contact.v_points[p].tangentImpulse);
}
this.m_world.postSolve(contact, impulse);
}
};
},{"./Body":2,"./Contact":3,"./Joint":5,"./Settings":7,"./collision/Distance":13,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Vec2":23,"./util/Timer":50,"./util/common":51}],10:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = World;
var options = require("./util/options");
var common = require("./util/common");
var Timer = require("./util/Timer");
var Vec2 = require("./common/Vec2");
var BroadPhase = require("./collision/BroadPhase");
var Solver = require("./Solver");
var Body = require("./Body");
var Contact = require("./Contact");
var WorldDef = {
gravity: Vec2.zero(),
allowSleep: true,
warmStarting: true,
continuousPhysics: true,
subStepping: false,
blockSolve: true,
velocityIterations: 8,
positionIterations: 3
};
function World(def) {
if (!(this instanceof World)) {
return new World(def);
}
if (def && Vec2.isValid(def)) {
def = {
gravity: def
};
}
def = options(def, WorldDef);
this.m_solver = new Solver(this);
this.m_broadPhase = new BroadPhase();
this.m_contactList = null;
this.m_contactCount = 0;
this.m_bodyList = null;
this.m_bodyCount = 0;
this.m_jointList = null;
this.m_jointCount = 0;
this.m_stepComplete = true;
this.m_allowSleep = def.allowSleep;
this.m_gravity = Vec2.clone(def.gravity);
this.m_clearForces = true;
this.m_newFixture = false;
this.m_locked = false;
this.m_warmStarting = def.warmStarting;
this.m_continuousPhysics = def.continuousPhysics;
this.m_subStepping = def.subStepping;
this.m_blockSolve = def.blockSolve;
this.m_velocityIterations = def.velocityIterations;
this.m_positionIterations = def.positionIterations;
this.m_t = 0;
this.m_stepCount = 0;
this.addPair = this.createContact.bind(this);
}
World.prototype.getBodyList = function() {
return this.m_bodyList;
};
World.prototype.getJointList = function() {
return this.m_jointList;
};
World.prototype.getContactList = function() {
return this.m_contactList;
};
World.prototype.getBodyCount = function() {
return this.m_bodyCount;
};
World.prototype.getJointCount = function() {
return this.m_jointCount;
};
World.prototype.getContactCount = function() {
return this.m_contactCount;
};
World.prototype.setGravity = function(gravity) {
this.m_gravity = gravity;
};
World.prototype.getGravity = function() {
return this.m_gravity;
};
World.prototype.isLocked = function() {
return this.m_locked;
};
World.prototype.setAllowSleeping = function(flag) {
if (flag == this.m_allowSleep) {
return;
}
this.m_allowSleep = flag;
if (this.m_allowSleep == false) {
for (var b = this.m_bodyList; b; b = b.m_next) {
b.setAwake(true);
}
}
};
World.prototype.getAllowSleeping = function() {
return this.m_allowSleep;
};
World.prototype.setWarmStarting = function(flag) {
this.m_warmStarting = flag;
};
World.prototype.getWarmStarting = function() {
return this.m_warmStarting;
};
World.prototype.setContinuousPhysics = function(flag) {
this.m_continuousPhysics = flag;
};
World.prototype.getContinuousPhysics = function() {
return this.m_continuousPhysics;
};
World.prototype.setSubStepping = function(flag) {
this.m_subStepping = flag;
};
World.prototype.getSubStepping = function() {
return this.m_subStepping;
};
World.prototype.setAutoClearForces = function(flag) {
this.m_clearForces = flag;
};
World.prototype.getAutoClearForces = function() {
return this.m_clearForces;
};
World.prototype.clearForces = function() {
for (var body = this.m_bodyList; body; body = body.getNext()) {
body.m_force.setZero();
body.m_torque = 0;
}
};
World.prototype.queryAABB = function(aabb, queryCallback) {
ASSERT && common.assert(typeof queryCallback === "function");
var broadPhase = this.m_broadPhase;
this.m_broadPhase.query(aabb, function(proxyId) {
var proxy = broadPhase.getUserData(proxyId);
return queryCallback(proxy.fixture);
});
};
World.prototype.rayCast = function(point1, point2, reportFixtureCallback) {
ASSERT && common.assert(typeof reportFixtureCallback === "function");
var broadPhase = this.m_broadPhase;
this.m_broadPhase.rayCast({
maxFraction: 1,
p1: point1,
p2: point2
}, function(input, proxyId) {
var proxy = broadPhase.getUserData(proxyId);
var fixture = proxy.fixture;
var index = proxy.childIndex;
var output = {};
var hit = fixture.rayCast(output, input, index);
if (hit) {
var fraction = output.fraction;
var point = Vec2.add(Vec2.mul(1 - fraction, input.p1), Vec2.mul(fraction, input.p2));
return reportFixtureCallback(fixture, point, output.normal, fraction);
}
return input.maxFraction;
});
};
World.prototype.getProxyCount = function() {
return this.m_broadPhase.getProxyCount();
};
World.prototype.getTreeHeight = function() {
return this.m_broadPhase.getTreeHeight();
};
World.prototype.getTreeBalance = function() {
return this.m_broadPhase.getTreeBalance();
};
World.prototype.getTreeQuality = function() {
return this.m_broadPhase.getTreeQuality();
};
World.prototype.shiftOrigin = function(newOrigin) {
ASSERT && common.assert(this.m_locked == false);
if (this.m_locked) {
return;
}
for (var b = this.m_bodyList; b; b = b.m_next) {
b.m_xf.p.sub(newOrigin);
b.m_sweep.c0.sub(newOrigin);
b.m_sweep.c.sub(newOrigin);
}
for (var j = this.m_jointList; j; j = j.m_next) {
j.shiftOrigin(newOrigin);
}
this.m_broadPhase.shiftOrigin(newOrigin);
};
World.prototype.createBody = function(def, angle) {
ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return null;
}
if (def && Vec2.isValid(def)) {
def = {
position: def,
angle: angle
};
}
var body = new Body(this, def);
body.m_prev = null;
body.m_next = this.m_bodyList;
if (this.m_bodyList) {
this.m_bodyList.m_prev = body;
}
this.m_bodyList = body;
++this.m_bodyCount;
return body;
};
World.prototype.createDynamicBody = function(def, angle) {
if (!def) {
def = {};
} else if (Vec2.isValid(def)) {
def = {
position: def,
angle: angle
};
}
def.type = "dynamic";
return this.createBody(def);
};
World.prototype.createKinematicBody = function(def, angle) {
if (!def) {
def = {};
} else if (Vec2.isValid(def)) {
def = {
position: def,
angle: angle
};
}
def.type = "kinematic";
return this.createBody(def);
};
World.prototype.destroyBody = function(b) {
ASSERT && common.assert(this.m_bodyCount > 0);
ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return;
}
if (b.m_destroyed) {
return false;
}
var je = b.m_jointList;
while (je) {
var je0 = je;
je = je.next;
this.publish("remove-joint", je0.joint);
this.destroyJoint(je0.joint);
b.m_jointList = je;
}
b.m_jointList = null;
var ce = b.m_contactList;
while (ce) {
var ce0 = ce;
ce = ce.next;
this.destroyContact(ce0.contact);
b.m_contactList = ce;
}
b.m_contactList = null;
var f = b.m_fixtureList;
while (f) {
var f0 = f;
f = f.m_next;
this.publish("remove-fixture", f0);
f0.destroyProxies(this.m_broadPhase);
b.m_fixtureList = f;
}
b.m_fixtureList = null;
if (b.m_prev) {
b.m_prev.m_next = b.m_next;
}
if (b.m_next) {
b.m_next.m_prev = b.m_prev;
}
if (b == this.m_bodyList) {
this.m_bodyList = b.m_next;
}
b.m_destroyed = true;
--this.m_bodyCount;
return true;
};
World.prototype.createJoint = function(joint) {
ASSERT && common.assert(!!joint.m_bodyA);
ASSERT && common.assert(!!joint.m_bodyB);
ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return null;
}
joint.m_prev = null;
joint.m_next = this.m_jointList;
if (this.m_jointList) {
this.m_jointList.m_prev = joint;
}
this.m_jointList = joint;
++this.m_jointCount;
joint.m_edgeA.joint = joint;
joint.m_edgeA.other = joint.m_bodyB;
joint.m_edgeA.prev = null;
joint.m_edgeA.next = joint.m_bodyA.m_jointList;
if (joint.m_bodyA.m_jointList) joint.m_bodyA.m_jointList.prev = joint.m_edgeA;
joint.m_bodyA.m_jointList = joint.m_edgeA;
joint.m_edgeB.joint = joint;
joint.m_edgeB.other = joint.m_bodyA;
joint.m_edgeB.prev = null;
joint.m_edgeB.next = joint.m_bodyB.m_jointList;
if (joint.m_bodyB.m_jointList) joint.m_bodyB.m_jointList.prev = joint.m_edgeB;
joint.m_bodyB.m_jointList = joint.m_edgeB;
if (joint.m_collideConnected == false) {
for (var edge = joint.m_bodyB.getContactList(); edge; edge = edge.next) {
if (edge.other == joint.m_bodyA) {
edge.contact.flagForFiltering();
}
}
}
return joint;
};
World.prototype.destroyJoint = function(joint) {
ASSERT && common.assert(this.isLocked() == false);
if (this.isLocked()) {
return;
}
if (joint.m_prev) {
joint.m_prev.m_next = joint.m_next;
}
if (joint.m_next) {
joint.m_next.m_prev = joint.m_prev;
}
if (joint == this.m_jointList) {
this.m_jointList = joint.m_next;
}
var bodyA = joint.m_bodyA;
var bodyB = joint.m_bodyB;
bodyA.setAwake(true);
bodyB.setAwake(true);
if (joint.m_edgeA.prev) {
joint.m_edgeA.prev.next = joint.m_edgeA.next;
}
if (joint.m_edgeA.next) {
joint.m_edgeA.next.prev = joint.m_edgeA.prev;
}
if (joint.m_edgeA == bodyA.m_jointList) {
bodyA.m_jointList = joint.m_edgeA.next;
}
joint.m_edgeA.prev = null;
joint.m_edgeA.next = null;
if (joint.m_edgeB.prev) {
joint.m_edgeB.prev.next = joint.m_edgeB.next;
}
if (joint.m_edgeB.next) {
joint.m_edgeB.next.prev = joint.m_edgeB.prev;
}
if (joint.m_edgeB == bodyB.m_jointList) {
bodyB.m_jointList = joint.m_edgeB.next;
}
joint.m_edgeB.prev = null;
joint.m_edgeB.next = null;
ASSERT && common.assert(this.m_jointCount > 0);
--this.m_jointCount;
if (joint.m_collideConnected == false) {
var edge = bodyB.getContactList();
while (edge) {
if (edge.other == bodyA) {
edge.contact.flagForFiltering();
}
edge = edge.next;
}
}
this.publish("remove-joint", joint);
};
var s_step = new Solver.TimeStep();
World.prototype.step = function(timeStep, velocityIterations, positionIterations) {
if ((velocityIterations | 0) !== velocityIterations) {
velocityIterations = 0;
}
velocityIterations = velocityIterations || this.m_velocityIterations;
positionIterations = positionIterations || this.m_positionIterations;
this.m_stepCount++;
if (this.m_newFixture) {
this.findNewContacts();
this.m_newFixture = false;
}
this.m_locked = true;
s_step.reset(timeStep);
s_step.velocityIterations = velocityIterations;
s_step.positionIterations = positionIterations;
s_step.warmStarting = this.m_warmStarting;
s_step.blockSolve = this.m_blockSolve;
this.updateContacts();
if (this.m_stepComplete && timeStep > 0) {
this.m_solver.solveWorld(s_step);
for (var b = this.m_bodyList; b; b = b.getNext()) {
if (b.m_islandFlag == false) {
continue;
}
if (b.isStatic()) {
continue;
}
b.synchronizeFixtures();
}
this.findNewContacts();
}
if (this.m_continuousPhysics && timeStep > 0) {
this.m_solver.solveWorldTOI(s_step);
}
if (this.m_clearForces) {
this.clearForces();
}
this.m_locked = false;
};
World.prototype.findNewContacts = function() {
this.m_broadPhase.updatePairs(this.addPair);
};
World.prototype.createContact = function(proxyA, proxyB) {
var fixtureA = proxyA.fixture;
var fixtureB = proxyB.fixture;
var indexA = proxyA.childIndex;
var indexB = proxyB.childIndex;
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
if (bodyA == bodyB) {
return;
}
var edge = bodyB.getContactList();
while (edge) {
if (edge.other == bodyA) {
var fA = edge.contact.getFixtureA();
var fB = edge.contact.getFixtureB();
var iA = edge.contact.getChildIndexA();
var iB = edge.contact.getChildIndexB();
if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) {
return;
}
if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) {
return;
}
}
edge = edge.next;
}
if (bodyB.shouldCollide(bodyA) == false) {
return;
}
if (fixtureB.shouldCollide(fixtureA) == false) {
return;
}
var contact = Contact.create(fixtureA, indexA, fixtureB, indexB);
if (contact == null) {
return;
}
contact.m_prev = null;
if (this.m_contactList != null) {
contact.m_next = this.m_contactList;
this.m_contactList.m_prev = contact;
}
this.m_contactList = contact;
++this.m_contactCount;
};
World.prototype.updateContacts = function() {
var c, next_c = this.m_contactList;
while (c = next_c) {
next_c = c.getNext();
var fixtureA = c.getFixtureA();
var fixtureB = c.getFixtureB();
var indexA = c.getChildIndexA();
var indexB = c.getChildIndexB();
var bodyA = fixtureA.getBody();
var bodyB = fixtureB.getBody();
if (c.m_filterFlag) {
if (bodyB.shouldCollide(bodyA) == false) {
this.destroyContact(c);
continue;
}
if (fixtureB.shouldCollide(fixtureA) == false) {
this.destroyContact(c);
continue;
}
c.m_filterFlag = false;
}
var activeA = bodyA.isAwake() && !bodyA.isStatic();
var activeB = bodyB.isAwake() && !bodyB.isStatic();
if (activeA == false && activeB == false) {
continue;
}
var proxyIdA = fixtureA.m_proxies[indexA].proxyId;
var proxyIdB = fixtureB.m_proxies[indexB].proxyId;
var overlap = this.m_broadPhase.testOverlap(proxyIdA, proxyIdB);
if (overlap == false) {
this.destroyContact(c);
continue;
}
c.update(this);
}
};
World.prototype.destroyContact = function(contact) {
Contact.destroy(contact, this);
if (contact.m_prev) {
contact.m_prev.m_next = contact.m_next;
}
if (contact.m_next) {
contact.m_next.m_prev = contact.m_prev;
}
if (contact == this.m_contactList) {
this.m_contactList = contact.m_next;
}
--this.m_contactCount;
};
World.prototype._listeners = null;
World.prototype.on = function(name, listener) {
if (typeof name !== "string" || typeof listener !== "function") {
return this;
}
if (!this._listeners) {
this._listeners = {};
}
if (!this._listeners[name]) {
this._listeners[name] = [];
}
this._listeners[name].push(listener);
return this;
};
World.prototype.off = function(name, listener) {
if (typeof name !== "string" || typeof listener !== "function") {
return this;
}
var listeners = this._listeners && this._listeners[name];
if (!listeners || !listeners.length) {
return this;
}
var index = listeners.indexOf(listener);
if (index >= 0) {
listeners.splice(index, 1);
}
return this;
};
World.prototype.publish = function(name, arg1, arg2, arg3) {
var listeners = this._listeners && this._listeners[name];
if (!listeners || !listeners.length) {
return 0;
}
for (var l = 0; l < listeners.length; l++) {
listeners[l].call(this, arg1, arg2, arg3);
}
return listeners.length;
};
World.prototype.beginContact = function(contact) {
this.publish("begin-contact", contact);
};
World.prototype.endContact = function(contact) {
this.publish("end-contact", contact);
};
World.prototype.preSolve = function(contact, oldManifold) {
this.publish("pre-solve", contact, oldManifold);
};
World.prototype.postSolve = function(contact, impulse) {
this.publish("post-solve", contact, impulse);
};
},{"./Body":2,"./Contact":3,"./Solver":9,"./collision/BroadPhase":12,"./common/Vec2":23,"./util/Timer":50,"./util/common":51,"./util/options":53}],11:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
module.exports = AABB;
function AABB(lower, upper) {
if (!(this instanceof AABB)) {
return new AABB(lower, upper);
}
this.lowerBound = Vec2.zero();
this.upperBound = Vec2.zero();
if (typeof lower === "object") {
this.lowerBound.set(lower);
}
if (typeof upper === "object") {
this.upperBound.set(upper);
}
}
AABB.prototype.isValid = function() {
return AABB.isValid(this);
};
AABB.isValid = function(aabb) {
var d = Vec2.sub(aabb.upperBound, aabb.lowerBound);
var valid = d.x >= 0 && d.y >= 0 && Vec2.isValid(aabb.lowerBound) && Vec2.isValid(aabb.upperBound);
return valid;
};
AABB.prototype.getCenter = function() {
return Vec2.neo((this.lowerBound.x + this.upperBound.x) * .5, (this.lowerBound.y + this.upperBound.y) * .5);
};
AABB.prototype.getExtents = function() {
return Vec2.neo((this.upperBound.x - this.lowerBound.x) * .5, (this.upperBound.y - this.lowerBound.y) * .5);
};
AABB.prototype.getPerimeter = function() {
return 2 * (this.upperBound.x - this.lowerBound.x + this.upperBound.y - this.lowerBound.y);
};
AABB.prototype.combine = function(a, b) {
b = b || this;
this.lowerBound.set(Math.min(a.lowerBound.x, b.lowerBound.x), Math.min(a.lowerBound.y, b.lowerBound.y));
this.upperBound.set(Math.max(a.upperBound.x, b.upperBound.x), Math.max(a.upperBound.y, b.upperBound.y));
};
AABB.prototype.combinePoints = function(a, b) {
this.lowerBound.set(Math.min(a.x, b.x), Math.min(a.y, b.y));
this.upperBound.set(Math.max(a.x, b.x), Math.max(a.y, b.y));
};
AABB.prototype.set = function(aabb) {
this.lowerBound.set(aabb.lowerBound.x, aabb.lowerBound.y);
this.upperBound.set(aabb.upperBound.x, aabb.upperBound.y);
};
AABB.prototype.contains = function(aabb) {
var result = true;
result = result && this.lowerBound.x <= aabb.lowerBound.x;
result = result && this.lowerBound.y <= aabb.lowerBound.y;
result = result && aabb.upperBound.x <= this.upperBound.x;
result = result && aabb.upperBound.y <= this.upperBound.y;
return result;
};
AABB.prototype.extend = function(value) {
AABB.extend(this, value);
};
AABB.extend = function(aabb, value) {
aabb.lowerBound.x -= value;
aabb.lowerBound.y -= value;
aabb.upperBound.x += value;
aabb.upperBound.y += value;
};
AABB.testOverlap = function(a, b) {
var d1x = b.lowerBound.x - a.upperBound.x;
var d2x = a.lowerBound.x - b.upperBound.x;
var d1y = b.lowerBound.y - a.upperBound.y;
var d2y = a.lowerBound.y - b.upperBound.y;
if (d1x > 0 || d1y > 0 || d2x > 0 || d2y > 0) {
return false;
}
return true;
};
AABB.areEqual = function(a, b) {
return Vec2.areEqual(a.lowerBound, b.lowerBound) && Vec2.areEqual(a.upperBound, b.upperBound);
};
AABB.diff = function(a, b) {
var wD = Math.max(0, Math.min(a.upperBound.x, b.upperBound.x) - Math.max(b.lowerBound.x, a.lowerBound.x));
var hD = Math.max(0, Math.min(a.upperBound.y, b.upperBound.y) - Math.max(b.lowerBound.y, a.lowerBound.y));
var wA = a.upperBound.x - a.lowerBound.x;
var hA = a.upperBound.y - a.lowerBound.y;
var hB = b.upperBound.y - b.lowerBound.y;
var hB = b.upperBound.y - b.lowerBound.y;
return wA * hA + wB * hB - wD * hD;
};
AABB.prototype.rayCast = function(output, input) {
var tmin = -Infinity;
var tmax = Infinity;
var p = input.p1;
var d = Vec2.sub(input.p2, input.p1);
var absD = Vec2.abs(d);
var normal = Vec2.zero();
for (var f = "x"; f !== null; f = f === "x" ? "y" : null) {
if (absD.x < Math.EPSILON) {
if (p[f] < this.lowerBound[f] || this.upperBound[f] < p[f]) {
return false;
}
} else {
var inv_d = 1 / d[f];
var t1 = (this.lowerBound[f] - p[f]) * inv_d;
var t2 = (this.upperBound[f] - p[f]) * inv_d;
var s = -1;
if (t1 > t2) {
var temp = t1;
t1 = t2, t2 = temp;
s = 1;
}
if (t1 > tmin) {
normal.setZero();
normal[f] = s;
tmin = t1;
}
tmax = Math.min(tmax, t2);
if (tmin > tmax) {
return false;
}
}
}
if (tmin < 0 || input.maxFraction < tmin) {
return false;
}
output.fraction = tmin;
output.normal = normal;
return true;
};
AABB.prototype.toString = function() {
return JSON.stringify(this);
};
},{"../Settings":7,"../common/Math":18,"../common/Vec2":23}],12:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var Settings = require("../Settings");
var common = require("../util/common");
var Math = require("../common/Math");
var AABB = require("./AABB");
var DynamicTree = require("./DynamicTree");
module.exports = BroadPhase;
function BroadPhase() {
this.m_tree = new DynamicTree();
this.m_proxyCount = 0;
this.m_moveBuffer = [];
this.queryCallback = this.queryCallback.bind(this);
}
BroadPhase.prototype.getUserData = function(proxyId) {
return this.m_tree.getUserData(proxyId);
};
BroadPhase.prototype.testOverlap = function(proxyIdA, proxyIdB) {
var aabbA = this.m_tree.getFatAABB(proxyIdA);
var aabbB = this.m_tree.getFatAABB(proxyIdB);
return AABB.testOverlap(aabbA, aabbB);
};
BroadPhase.prototype.getFatAABB = function(proxyId) {
return this.m_tree.getFatAABB(proxyId);
};
BroadPhase.prototype.getProxyCount = function() {
return this.m_proxyCount;
};
BroadPhase.prototype.getTreeHeight = function() {
return this.m_tree.getHeight();
};
BroadPhase.prototype.getTreeBalance = function() {
return this.m_tree.getMaxBalance();
};
BroadPhase.prototype.getTreeQuality = function() {
return this.m_tree.getAreaRatio();
};
BroadPhase.prototype.query = function(aabb, queryCallback) {
this.m_tree.query(aabb, queryCallback);
};
BroadPhase.prototype.rayCast = function(input, rayCastCallback) {
this.m_tree.rayCast(input, rayCastCallback);
};
BroadPhase.prototype.shiftOrigin = function(newOrigin) {
this.m_tree.shiftOrigin(newOrigin);
};
BroadPhase.prototype.createProxy = function(aabb, userData) {
ASSERT && common.assert(AABB.isValid(aabb));
var proxyId = this.m_tree.createProxy(aabb, userData);
this.m_proxyCount++;
this.bufferMove(proxyId);
return proxyId;
};
BroadPhase.prototype.destroyProxy = function(proxyId) {
this.unbufferMove(proxyId);
this.m_proxyCount--;
this.m_tree.destroyProxy(proxyId);
};
BroadPhase.prototype.moveProxy = function(proxyId, aabb, displacement) {
ASSERT && common.assert(AABB.isValid(aabb));
var changed = this.m_tree.moveProxy(proxyId, aabb, displacement);
if (changed) {
this.bufferMove(proxyId);
}
};
BroadPhase.prototype.touchProxy = function(proxyId) {
this.bufferMove(proxyId);
};
BroadPhase.prototype.bufferMove = function(proxyId) {
this.m_moveBuffer.push(proxyId);
};
BroadPhase.prototype.unbufferMove = function(proxyId) {
for (var i = 0; i < this.m_moveBuffer.length; ++i) {
if (this.m_moveBuffer[i] == proxyId) {
this.m_moveBuffer[i] = null;
}
}
};
BroadPhase.prototype.updatePairs = function(addPairCallback) {
ASSERT && common.assert(typeof addPairCallback === "function");
this.m_callback = addPairCallback;
while (this.m_moveBuffer.length > 0) {
this.m_queryProxyId = this.m_moveBuffer.pop();
if (this.m_queryProxyId === null) {
continue;
}
var fatAABB = this.m_tree.getFatAABB(this.m_queryProxyId);
this.m_tree.query(fatAABB, this.queryCallback);
}
};
BroadPhase.prototype.queryCallback = function(proxyId) {
if (proxyId == this.m_queryProxyId) {
return true;
}
var proxyIdA = Math.min(proxyId, this.m_queryProxyId);
var proxyIdB = Math.max(proxyId, this.m_queryProxyId);
var userDataA = this.m_tree.getUserData(proxyIdA);
var userDataB = this.m_tree.getUserData(proxyIdB);
this.m_callback(userDataA, userDataB);
return true;
};
},{"../Settings":7,"../common/Math":18,"../util/common":51,"./AABB":11,"./DynamicTree":14}],13:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Distance;
module.exports.Input = DistanceInput;
module.exports.Output = DistanceOutput;
module.exports.Proxy = DistanceProxy;
module.exports.Cache = SimplexCache;
var Settings = require("../Settings");
var common = require("../util/common");
var Timer = require("../util/Timer");
var stats = require("../common/stats");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
stats.gjkCalls = 0;
stats.gjkIters = 0;
stats.gjkMaxIters = 0;
function DistanceInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.transformA = null;
this.transformB = null;
this.useRadii = false;
}
function DistanceOutput() {
this.pointA = Vec2.zero();
this.pointB = Vec2.zero();
this.distance;
this.iterations;
}
function SimplexCache() {
this.metric = 0;
this.indexA = [];
this.indexB = [];
this.count = 0;
}
function Distance(output, cache, input) {
++stats.gjkCalls;
var proxyA = input.proxyA;
var proxyB = input.proxyB;
var xfA = input.transformA;
var xfB = input.transformB;
DEBUG && common.debug("cahce:", cache.metric, cache.count);
DEBUG && common.debug("proxyA:", proxyA.m_count);
DEBUG && common.debug("proxyB:", proxyB.m_count);
DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s);
DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s);
var simplex = new Simplex();
simplex.readCache(cache, proxyA, xfA, proxyB, xfB);
DEBUG && common.debug("cache", simplex.print());
var vertices = simplex.m_v;
var k_maxIters = Settings.maxDistnceIterations;
var saveA = [];
var saveB = [];
var saveCount = 0;
var distanceSqr1 = Infinity;
var distanceSqr2 = Infinity;
var iter = 0;
while (iter < k_maxIters) {
saveCount = simplex.m_count;
for (var i = 0; i < saveCount; ++i) {
saveA[i] = vertices[i].indexA;
saveB[i] = vertices[i].indexB;
}
simplex.solve();
if (simplex.m_count == 3) {
break;
}
var p = simplex.getClosestPoint();
distanceSqr2 = p.lengthSquared();
if (distanceSqr2 >= distanceSqr1) {}
distanceSqr1 = distanceSqr2;
var d = simplex.getSearchDirection();
if (d.lengthSquared() < Math.EPSILON * Math.EPSILON) {
break;
}
var vertex = vertices[simplex.m_count];
vertex.indexA = proxyA.getSupport(Rot.mulT(xfA.q, Vec2.neg(d)));
vertex.wA = Transform.mul(xfA, proxyA.getVertex(vertex.indexA));
vertex.indexB = proxyB.getSupport(Rot.mulT(xfB.q, d));
vertex.wB = Transform.mul(xfB, proxyB.getVertex(vertex.indexB));
vertex.w = Vec2.sub(vertex.wB, vertex.wA);
++iter;
++stats.gjkIters;
var duplicate = false;
for (var i = 0; i < saveCount; ++i) {
if (vertex.indexA == saveA[i] && vertex.indexB == saveB[i]) {
duplicate = true;
break;
}
}
if (duplicate) {
break;
}
++simplex.m_count;
}
stats.gjkMaxIters = Math.max(stats.gjkMaxIters, iter);
simplex.getWitnessPoints(output.pointA, output.pointB);
output.distance = Vec2.distance(output.pointA, output.pointB);
output.iterations = iter;
DEBUG && common.debug("Distance:", output.distance, output.pointA.x, output.pointA.y, output.pointB.x, output.pointB.y);
simplex.writeCache(cache);
if (input.useRadii) {
var rA = proxyA.m_radius;
var rB = proxyB.m_radius;
if (output.distance > rA + rB && output.distance > Math.EPSILON) {
output.distance -= rA + rB;
var normal = Vec2.sub(output.pointB, output.pointA);
normal.normalize();
output.pointA.wAdd(rA, normal);
output.pointB.wSub(rB, normal);
} else {
var p = Vec2.mid(output.pointA, output.pointB);
output.pointA.set(p);
output.pointB.set(p);
output.distance = 0;
}
}
}
function DistanceProxy() {
this.m_buffer = [];
this.m_vertices = [];
this.m_count = 0;
this.m_radius = 0;
}
DistanceProxy.prototype.getVertexCount = function() {
return this.m_count;
};
DistanceProxy.prototype.getVertex = function(index) {
ASSERT && common.assert(0 <= index && index < this.m_count);
return this.m_vertices[index];
};
DistanceProxy.prototype.getSupport = function(d) {
var bestIndex = 0;
var bestValue = Vec2.dot(this.m_vertices[0], d);
for (var i = 0; i < this.m_count; ++i) {
var value = Vec2.dot(this.m_vertices[i], d);
if (value > bestValue) {
bestIndex = i;
bestValue = value;
}
}
return bestIndex;
};
DistanceProxy.prototype.getSupportVertex = function(d) {
return this.m_vertices[this.getSupport(d)];
};
DistanceProxy.prototype.set = function(shape, index) {
ASSERT && common.assert(typeof shape.computeDistanceProxy === "function");
shape.computeDistanceProxy(this, index);
};
function SimplexVertex() {
this.indexA;
this.indexB;
this.wA = Vec2.zero();
this.wB = Vec2.zero();
this.w = Vec2.zero();
this.a;
}
SimplexVertex.prototype.set = function(v) {
this.indexA = v.indexA;
this.indexB = v.indexB;
this.wA = Vec2.clone(v.wA);
this.wB = Vec2.clone(v.wB);
this.w = Vec2.clone(v.w);
this.a = v.a;
};
function Simplex() {
this.m_v1 = new SimplexVertex();
this.m_v2 = new SimplexVertex();
this.m_v3 = new SimplexVertex();
this.m_v = [ this.m_v1, this.m_v2, this.m_v3 ];
this.m_count;
}
Simplex.prototype.print = function() {
if (this.m_count == 3) {
return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y, this.m_v3.a, this.m_v3.wA.x, this.m_v3.wA.y, this.m_v3.wB.x, this.m_v3.wB.y ].toString();
} else if (this.m_count == 2) {
return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y, this.m_v2.a, this.m_v2.wA.x, this.m_v2.wA.y, this.m_v2.wB.x, this.m_v2.wB.y ].toString();
} else if (this.m_count == 1) {
return [ "+" + this.m_count, this.m_v1.a, this.m_v1.wA.x, this.m_v1.wA.y, this.m_v1.wB.x, this.m_v1.wB.y ].toString();
} else {
return "+" + this.m_count;
}
};
Simplex.prototype.readCache = function(cache, proxyA, transformA, proxyB, transformB) {
ASSERT && common.assert(cache.count <= 3);
this.m_count = cache.count;
for (var i = 0; i < this.m_count; ++i) {
var v = this.m_v[i];
v.indexA = cache.indexA[i];
v.indexB = cache.indexB[i];
var wALocal = proxyA.getVertex(v.indexA);
var wBLocal = proxyB.getVertex(v.indexB);
v.wA = Transform.mul(transformA, wALocal);
v.wB = Transform.mul(transformB, wBLocal);
v.w = Vec2.sub(v.wB, v.wA);
v.a = 0;
}
if (this.m_count > 1) {
var metric1 = cache.metric;
var metric2 = this.getMetric();
if (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < Math.EPSILON) {
this.m_count = 0;
}
}
if (this.m_count == 0) {
var v = this.m_v[0];
v.indexA = 0;
v.indexB = 0;
var wALocal = proxyA.getVertex(0);
var wBLocal = proxyB.getVertex(0);
v.wA = Transform.mul(transformA, wALocal);
v.wB = Transform.mul(transformB, wBLocal);
v.w = Vec2.sub(v.wB, v.wA);
v.a = 1;
this.m_count = 1;
}
};
Simplex.prototype.writeCache = function(cache) {
cache.metric = this.getMetric();
cache.count = this.m_count;
for (var i = 0; i < this.m_count; ++i) {
cache.indexA[i] = this.m_v[i].indexA;
cache.indexB[i] = this.m_v[i].indexB;
}
};
Simplex.prototype.getSearchDirection = function() {
switch (this.m_count) {
case 1:
return Vec2.neg(this.m_v1.w);
case 2:
{
var e12 = Vec2.sub(this.m_v2.w, this.m_v1.w);
var sgn = Vec2.cross(e12, Vec2.neg(this.m_v1.w));
if (sgn > 0) {
return Vec2.cross(1, e12);
} else {
return Vec2.cross(e12, 1);
}
}
default:
ASSERT && common.assert(false);
return Vec2.zero();
}
};
Simplex.prototype.getClosestPoint = function() {
switch (this.m_count) {
case 0:
ASSERT && common.assert(false);
return Vec2.zero();
case 1:
return Vec2.clone(this.m_v1.w);
case 2:
return Vec2.wAdd(this.m_v1.a, this.m_v1.w, this.m_v2.a, this.m_v2.w);
case 3:
return Vec2.zero();
default:
ASSERT && common.assert(false);
return Vec2.zero();
}
};
Simplex.prototype.getWitnessPoints = function(pA, pB) {
switch (this.m_count) {
case 0:
ASSERT && common.assert(false);
break;
case 1:
DEBUG && common.debug("case1", this.print());
pA.set(this.m_v1.wA);
pB.set(this.m_v1.wB);
break;
case 2:
DEBUG && common.debug("case2", this.print());
pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA);
pB.wSet(this.m_v1.a, this.m_v1.wB, this.m_v2.a, this.m_v2.wB);
break;
case 3:
DEBUG && common.debug("case3", this.print());
pA.wSet(this.m_v1.a, this.m_v1.wA, this.m_v2.a, this.m_v2.wA);
pA.wAdd(this.m_v3.a, this.m_v3.wA);
pB.set(pA);
break;
default:
ASSERT && common.assert(false);
break;
}
};
Simplex.prototype.getMetric = function() {
switch (this.m_count) {
case 0:
ASSERT && common.assert(false);
return 0;
case 1:
return 0;
case 2:
return Vec2.distance(this.m_v1.w, this.m_v2.w);
case 3:
return Vec2.cross(Vec2.sub(this.m_v2.w, this.m_v1.w), Vec2.sub(this.m_v3.w, this.m_v1.w));
default:
ASSERT && common.assert(false);
return 0;
}
};
Simplex.prototype.solve = function() {
switch (this.m_count) {
case 1:
break;
case 2:
this.solve2();
break;
case 3:
this.solve3();
break;
default:
ASSERT && common.assert(false);
}
};
Simplex.prototype.solve2 = function() {
var w1 = this.m_v1.w;
var w2 = this.m_v2.w;
var e12 = Vec2.sub(w2, w1);
var d12_2 = -Vec2.dot(w1, e12);
if (d12_2 <= 0) {
this.m_v1.a = 1;
this.m_count = 1;
return;
}
var d12_1 = Vec2.dot(w2, e12);
if (d12_1 <= 0) {
this.m_v2.a = 1;
this.m_count = 1;
this.m_v1.set(this.m_v2);
return;
}
var inv_d12 = 1 / (d12_1 + d12_2);
this.m_v1.a = d12_1 * inv_d12;
this.m_v2.a = d12_2 * inv_d12;
this.m_count = 2;
};
Simplex.prototype.solve3 = function() {
var w1 = this.m_v1.w;
var w2 = this.m_v2.w;
var w3 = this.m_v3.w;
var e12 = Vec2.sub(w2, w1);
var w1e12 = Vec2.dot(w1, e12);
var w2e12 = Vec2.dot(w2, e12);
var d12_1 = w2e12;
var d12_2 = -w1e12;
var e13 = Vec2.sub(w3, w1);
var w1e13 = Vec2.dot(w1, e13);
var w3e13 = Vec2.dot(w3, e13);
var d13_1 = w3e13;
var d13_2 = -w1e13;
var e23 = Vec2.sub(w3, w2);
var w2e23 = Vec2.dot(w2, e23);
var w3e23 = Vec2.dot(w3, e23);
var d23_1 = w3e23;
var d23_2 = -w2e23;
var n123 = Vec2.cross(e12, e13);
var d123_1 = n123 * Vec2.cross(w2, w3);
var d123_2 = n123 * Vec2.cross(w3, w1);
var d123_3 = n123 * Vec2.cross(w1, w2);
if (d12_2 <= 0 && d13_2 <= 0) {
this.m_v1.a = 1;
this.m_count = 1;
return;
}
if (d12_1 > 0 && d12_2 > 0 && d123_3 <= 0) {
var inv_d12 = 1 / (d12_1 + d12_2);
this.m_v1.a = d12_1 * inv_d12;
this.m_v2.a = d12_2 * inv_d12;
this.m_count = 2;
return;
}
if (d13_1 > 0 && d13_2 > 0 && d123_2 <= 0) {
var inv_d13 = 1 / (d13_1 + d13_2);
this.m_v1.a = d13_1 * inv_d13;
this.m_v3.a = d13_2 * inv_d13;
this.m_count = 2;
this.m_v2.set(this.m_v3);
return;
}
if (d12_1 <= 0 && d23_2 <= 0) {
this.m_v2.a = 1;
this.m_count = 1;
this.m_v1.set(this.m_v2);
return;
}
if (d13_1 <= 0 && d23_1 <= 0) {
this.m_v3.a = 1;
this.m_count = 1;
this.m_v1.set(this.m_v3);
return;
}
if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) {
var inv_d23 = 1 / (d23_1 + d23_2);
this.m_v2.a = d23_1 * inv_d23;
this.m_v3.a = d23_2 * inv_d23;
this.m_count = 2;
this.m_v1.set(this.m_v3);
return;
}
var inv_d123 = 1 / (d123_1 + d123_2 + d123_3);
this.m_v1.a = d123_1 * inv_d123;
this.m_v2.a = d123_2 * inv_d123;
this.m_v3.a = d123_3 * inv_d123;
this.m_count = 3;
};
Distance.testOverlap = function(shapeA, indexA, shapeB, indexB, xfA, xfB) {
var input = new DistanceInput();
input.proxyA.set(shapeA, indexA);
input.proxyB.set(shapeB, indexB);
input.transformA = xfA;
input.transformB = xfB;
input.useRadii = true;
var cache = new SimplexCache();
var output = new DistanceOutput();
Distance(output, cache, input);
return output.distance < 10 * Math.EPSILON;
};
},{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51}],14:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var Settings = require("../Settings");
var common = require("../util/common");
var Pool = require("../util/Pool");
var Vec2 = require("../common/Vec2");
var Math = require("../common/Math");
var AABB = require("./AABB");
module.exports = DynamicTree;
function TreeNode(id) {
this.id = id;
this.aabb = new AABB();
this.userData = null;
this.parent = null;
this.child1 = null;
this.child2 = null;
this.height = -1;
this.toString = function() {
return this.id + ": " + this.userData;
};
}
TreeNode.prototype.isLeaf = function() {
return this.child1 == null;
};
function DynamicTree() {
this.m_root = null;
this.m_nodes = {};
this.m_lastProxyId = 0;
this.m_pool = new Pool({
create: function() {
return new TreeNode();
}
});
}
DynamicTree.prototype.getUserData = function(id) {
var node = this.m_nodes[id];
ASSERT && common.assert(!!node);
return node.userData;
};
DynamicTree.prototype.getFatAABB = function(id) {
var node = this.m_nodes[id];
ASSERT && common.assert(!!node);
return node.aabb;
};
DynamicTree.prototype.allocateNode = function() {
var node = this.m_pool.allocate();
node.id = ++this.m_lastProxyId;
node.userData = null;
node.parent = null;
node.child1 = null;
node.child2 = null;
node.height = -1;
this.m_nodes[node.id] = node;
return node;
};
DynamicTree.prototype.freeNode = function(node) {
this.m_pool.release(node);
node.height = -1;
delete this.m_nodes[node.id];
};
DynamicTree.prototype.createProxy = function(aabb, userData) {
ASSERT && common.assert(AABB.isValid(aabb));
var node = this.allocateNode();
node.aabb.set(aabb);
AABB.extend(node.aabb, Settings.aabbExtension);
node.userData = userData;
node.height = 0;
this.insertLeaf(node);
return node.id;
};
DynamicTree.prototype.destroyProxy = function(id) {
var node = this.m_nodes[id];
ASSERT && common.assert(!!node);
ASSERT && common.assert(node.isLeaf());
this.removeLeaf(node);
this.freeNode(node);
};
DynamicTree.prototype.moveProxy = function(id, aabb, d) {
ASSERT && common.assert(AABB.isValid(aabb));
ASSERT && common.assert(!d || Vec2.isValid(d));
var node = this.m_nodes[id];
ASSERT && common.assert(!!node);
ASSERT && common.assert(node.isLeaf());
if (node.aabb.contains(aabb)) {
return false;
}
this.removeLeaf(node);
node.aabb.set(aabb);
aabb = node.aabb;
AABB.extend(aabb, Settings.aabbExtension);
if (d.x < 0) {
aabb.lowerBound.x += d.x * Settings.aabbMultiplier;
} else {
aabb.upperBound.x += d.x * Settings.aabbMultiplier;
}
if (d.y < 0) {
aabb.lowerBound.y += d.y * Settings.aabbMultiplier;
} else {
aabb.upperBound.y += d.y * Settings.aabbMultiplier;
}
this.insertLeaf(node);
return true;
};
DynamicTree.prototype.insertLeaf = function(leaf) {
ASSERT && common.assert(AABB.isValid(leaf.aabb));
if (this.m_root == null) {
this.m_root = leaf;
this.m_root.parent = null;
return;
}
var leafAABB = leaf.aabb;
var index = this.m_root;
while (index.isLeaf() == false) {
var child1 = index.child1;
var child2 = index.child2;
var area = index.aabb.getPerimeter();
var combinedAABB = new AABB();
combinedAABB.combine(index.aabb, leafAABB);
var combinedArea = combinedAABB.getPerimeter();
var cost = 2 * combinedArea;
var inheritanceCost = 2 * (combinedArea - area);
var cost1;
if (child1.isLeaf()) {
var aabb = new AABB();
aabb.combine(leafAABB, child1.aabb);
cost1 = aabb.getPerimeter() + inheritanceCost;
} else {
var aabb = new AABB();
aabb.combine(leafAABB, child1.aabb);
var oldArea = child1.aabb.getPerimeter();
var newArea = aabb.getPerimeter();
cost1 = newArea - oldArea + inheritanceCost;
}
var cost2;
if (child2.isLeaf()) {
var aabb = new AABB();
aabb.combine(leafAABB, child2.aabb);
cost2 = aabb.getPerimeter() + inheritanceCost;
} else {
var aabb = new AABB();
aabb.combine(leafAABB, child2.aabb);
var oldArea = child2.aabb.getPerimeter();
var newArea = aabb.getPerimeter();
cost2 = newArea - oldArea + inheritanceCost;
}
if (cost < cost1 && cost < cost2) {
break;
}
if (cost1 < cost2) {
index = child1;
} else {
index = child2;
}
}
var sibling = index;
var oldParent = sibling.parent;
var newParent = this.allocateNode();
newParent.parent = oldParent;
newParent.userData = null;
newParent.aabb.combine(leafAABB, sibling.aabb);
newParent.height = sibling.height + 1;
if (oldParent != null) {
if (oldParent.child1 == sibling) {
oldParent.child1 = newParent;
} else {
oldParent.child2 = newParent;
}
newParent.child1 = sibling;
newParent.child2 = leaf;
sibling.parent = newParent;
leaf.parent = newParent;
} else {
newParent.child1 = sibling;
newParent.child2 = leaf;
sibling.parent = newParent;
leaf.parent = newParent;
this.m_root = newParent;
}
index = leaf.parent;
while (index != null) {
index = this.balance(index);
var child1 = index.child1;
var child2 = index.child2;
ASSERT && common.assert(child1 != null);
ASSERT && common.assert(child2 != null);
index.height = 1 + Math.max(child1.height, child2.height);
index.aabb.combine(child1.aabb, child2.aabb);
index = index.parent;
}
};
DynamicTree.prototype.removeLeaf = function(leaf) {
if (leaf == this.m_root) {
this.m_root = null;
return;
}
var parent = leaf.parent;
var grandParent = parent.parent;
var sibling;
if (parent.child1 == leaf) {
sibling = parent.child2;
} else {
sibling = parent.child1;
}
if (grandParent != null) {
if (grandParent.child1 == parent) {
grandParent.child1 = sibling;
} else {
grandParent.child2 = sibling;
}
sibling.parent = grandParent;
this.freeNode(parent);
var index = grandParent;
while (index != null) {
index = this.balance(index);
var child1 = index.child1;
var child2 = index.child2;
index.aabb.combine(child1.aabb, child2.aabb);
index.height = 1 + Math.max(child1.height, child2.height);
index = index.parent;
}
} else {
this.m_root = sibling;
sibling.parent = null;
this.freeNode(parent);
}
};
DynamicTree.prototype.balance = function(iA) {
ASSERT && common.assert(iA != null);
var A = iA;
if (A.isLeaf() || A.height < 2) {
return iA;
}
var B = A.child1;
var C = A.child2;
var balance = C.height - B.height;
if (balance > 1) {
var F = C.child1;
var G = C.child2;
C.child1 = A;
C.parent = A.parent;
A.parent = C;
if (C.parent != null) {
if (C.parent.child1 == iA) {
C.parent.child1 = C;
} else {
C.parent.child2 = C;
}
} else {
this.m_root = C;
}
if (F.height > G.height) {
C.child2 = F;
A.child2 = G;
G.parent = A;
A.aabb.combine(B.aabb, G.aabb);
C.aabb.combine(A.aabb, F.aabb);
A.height = 1 + Math.max(B.height, G.height);
C.height = 1 + Math.max(A.height, F.height);
} else {
C.child2 = G;
A.child2 = F;
F.parent = A;
A.aabb.combine(B.aabb, F.aabb);
C.aabb.combine(A.aabb, G.aabb);
A.height = 1 + Math.max(B.height, F.height);
C.height = 1 + Math.max(A.height, G.height);
}
return C;
}
if (balance < -1) {
var D = B.child1;
var E = B.child2;
B.child1 = A;
B.parent = A.parent;
A.parent = B;
if (B.parent != null) {
if (B.parent.child1 == A) {
B.parent.child1 = B;
} else {
B.parent.child2 = B;
}
} else {
this.m_root = B;
}
if (D.height > E.height) {
B.child2 = D;
A.child1 = E;
E.parent = A;
A.aabb.combine(C.aabb, E.aabb);
B.aabb.combine(A.aabb, D.aabb);
A.height = 1 + Math.max(C.height, E.height);
B.height = 1 + Math.max(A.height, D.height);
} else {
B.child2 = E;
A.child1 = D;
D.parent = A;
A.aabb.combine(C.aabb, D.aabb);
B.aabb.combine(A.aabb, E.aabb);
A.height = 1 + Math.max(C.height, D.height);
B.height = 1 + Math.max(A.height, E.height);
}
return B;
}
return A;
};
DynamicTree.prototype.getHeight = function() {
if (this.m_root == null) {
return 0;
}
return this.m_root.height;
};
DynamicTree.prototype.getAreaRatio = function() {
if (this.m_root == null) {
return 0;
}
var root = this.m_root;
var rootArea = root.aabb.getPerimeter();
var totalArea = 0;
var node, it = iteratorPool.allocate().preorder();
while (node = it.next()) {
if (node.height < 0) {
continue;
}
totalArea += node.aabb.getPerimeter();
}
iteratorPool.release(it);
return totalArea / rootArea;
};
DynamicTree.prototype.computeHeight = function(id) {
var node;
if (typeof id !== "undefined") {
node = this.m_nodes[id];
} else {
node = this.m_root;
}
if (node.isLeaf()) {
return 0;
}
var height1 = ComputeHeight(node.child1);
var height2 = ComputeHeight(node.child2);
return 1 + Math.max(height1, height2);
};
DynamicTree.prototype.validateStructure = function(node) {
if (node == null) {
return;
}
if (node == this.m_root) {
ASSERT && common.assert(node.parent == null);
}
var child1 = node.child1;
var child2 = node.child2;
if (node.isLeaf()) {
ASSERT && common.assert(child1 == null);
ASSERT && common.assert(child2 == null);
ASSERT && common.assert(node.height == 0);
return;
}
ASSERT && common.assert(child1.parent == node);
ASSERT && common.assert(child2.parent == node);
this.validateStructure(child1);
this.validateStructure(child2);
};
DynamicTree.prototype.validateMetrics = function(node) {
if (node == null) {
return;
}
var child1 = node.child1;
var child2 = node.child2;
if (node.isLeaf()) {
ASSERT && common.assert(child1 == null);
ASSERT && common.assert(child2 == null);
ASSERT && common.assert(node.height == 0);
return;
}
var height1 = this.m_nodes[child1].height;
var height2 = this.m_nodes[child2].height;
var height = 1 + Math.max(height1, height2);
ASSERT && common.assert(node.height == height);
var aabb = new AABB();
aabb.combine(child1.aabb, child2.aabb);
ASSERT && common.assert(AABB.areEqual(aabb, node.aabb));
this.validateMetrics(child1);
this.validateMetrics(child2);
};
DynamicTree.prototype.validate = function() {
ValidateStructure(this.m_root);
ValidateMetrics(this.m_root);
ASSERT && common.assert(this.getHeight() == this.computeHeight());
};
DynamicTree.prototype.getMaxBalance = function() {
var maxBalance = 0;
var node, it = iteratorPool.allocate().preorder();
while (node = it.next()) {
if (node.height <= 1) {
continue;
}
ASSERT && common.assert(node.isLeaf() == false);
var balance = Math.abs(node.child2.height - node.child1.height);
maxBalance = Math.max(maxBalance, balance);
}
iteratorPool.release(it);
return maxBalance;
};
DynamicTree.prototype.rebuildBottomUp = function() {
var nodes = [];
var count = 0;
var node, it = iteratorPool.allocate().preorder();
while (node = it.next()) {
if (node.height < 0) {
continue;
}
if (node.isLeaf()) {
node.parent = null;
nodes[count] = node;
++count;
} else {
this.freeNode(node);
}
}
iteratorPool.release(it);
while (count > 1) {
var minCost = Infinity;
var iMin = -1, jMin = -1;
for (var i = 0; i < count; ++i) {
var aabbi = nodes[i].aabb;
for (var j = i + 1; j < count; ++j) {
var aabbj = nodes[j].aabb;
var b = new AABB();
b.combine(aabbi, aabbj);
var cost = b.getPerimeter();
if (cost < minCost) {
iMin = i;
jMin = j;
minCost = cost;
}
}
}
var child1 = nodes[iMin];
var child2 = nodes[jMin];
var parent = this.allocateNode();
parent.child1 = child1;
parent.child2 = child2;
parent.height = 1 + Math.max(child1.height, child2.height);
parent.aabb.combine(child1.aabb, child2.aabb);
parent.parent = null;
child1.parent = parent;
child2.parent = parent;
nodes[jMin] = nodes[count - 1];
nodes[iMin] = parent;
--count;
}
this.m_root = nodes[0];
this.validate();
};
DynamicTree.prototype.shiftOrigin = function(newOrigin) {
var node, it = iteratorPool.allocate().preorder();
while (node = it.next()) {
var aabb = node.aabb;
aabb.lowerBound.x -= newOrigin.x;
aabb.lowerBound.y -= newOrigin.y;
aabb.lowerBound.x -= newOrigin.x;
aabb.lowerBound.y -= newOrigin.y;
}
iteratorPool.release(it);
};
DynamicTree.prototype.query = function(aabb, queryCallback) {
ASSERT && common.assert(typeof queryCallback === "function");
var stack = stackPool.allocate();
stack.push(this.m_root);
while (stack.length > 0) {
var node = stack.pop();
if (node == null) {
continue;
}
if (AABB.testOverlap(node.aabb, aabb)) {
if (node.isLeaf()) {
var proceed = queryCallback(node.id);
if (proceed == false) {
return;
}
} else {
stack.push(node.child1);
stack.push(node.child2);
}
}
}
stackPool.release(stack);
};
DynamicTree.prototype.rayCast = function(input, rayCastCallback) {
ASSERT && common.assert(typeof rayCastCallback === "function");
var p1 = input.p1;
var p2 = input.p2;
var r = Vec2.sub(p2, p1);
ASSERT && common.assert(r.lengthSquared() > 0);
r.normalize();
var v = Vec2.cross(1, r);
var abs_v = Vec2.abs(v);
var maxFraction = input.maxFraction;
var segmentAABB = new AABB();
var t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2);
segmentAABB.combinePoints(p1, t);
var stack = stackPool.allocate();
var subInput = inputPool.allocate();
stack.push(this.m_root);
while (stack.length > 0) {
var node = stack.pop();
if (node == null) {
continue;
}
if (AABB.testOverlap(node.aabb, segmentAABB) == false) {
continue;
}
var c = node.aabb.getCenter();
var h = node.aabb.getExtents();
var separation = Math.abs(Vec2.dot(v, Vec2.sub(p1, c))) - Vec2.dot(abs_v, h);
if (separation > 0) {
continue;
}
if (node.isLeaf()) {
subInput.p1 = Vec2.clone(input.p1);
subInput.p2 = Vec2.clone(input.p2);
subInput.maxFraction = maxFraction;
var value = rayCastCallback(subInput, node.id);
if (value == 0) {
return;
}
if (value > 0) {
maxFraction = value;
t = Vec2.wAdd(1 - maxFraction, p1, maxFraction, p2);
segmentAABB.combinePoints(p1, t);
}
} else {
stack.push(node.child1);
stack.push(node.child2);
}
}
stackPool.release(stack);
inputPool.release(subInput);
};
var inputPool = new Pool({
create: function() {
return {};
},
release: function(stack) {}
});
var stackPool = new Pool({
create: function() {
return [];
},
release: function(stack) {
stack.length = 0;
}
});
var iteratorPool = new Pool({
create: function() {
return new Iterator();
},
release: function(iterator) {
iterator.close();
}
});
function Iterator() {
var parents = [];
var states = [];
return {
preorder: function(root) {
parents.length = 0;
parents.push(root);
states.length = 0;
states.push(0);
return this;
},
next: function() {
while (parents.length > 0) {
var i = parents.length - 1;
var node = parents[i];
if (states[i] === 0) {
states[i] = 1;
return node;
}
if (states[i] === 1) {
states[i] = 2;
if (node.child1) {
parents.push(node.child1);
states.push(1);
return node.child1;
}
}
if (states[i] === 2) {
states[i] = 3;
if (node.child2) {
parents.push(node.child2);
states.push(1);
return node.child2;
}
}
parents.pop();
states.pop();
}
},
close: function() {
parents.length = 0;
}
};
}
},{"../Settings":7,"../common/Math":18,"../common/Vec2":23,"../util/Pool":49,"../util/common":51,"./AABB":11}],15:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = TimeOfImpact;
module.exports.Input = TOIInput;
module.exports.Output = TOIOutput;
var Settings = require("../Settings");
var common = require("../util/common");
var Timer = require("../util/Timer");
var stats = require("../common/stats");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Distance = require("./Distance");
var DistanceInput = Distance.Input;
var DistanceOutput = Distance.Output;
var DistanceProxy = Distance.Proxy;
var SimplexCache = Distance.Cache;
function TOIInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.sweepA = new Sweep();
this.sweepB = new Sweep();
this.tMax;
}
TOIOutput.e_unknown = 0;
TOIOutput.e_failed = 1;
TOIOutput.e_overlapped = 2;
TOIOutput.e_touching = 3;
TOIOutput.e_separated = 4;
function TOIOutput() {
this.state;
this.t;
}
stats.toiTime = 0;
stats.toiMaxTime = 0;
stats.toiCalls = 0;
stats.toiIters = 0;
stats.toiMaxIters = 0;
stats.toiRootIters = 0;
stats.toiMaxRootIters = 0;
function TimeOfImpact(output, input) {
var timer = Timer.now();
++stats.toiCalls;
output.state = TOIOutput.e_unknown;
output.t = input.tMax;
var proxyA = input.proxyA;
var proxyB = input.proxyB;
var sweepA = input.sweepA;
var sweepB = input.sweepB;
DEBUG && common.debug("sweepA", sweepA.localCenter.x, sweepA.localCenter.y, sweepA.c.x, sweepA.c.y, sweepA.a, sweepA.alpha0, sweepA.c0.x, sweepA.c0.y, sweepA.a0);
DEBUG && common.debug("sweepB", sweepB.localCenter.x, sweepB.localCenter.y, sweepB.c.x, sweepB.c.y, sweepB.a, sweepB.alpha0, sweepB.c0.x, sweepB.c0.y, sweepB.a0);
sweepA.normalize();
sweepB.normalize();
var tMax = input.tMax;
var totalRadius = proxyA.m_radius + proxyB.m_radius;
var target = Math.max(Settings.linearSlop, totalRadius - 3 * Settings.linearSlop);
var tolerance = .25 * Settings.linearSlop;
ASSERT && common.assert(target > tolerance);
var t1 = 0;
var k_maxIterations = Settings.maxTOIIterations;
var iter = 0;
var cache = new SimplexCache();
var distanceInput = new DistanceInput();
distanceInput.proxyA = input.proxyA;
distanceInput.proxyB = input.proxyB;
distanceInput.useRadii = false;
for (;;) {
var xfA = Transform.identity();
var xfB = Transform.identity();
sweepA.getTransform(xfA, t1);
sweepB.getTransform(xfB, t1);
DEBUG && common.debug("xfA:", xfA.p.x, xfA.p.y, xfA.q.c, xfA.q.s);
DEBUG && common.debug("xfB:", xfB.p.x, xfB.p.y, xfB.q.c, xfB.q.s);
distanceInput.transformA = xfA;
distanceInput.transformB = xfB;
var distanceOutput = new DistanceOutput();
Distance(distanceOutput, cache, distanceInput);
DEBUG && common.debug("distance:", distanceOutput.distance);
if (distanceOutput.distance <= 0) {
output.state = TOIOutput.e_overlapped;
output.t = 0;
break;
}
if (distanceOutput.distance < target + tolerance) {
output.state = TOIOutput.e_touching;
output.t = t1;
break;
}
var fcn = new SeparationFunction();
fcn.initialize(cache, proxyA, sweepA, proxyB, sweepB, t1);
if (false) {
var N = 100;
var dx = 1 / N;
var xs = [];
var fs = [];
var x = 0;
for (var i = 0; i <= N; ++i) {
sweepA.getTransform(xfA, x);
sweepB.getTransform(xfB, x);
var f = fcn.evaluate(xfA, xfB) - target;
printf("%g %g\n", x, f);
xs[i] = x;
fs[i] = f;
x += dx;
}
}
var done = false;
var t2 = tMax;
var pushBackIter = 0;
for (;;) {
var s2 = fcn.findMinSeparation(t2);
var indexA = fcn.indexA;
var indexB = fcn.indexB;
if (s2 > target + tolerance) {
output.state = TOIOutput.e_separated;
output.t = tMax;
done = true;
break;
}
if (s2 > target - tolerance) {
t1 = t2;
break;
}
var s1 = fcn.evaluate(t1);
var indexA = fcn.indexA;
var indexB = fcn.indexB;
DEBUG && common.debug("s1:", s1, target, tolerance, t1);
if (s1 < target - tolerance) {
output.state = TOIOutput.e_failed;
output.t = t1;
done = true;
break;
}
if (s1 <= target + tolerance) {
output.state = TOIOutput.e_touching;
output.t = t1;
done = true;
break;
}
var rootIterCount = 0;
var a1 = t1, a2 = t2;
for (;;) {
var t;
if (rootIterCount & 1) {
t = a1 + (target - s1) * (a2 - a1) / (s2 - s1);
} else {
t = .5 * (a1 + a2);
}
++rootIterCount;
++stats.toiRootIters;
var s = fcn.evaluate(t);
var indexA = fcn.indexA;
var indexB = fcn.indexB;
if (Math.abs(s - target) < tolerance) {
t2 = t;
break;
}
if (s > target) {
a1 = t;
s1 = s;
} else {
a2 = t;
s2 = s;
}
if (rootIterCount == 50) {
break;
}
}
stats.toiMaxRootIters = Math.max(stats.toiMaxRootIters, rootIterCount);
++pushBackIter;
if (pushBackIter == Settings.maxPolygonVertices) {
break;
}
}
++iter;
++stats.toiIters;
if (done) {
break;
}
if (iter == k_maxIterations) {
output.state = TOIOutput.e_failed;
output.t = t1;
break;
}
}
stats.toiMaxIters = Math.max(stats.toiMaxIters, iter);
var time = Timer.diff(timer);
stats.toiMaxTime = Math.max(stats.toiMaxTime, time);
stats.toiTime += time;
}
var e_points = 1;
var e_faceA = 2;
var e_faceB = 3;
function SeparationFunction() {
this.m_proxyA = new DistanceProxy();
this.m_proxyB = new DistanceProxy();
this.m_sweepA;
this.m_sweepB;
this.m_type;
this.m_localPoint = Vec2.zero();
this.m_axis = Vec2.zero();
}
SeparationFunction.prototype.initialize = function(cache, proxyA, sweepA, proxyB, sweepB, t1) {
this.m_proxyA = proxyA;
this.m_proxyB = proxyB;
var count = cache.count;
ASSERT && common.assert(0 < count && count < 3);
this.m_sweepA = sweepA;
this.m_sweepB = sweepB;
var xfA = Transform.identity();
var xfB = Transform.identity();
this.m_sweepA.getTransform(xfA, t1);
this.m_sweepB.getTransform(xfB, t1);
if (count == 1) {
this.m_type = e_points;
var localPointA = this.m_proxyA.getVertex(cache.indexA[0]);
var localPointB = this.m_proxyB.getVertex(cache.indexB[0]);
var pointA = Transform.mul(xfA, localPointA);
var pointB = Transform.mul(xfB, localPointB);
this.m_axis.wSet(1, pointB, -1, pointA);
var s = this.m_axis.normalize();
return s;
} else if (cache.indexA[0] == cache.indexA[1]) {
this.m_type = e_faceB;
var localPointB1 = proxyB.getVertex(cache.indexB[0]);
var localPointB2 = proxyB.getVertex(cache.indexB[1]);
this.m_axis = Vec2.cross(Vec2.sub(localPointB2, localPointB1), 1);
this.m_axis.normalize();
var normal = Rot.mul(xfB.q, this.m_axis);
this.m_localPoint = Vec2.mid(localPointB1, localPointB2);
var pointB = Transform.mul(xfB, this.m_localPoint);
var localPointA = proxyA.getVertex(cache.indexA[0]);
var pointA = Transform.mul(xfA, localPointA);
var s = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal);
if (s < 0) {
this.m_axis = Vec2.neg(this.m_axis);
s = -s;
}
return s;
} else {
this.m_type = e_faceA;
var localPointA1 = this.m_proxyA.getVertex(cache.indexA[0]);
var localPointA2 = this.m_proxyA.getVertex(cache.indexA[1]);
this.m_axis = Vec2.cross(Vec2.sub(localPointA2, localPointA1), 1);
this.m_axis.normalize();
var normal = Rot.mul(xfA.q, this.m_axis);
this.m_localPoint = Vec2.mid(localPointA1, localPointA2);
var pointA = Transform.mul(xfA, this.m_localPoint);
var localPointB = this.m_proxyB.getVertex(cache.indexB[0]);
var pointB = Transform.mul(xfB, localPointB);
var s = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal);
if (s < 0) {
this.m_axis = Vec2.neg(this.m_axis);
s = -s;
}
return s;
}
};
SeparationFunction.prototype.compute = function(find, t) {
var xfA = Transform.identity();
var xfB = Transform.identity();
this.m_sweepA.getTransform(xfA, t);
this.m_sweepB.getTransform(xfB, t);
switch (this.m_type) {
case e_points:
{
if (find) {
var axisA = Rot.mulT(xfA.q, this.m_axis);
var axisB = Rot.mulT(xfB.q, Vec2.neg(this.m_axis));
this.indexA = this.m_proxyA.getSupport(axisA);
this.indexB = this.m_proxyB.getSupport(axisB);
}
var localPointA = this.m_proxyA.getVertex(this.indexA);
var localPointB = this.m_proxyB.getVertex(this.indexB);
var pointA = Transform.mul(xfA, localPointA);
var pointB = Transform.mul(xfB, localPointB);
var sep = Vec2.dot(pointB, this.m_axis) - Vec2.dot(pointA, this.m_axis);
return sep;
}
case e_faceA:
{
var normal = Rot.mul(xfA.q, this.m_axis);
var pointA = Transform.mul(xfA, this.m_localPoint);
if (find) {
var axisB = Rot.mulT(xfB.q, Vec2.neg(normal));
this.indexA = -1;
this.indexB = this.m_proxyB.getSupport(axisB);
}
var localPointB = this.m_proxyB.getVertex(this.indexB);
var pointB = Transform.mul(xfB, localPointB);
var sep = Vec2.dot(pointB, normal) - Vec2.dot(pointA, normal);
return sep;
}
case e_faceB:
{
var normal = Rot.mul(xfB.q, this.m_axis);
var pointB = Transform.mul(xfB, this.m_localPoint);
if (find) {
var axisA = Rot.mulT(xfA.q, Vec2.neg(normal));
this.indexB = -1;
this.indexA = this.m_proxyA.getSupport(axisA);
}
var localPointA = this.m_proxyA.getVertex(this.indexA);
var pointA = Transform.mul(xfA, localPointA);
var sep = Vec2.dot(pointA, normal) - Vec2.dot(pointB, normal);
return sep;
}
default:
ASSERT && common.assert(false);
if (find) {
this.indexA = -1;
this.indexB = -1;
}
return 0;
}
};
SeparationFunction.prototype.findMinSeparation = function(t) {
return this.compute(true, t);
};
SeparationFunction.prototype.evaluate = function(t) {
return this.compute(false, t);
};
},{"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../common/stats":26,"../util/Timer":50,"../util/common":51,"./Distance":13}],16:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Mat22;
var common = require("../util/common");
var Math = require("./Math");
var Vec2 = require("./Vec2");
function Mat22(a, b, c, d) {
if (typeof a === "object" && a !== null) {
this.ex = Vec2.clone(a);
this.ey = Vec2.clone(b);
} else if (typeof a === "number") {
this.ex = Vec2.neo(a, c);
this.ey = Vec2.neo(b, d);
} else {
this.ex = Vec2.zero();
this.ey = Vec2.zero();
}
}
Mat22.prototype.toString = function() {
return JSON.stringify(this);
};
Mat22.isValid = function(o) {
return o && Vec2.isValid(o.ex) && Vec2.isValid(o.ey);
};
Mat22.assert = function(o) {
if (!ASSERT) return;
if (!Mat22.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Mat22!");
}
};
Mat22.prototype.set = function(a, b, c, d) {
if (typeof a === "number" && typeof b === "number" && typeof c === "number" && typeof d === "number") {
this.ex.set(a, c);
this.ey.set(b, d);
} else if (typeof a === "object" && typeof b === "object") {
this.ex.set(a);
this.ey.set(b);
} else if (typeof a === "object") {
ASSERT && Mat22.assert(a);
this.ex.set(a.ex);
this.ey.set(a.ey);
} else {
ASSERT && common.assert(false);
}
};
Mat22.prototype.setIdentity = function() {
this.ex.x = 1;
this.ey.x = 0;
this.ex.y = 0;
this.ey.y = 1;
};
Mat22.prototype.setZero = function() {
this.ex.x = 0;
this.ey.x = 0;
this.ex.y = 0;
this.ey.y = 0;
};
Mat22.prototype.getInverse = function() {
var a = this.ex.x;
var b = this.ey.x;
var c = this.ex.y;
var d = this.ey.y;
var det = a * d - b * c;
if (det != 0) {
det = 1 / det;
}
var imx = new Mat22();
imx.ex.x = det * d;
imx.ey.x = -det * b;
imx.ex.y = -det * c;
imx.ey.y = det * a;
return imx;
};
Mat22.prototype.solve = function(v) {
ASSERT && Vec2.assert(v);
var a = this.ex.x;
var b = this.ey.x;
var c = this.ex.y;
var d = this.ey.y;
var det = a * d - b * c;
if (det != 0) {
det = 1 / det;
}
var w = Vec2.zero();
w.x = det * (d * v.x - b * v.y);
w.y = det * (a * v.y - c * v.x);
return w;
};
Mat22.mul = function(mx, v) {
if (v && "x" in v && "y" in v) {
ASSERT && Vec2.assert(v);
var x = mx.ex.x * v.x + mx.ey.x * v.y;
var y = mx.ex.y * v.x + mx.ey.y * v.y;
return Vec2.neo(x, y);
} else if (v && "ex" in v && "ey" in v) {
ASSERT && Mat22.assert(v);
return new Mat22(Vec2.mul(mx, v.ex), Vec2.mul(mx, v.ey));
}
ASSERT && common.assert(false);
};
Mat22.mulT = function(mx, v) {
if (v && "x" in v && "y" in v) {
ASSERT && Vec2.assert(v);
return Vec2.neo(Vec2.dot(v, mx.ex), Vec2.dot(v, mx.ey));
} else if (v && "ex" in v && "ey" in v) {
ASSERT && Mat22.assert(v);
var c1 = Vec2.neo(Vec2.dot(mx.ex, v.ex), Vec2.dot(mx.ey, v.ex));
var c2 = Vec2.neo(Vec2.dot(mx.ex, v.ey), Vec2.dot(mx.ey, v.ey));
return new Mat22(c1, c2);
}
ASSERT && common.assert(false);
};
Mat22.abs = function(mx) {
ASSERT && Mat22.assert(mx);
return new Mat22(Vec2.abs(mx.ex), Vec2.abs(mx.ey));
};
Mat22.add = function(mx1, mx2) {
ASSERT && Mat22.assert(mx1);
ASSERT && Mat22.assert(mx2);
return new Mat22(Vec2.add(mx1.ex + mx2.ex), Vec2.add(mx1.ey + mx2.ey));
};
},{"../util/common":51,"./Math":18,"./Vec2":23}],17:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Mat33;
var common = require("../util/common");
var Math = require("./Math");
var Vec2 = require("./Vec2");
var Vec3 = require("./Vec3");
function Mat33(a, b, c) {
if (typeof a === "object" && a !== null) {
this.ex = Vec3.clone(a);
this.ey = Vec3.clone(b);
this.ez = Vec3.clone(c);
} else {
this.ex = Vec3();
this.ey = Vec3();
this.ez = Vec3();
}
}
Mat33.prototype.toString = function() {
return JSON.stringify(this);
};
Mat33.isValid = function(o) {
return o && Vec3.isValid(o.ex) && Vec3.isValid(o.ey) && Vec3.isValid(o.ez);
};
Mat33.assert = function(o) {
if (!ASSERT) return;
if (!Mat33.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Mat33!");
}
};
Mat33.prototype.setZero = function() {
this.ex.setZero();
this.ey.setZero();
this.ez.setZero();
return this;
};
Mat33.prototype.solve33 = function(v) {
var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez));
if (det != 0) {
det = 1 / det;
}
var r = new Vec3();
r.x = det * Vec3.dot(v, Vec3.cross(this.ey, this.ez));
r.y = det * Vec3.dot(this.ex, Vec3.cross(v, this.ez));
r.z = det * Vec3.dot(this.ex, Vec3.cross(this.ey, v));
return r;
};
Mat33.prototype.solve22 = function(v) {
var a11 = this.ex.x;
var a12 = this.ey.x;
var a21 = this.ex.y;
var a22 = this.ey.y;
var det = a11 * a22 - a12 * a21;
if (det != 0) {
det = 1 / det;
}
var r = Vec2.zero();
r.x = det * (a22 * v.x - a12 * v.y);
r.y = det * (a11 * v.y - a21 * v.x);
return r;
};
Mat33.prototype.getInverse22 = function(M) {
var a = this.ex.x;
var b = this.ey.x;
var c = this.ex.y;
var d = this.ey.y;
var det = a * d - b * c;
if (det != 0) {
det = 1 / det;
}
M.ex.x = det * d;
M.ey.x = -det * b;
M.ex.z = 0;
M.ex.y = -det * c;
M.ey.y = det * a;
M.ey.z = 0;
M.ez.x = 0;
M.ez.y = 0;
M.ez.z = 0;
};
Mat33.prototype.getSymInverse33 = function(M) {
var det = Vec3.dot(this.ex, Vec3.cross(this.ey, this.ez));
if (det != 0) {
det = 1 / det;
}
var a11 = this.ex.x;
var a12 = this.ey.x;
var a13 = this.ez.x;
var a22 = this.ey.y;
var a23 = this.ez.y;
var a33 = this.ez.z;
M.ex.x = det * (a22 * a33 - a23 * a23);
M.ex.y = det * (a13 * a23 - a12 * a33);
M.ex.z = det * (a12 * a23 - a13 * a22);
M.ey.x = M.ex.y;
M.ey.y = det * (a11 * a33 - a13 * a13);
M.ey.z = det * (a13 * a12 - a11 * a23);
M.ez.x = M.ex.z;
M.ez.y = M.ey.z;
M.ez.z = det * (a11 * a22 - a12 * a12);
};
Mat33.mul = function(a, b) {
ASSERT && Mat33.assert(a);
if (b && "z" in b && "y" in b && "x" in b) {
ASSERT && Vec3.assert(b);
var x = a.ex.x * b.x + a.ey.x * b.y + a.ez.x * b.z;
var y = a.ex.y * b.x + a.ey.y * b.y + a.ez.y * b.z;
var z = a.ex.z * b.x + a.ey.z * b.y + a.ez.z * b.z;
return new Vec3(x, y, z);
} else if (b && "y" in b && "x" in b) {
ASSERT && Vec2.assert(b);
var x = a.ex.x * b.x + a.ey.x * b.y;
var y = a.ex.y * b.x + a.ey.y * b.y;
return Vec2.neo(x, y);
}
ASSERT && common.assert(false);
};
Mat33.add = function(a, b) {
ASSERT && Mat33.assert(a);
ASSERT && Mat33.assert(b);
return new Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
};
},{"../util/common":51,"./Math":18,"./Vec2":23,"./Vec3":24}],18:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var create = require("../util/create");
var native = Math;
var math = module.exports = create(native);
math.EPSILON = 1e-9;
math.isFinite = function(x) {
return typeof x === "number" && isFinite(x) && !isNaN(x);
};
math.assert = function(x) {
if (!ASSERT) return;
if (!math.isFinite(x)) {
DEBUG && common.debug(x);
throw new Error("Invalid Number!");
}
};
math.invSqrt = function(x) {
return 1 / native.sqrt(x);
};
math.nextPowerOfTwo = function(x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
};
math.isPowerOfTwo = function(x) {
return x > 0 && (x & x - 1) == 0;
};
math.mod = function(num, min, max) {
if (typeof min === "undefined") {
max = 1, min = 0;
} else if (typeof max === "undefined") {
max = min, min = 0;
}
if (max > min) {
num = (num - min) % (max - min);
return num + (num < 0 ? max : min);
} else {
num = (num - max) % (min - max);
return num + (num <= 0 ? min : max);
}
};
math.clamp = function(num, min, max) {
if (num < min) {
return min;
} else if (num > max) {
return max;
} else {
return num;
}
};
math.random = function(min, max) {
if (typeof min === "undefined") {
max = 1;
min = 0;
} else if (typeof max === "undefined") {
max = min;
min = 0;
}
return min == max ? min : native.random() * (max - min) + min;
};
},{"../util/common":51,"../util/create":52}],19:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Position;
var Vec2 = require("./Vec2");
var Rot = require("./Rot");
function Position() {
this.c = Vec2.zero();
this.a = 0;
}
Position.prototype.getTransform = function(xf, p) {
xf.q.set(this.a);
xf.p.set(Vec2.sub(this.c, Rot.mul(xf.q, p)));
return xf;
};
},{"./Rot":20,"./Vec2":23}],20:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Rot;
var common = require("../util/common");
var Vec2 = require("./Vec2");
var Math = require("./Math");
function Rot(angle) {
if (!(this instanceof Rot)) {
return new Rot(angle);
}
if (typeof angle === "number") {
this.setAngle(angle);
} else if (typeof angle === "object") {
this.set(angle);
} else {
this.setIdentity();
}
}
Rot.neo = function(angle) {
var obj = Object.create(Rot.prototype);
obj.setAngle(angle);
return obj;
};
Rot.clone = function(rot) {
ASSERT && Rot.assert(rot);
var obj = Object.create(Rot.prototype);
ojb.s = rot.s;
ojb.c = rot.c;
return ojb;
};
Rot.identity = function(rot) {
ASSERT && Rot.assert(rot);
var obj = Object.create(Rot.prototype);
obj.s = 0;
obj.c = 1;
return obj;
};
Rot.isValid = function(o) {
return o && Math.isFinite(o.s) && Math.isFinite(o.c);
};
Rot.assert = function(o) {
if (!ASSERT) return;
if (!Rot.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Rot!");
}
};
Rot.prototype.setIdentity = function() {
this.s = 0;
this.c = 1;
};
Rot.prototype.set = function(angle) {
if (typeof angle === "object") {
ASSERT && Rot.assert(angle);
this.s = angle.s;
this.c = angle.c;
} else {
ASSERT && Math.assert(angle);
this.s = Math.sin(angle);
this.c = Math.cos(angle);
}
};
Rot.prototype.setAngle = function(angle) {
ASSERT && Math.assert(angle);
this.s = Math.sin(angle);
this.c = Math.cos(angle);
};
Rot.prototype.getAngle = function() {
return Math.atan2(this.s, this.c);
};
Rot.prototype.getXAxis = function() {
return Vec2.neo(this.c, this.s);
};
Rot.prototype.getYAxis = function() {
return Vec2.neo(-this.s, this.c);
};
Rot.mul = function(rot, m) {
ASSERT && Rot.assert(rot);
if ("c" in m && "s" in m) {
ASSERT && Rot.assert(m);
var qr = Rot.identity();
qr.s = rot.s * m.c + rot.c * m.s;
qr.c = rot.c * m.c - rot.s * m.s;
return qr;
} else if ("x" in m && "y" in m) {
ASSERT && Vec2.assert(m);
return Vec2.neo(rot.c * m.x - rot.s * m.y, rot.s * m.x + rot.c * m.y);
}
};
Rot.mulSub = function(rot, v, w) {
var x = rot.c * (v.x - w.x) - rot.s * (v.y - w.y);
var y = rot.s * (v.x - w.y) + rot.c * (v.y - w.y);
return Vec2.neo(x, y);
};
Rot.mulT = function(rot, m) {
if ("c" in m && "s" in m) {
ASSERT && Rot.assert(m);
var qr = Rot.identity();
qr.s = rot.c * m.s - rot.s * m.c;
qr.c = rot.c * m.c + rot.s * m.s;
return qr;
} else if ("x" in m && "y" in m) {
ASSERT && Vec2.assert(m);
return Vec2.neo(rot.c * m.x + rot.s * m.y, -rot.s * m.x + rot.c * m.y);
}
};
},{"../util/common":51,"./Math":18,"./Vec2":23}],21:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Sweep;
var common = require("../util/common");
var Math = require("./Math");
var Vec2 = require("./Vec2");
var Rot = require("./Rot");
var Transform = require("./Transform");
function Sweep(c, a) {
ASSERT && common.assert(typeof c === "undefined");
ASSERT && common.assert(typeof a === "undefined");
this.localCenter = Vec2.zero();
this.c = Vec2.zero();
this.a = 0;
this.alpha0 = 0;
this.c0 = Vec2.zero();
this.a0 = 0;
}
Sweep.prototype.setTransform = function(xf) {
var c = Transform.mul(xf, this.localCenter);
this.c.set(c);
this.c0.set(c);
this.a = xf.q.getAngle();
this.a0 = xf.q.getAngle();
};
Sweep.prototype.setLocalCenter = function(localCenter, xf) {
this.localCenter.set(localCenter);
var c = Transform.mul(xf, this.localCenter);
this.c.set(c);
this.c0.set(c);
};
Sweep.prototype.getTransform = function(xf, beta) {
beta = typeof beta === "undefined" ? 0 : beta;
xf.q.setAngle((1 - beta) * this.a0 + beta * this.a);
xf.p.wSet(1 - beta, this.c0, beta, this.c);
xf.p.sub(Rot.mul(xf.q, this.localCenter));
};
Sweep.prototype.advance = function(alpha) {
ASSERT && common.assert(this.alpha0 < 1);
var beta = (alpha - this.alpha0) / (1 - this.alpha0);
this.c0.wSet(beta, this.c, 1 - beta, this.c0);
this.a0 = beta * this.a + (1 - beta) * this.a0;
this.alpha0 = alpha;
};
Sweep.prototype.forward = function() {
this.a0 = this.a;
this.c0.set(this.c);
};
Sweep.prototype.normalize = function() {
var a0 = Math.mod(this.a0, -Math.PI, +Math.PI);
this.a -= this.a0 - a0;
this.a0 = a0;
};
Sweep.prototype.clone = function() {
var clone = new Sweep();
clone.localCenter.set(this.localCenter);
clone.alpha0 = this.alpha0;
clone.a0 = this.a0;
clone.a = this.a;
clone.c0.set(this.c0);
clone.c.set(this.c);
return clone;
};
Sweep.prototype.set = function(that) {
this.localCenter.set(that.localCenter);
this.alpha0 = that.alpha0;
this.a0 = that.a0;
this.a = that.a;
this.c0.set(that.c0);
this.c.set(that.c);
};
},{"../util/common":51,"./Math":18,"./Rot":20,"./Transform":22,"./Vec2":23}],22:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Transform;
var common = require("../util/common");
var Vec2 = require("./Vec2");
var Rot = require("./Rot");
function Transform(position, rotation) {
if (!(this instanceof Transform)) {
return new Transform(position, rotation);
}
this.p = Vec2.zero();
this.q = Rot.identity();
if (typeof position !== "undefined") {
this.p.set(position);
}
if (typeof rotation !== "undefined") {
this.q.set(rotation);
}
}
Transform.clone = function(xf) {
var obj = Object.create(Transform.prototype);
obj.p = Vec2.clone(xf.p);
obj.q = Rot.clone(xf.q);
return obj;
};
Transform.neo = function(position, rotation) {
var obj = Object.create(Transform.prototype);
obj.p = Vec2.clone(position);
obj.q = Rot.clone(rotation);
return obj;
};
Transform.identity = function() {
var obj = Object.create(Transform.prototype);
obj.p = Vec2.zero();
obj.q = Rot.identity();
return obj;
};
Transform.prototype.setIdentity = function() {
this.p.setZero();
this.q.setIdentity();
};
Transform.prototype.set = function(a, b) {
if (Transform.isValid(a)) {
this.p.set(a.p);
this.q.set(a.q);
} else {
this.p.set(a);
this.q.set(b);
}
};
Transform.isValid = function(o) {
return o && Vec2.isValid(o.p) && Rot.isValid(o.q);
};
Transform.assert = function(o) {
if (!ASSERT) return;
if (!Transform.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Transform!");
}
};
Transform.mul = function(a, b) {
ASSERT && Transform.assert(a);
if (Array.isArray(b)) {
var arr = [];
for (var i = 0; i < b.length; i++) {
arr[i] = Transform.mul(a, b[i]);
}
return arr;
} else if ("x" in b && "y" in b) {
ASSERT && Vec2.assert(b);
var x = a.q.c * b.x - a.q.s * b.y + a.p.x;
var y = a.q.s * b.x + a.q.c * b.y + a.p.y;
return Vec2.neo(x, y);
} else if ("p" in b && "q" in b) {
ASSERT && Transform.assert(b);
var xf = Transform.identity();
xf.q = Rot.mul(a.q, b.q);
xf.p = Vec2.add(Rot.mul(a.q, b.p), a.p);
return xf;
}
};
Transform.mulT = function(a, b) {
ASSERT && Transform.assert(a);
if ("x" in b && "y" in b) {
ASSERT && Vec2.assert(b);
var px = b.x - a.p.x;
var py = b.y - a.p.y;
var x = a.q.c * px + a.q.s * py;
var y = -a.q.s * px + a.q.c * py;
return Vec2.neo(x, y);
} else if ("p" in b && "q" in b) {
ASSERT && Transform.assert(b);
var xf = Transform.identity();
xf.q.set(Rot.mulT(a.q, b.q));
xf.p.set(Rot.mulT(a.q, Vec2.sub(b.p, a.p)));
return xf;
}
};
},{"../util/common":51,"./Rot":20,"./Vec2":23}],23:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Vec2;
var common = require("../util/common");
var Math = require("./Math");
function Vec2(x, y) {
if (!(this instanceof Vec2)) {
return new Vec2(x, y);
}
if (typeof x === "undefined") {
this.x = 0, this.y = 0;
} else if (typeof x === "object") {
this.x = x.x, this.y = x.y;
} else {
this.x = x, this.y = y;
}
ASSERT && Vec2.assert(this);
}
Vec2.zero = function() {
var obj = Object.create(Vec2.prototype);
obj.x = 0;
obj.y = 0;
return obj;
};
Vec2.neo = function(x, y) {
var obj = Object.create(Vec2.prototype);
obj.x = x;
obj.y = y;
return obj;
};
Vec2.clone = function(v, depricated) {
ASSERT && Vec2.assert(v);
ASSERT && common.assert(!depricated);
return Vec2.neo(v.x, v.y);
};
Vec2.prototype.toString = function() {
return JSON.stringify(this);
};
Vec2.isValid = function(v) {
return v && Math.isFinite(v.x) && Math.isFinite(v.y);
};
Vec2.assert = function(o) {
if (!ASSERT) return;
if (!Vec2.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Vec2!");
}
};
Vec2.prototype.clone = function(depricated) {
return Vec2.clone(this, depricated);
};
Vec2.prototype.setZero = function() {
this.x = 0;
this.y = 0;
return this;
};
Vec2.prototype.set = function(x, y) {
if (typeof x === "object") {
ASSERT && Vec2.assert(x);
this.x = x.x;
this.y = x.y;
} else {
ASSERT && Math.assert(x);
ASSERT && Math.assert(y);
this.x = x;
this.y = y;
}
return this;
};
Vec2.prototype.wSet = function(a, v, b, w) {
ASSERT && Math.assert(a);
ASSERT && Vec2.assert(v);
var x = a * v.x;
var y = a * v.y;
if (typeof b !== "undefined" || typeof w !== "undefined") {
ASSERT && Math.assert(b);
ASSERT && Vec2.assert(w);
x += b * w.x;
y += b * w.y;
}
this.x = x;
this.y = y;
return this;
};
Vec2.prototype.add = function(w) {
ASSERT && Vec2.assert(w);
this.x += w.x;
this.y += w.y;
return this;
};
Vec2.prototype.wAdd = function(a, v, b, w) {
ASSERT && Math.assert(a);
ASSERT && Vec2.assert(v);
var x = a * v.x;
var y = a * v.y;
if (typeof b !== "undefined" || typeof w !== "undefined") {
ASSERT && Math.assert(b);
ASSERT && Vec2.assert(w);
x += b * w.x;
y += b * w.y;
}
this.x += x;
this.y += y;
return this;
};
Vec2.prototype.wSub = function(a, v, b, w) {
ASSERT && Math.assert(a);
ASSERT && Vec2.assert(v);
var x = a * v.x;
var y = a * v.y;
if (typeof b !== "undefined" || typeof w !== "undefined") {
ASSERT && Math.assert(b);
ASSERT && Vec2.assert(w);
x += b * w.x;
y += b * w.y;
}
this.x -= x;
this.y -= y;
return this;
};
Vec2.prototype.sub = function(w) {
ASSERT && Vec2.assert(w);
this.x -= w.x;
this.y -= w.y;
return this;
};
Vec2.prototype.mul = function(m) {
ASSERT && Math.assert(m);
this.x *= m;
this.y *= m;
return this;
};
Vec2.prototype.length = function() {
return Vec2.lengthOf(this);
};
Vec2.prototype.lengthSquared = function() {
return Vec2.lengthSquared(this);
};
Vec2.prototype.normalize = function() {
var length = this.length();
if (length < Math.EPSILON) {
return 0;
}
var invLength = 1 / length;
this.x *= invLength;
this.y *= invLength;
return length;
};
Vec2.lengthOf = function(v) {
ASSERT && Vec2.assert(v);
return Math.sqrt(v.x * v.x + v.y * v.y);
};
Vec2.lengthSquared = function(v) {
ASSERT && Vec2.assert(v);
return v.x * v.x + v.y * v.y;
};
Vec2.distance = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
var dx = v.x - w.x, dy = v.y - w.y;
return Math.sqrt(dx * dx + dy * dy);
};
Vec2.distanceSquared = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
var dx = v.x - w.x, dy = v.y - w.y;
return dx * dx + dy * dy;
};
Vec2.areEqual = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y;
};
Vec2.skew = function(v) {
ASSERT && Vec2.assert(v);
return Vec2.neo(-v.y, v.x);
};
Vec2.dot = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return v.x * w.x + v.y * w.y;
};
Vec2.cross = function(v, w) {
if (typeof w === "number") {
ASSERT && Vec2.assert(v);
ASSERT && Math.assert(w);
return Vec2.neo(w * v.y, -w * v.x);
} else if (typeof v === "number") {
ASSERT && Math.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(-v * w.y, v * w.x);
} else {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return v.x * w.y - v.y * w.x;
}
};
Vec2.addCross = function(a, v, w) {
if (typeof w === "number") {
ASSERT && Vec2.assert(v);
ASSERT && Math.assert(w);
return Vec2.neo(w * v.y + a.x, -w * v.x + a.y);
} else if (typeof v === "number") {
ASSERT && Math.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(-v * w.y + a.x, v * w.x + a.y);
}
ASSERT && common.assert(false);
};
Vec2.add = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(v.x + w.x, v.y + w.y);
};
Vec2.wAdd = function(a, v, b, w) {
var r = Vec2.zero();
r.wAdd(a, v, b, w);
return r;
};
Vec2.sub = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(v.x - w.x, v.y - w.y);
};
Vec2.mul = function(a, b) {
if (typeof a === "object") {
ASSERT && Vec2.assert(a);
ASSERT && Math.assert(b);
return Vec2.neo(a.x * b, a.y * b);
} else if (typeof b === "object") {
ASSERT && Math.assert(a);
ASSERT && Vec2.assert(b);
return Vec2.neo(a * b.x, a * b.y);
}
};
Vec2.prototype.neg = function() {
this.x = -this.x;
this.y = -this.y;
return this;
};
Vec2.neg = function(v) {
ASSERT && Vec2.assert(v);
return Vec2.neo(-v.x, -v.y);
};
Vec2.abs = function(v) {
ASSERT && Vec2.assert(v);
return Vec2.neo(Math.abs(v.x), Math.abs(v.y));
};
Vec2.mid = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo((v.x + w.x) * .5, (v.y + w.y) * .5);
};
Vec2.upper = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(Math.max(v.x, w.x), Math.max(v.y, w.y));
};
Vec2.lower = function(v, w) {
ASSERT && Vec2.assert(v);
ASSERT && Vec2.assert(w);
return Vec2.neo(Math.min(v.x, w.x), Math.min(v.y, w.y));
};
Vec2.prototype.clamp = function(max) {
var lengthSqr = this.x * this.x + this.y * this.y;
if (lengthSqr > max * max) {
var invLength = Math.invSqrt(lengthSqr);
this.x *= invLength * max;
this.y *= invLength * max;
}
return this;
};
Vec2.clamp = function(v, max) {
v = Vec2.neo(v.x, v.y);
v.clamp(max);
return v;
};
},{"../util/common":51,"./Math":18}],24:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Vec3;
var common = require("../util/common");
var Math = require("./Math");
function Vec3(x, y, z) {
if (!(this instanceof Vec3)) {
return new Vec3(x, y, z);
}
if (typeof x === "undefined") {
this.x = 0, this.y = 0, this.z = 0;
} else if (typeof x === "object") {
this.x = x.x, this.y = x.y, this.z = x.z;
} else {
this.x = x, this.y = y, this.z = z;
}
ASSERT && Vec3.assert(this);
}
Vec3.prototype.toString = function() {
return JSON.stringify(this);
};
Vec3.isValid = function(v) {
return v && Math.isFinite(v.x) && Math.isFinite(v.y) && Math.isFinite(v.z);
};
Vec3.assert = function(o) {
if (!ASSERT) return;
if (!Vec3.isValid(o)) {
DEBUG && common.debug(o);
throw new Error("Invalid Vec3!");
}
};
Vec3.prototype.setZero = function() {
this.x = 0;
this.y = 0;
this.z = 0;
return this;
};
Vec3.prototype.set = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
};
Vec3.prototype.add = function(w) {
this.x += w.x;
this.y += w.y;
this.z += w.z;
return this;
};
Vec3.prototype.sub = function(w) {
this.x -= w.x;
this.y -= w.y;
this.z -= w.z;
return this;
};
Vec3.prototype.mul = function(m) {
this.x *= m;
this.y *= m;
this.z *= m;
return this;
};
Vec3.areEqual = function(v, w) {
return v == w || typeof w === "object" && w !== null && v.x == w.x && v.y == w.y && v.z == w.z;
};
Vec3.dot = function(v, w) {
return v.x * w.x + v.y * w.y + v.z * w.z;
};
Vec3.cross = function(v, w) {
return new Vec3(v.y * w.z - v.z * w.y, v.z * w.x - v.x * w.z, v.x * w.y - v.y * w.x);
};
Vec3.add = function(v, w) {
return new Vec3(v.x + w.x, v.y + w.y, v.z + w.z);
};
Vec3.sub = function(v, w) {
return new Vec3(v.x - w.x, v.y - w.y, v.z - w.z);
};
Vec3.mul = function(v, m) {
return new Vec3(m * v.x, m * v.y, m * v.z);
};
Vec3.prototype.neg = function(m) {
this.x = -this.x;
this.y = -this.y;
this.z = -this.z;
return this;
};
Vec3.neg = function(v) {
return new Vec3(-v.x, -v.y, -v.z);
};
},{"../util/common":51,"./Math":18}],25:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Velocity;
var Vec2 = require("./Vec2");
function Velocity() {
this.v = Vec2.zero();
this.w = 0;
}
},{"./Vec2":23}],26:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
exports.toString = function(newline) {
newline = typeof newline === "string" ? newline : "\n";
var string = "";
for (var name in this) {
if (typeof this[name] !== "function" && typeof this[name] !== "object") {
string += name + ": " + this[name] + newline;
}
}
return string;
};
},{}],27:[function(require,module,exports){
exports.internal = {};
exports.Math = require("./common/Math");
exports.Vec2 = require("./common/Vec2");
exports.Transform = require("./common/Transform");
exports.Rot = require("./common/Rot");
exports.AABB = require("./collision/AABB");
exports.Shape = require("./Shape");
exports.Fixture = require("./Fixture");
exports.Body = require("./Body");
exports.Contact = require("./Contact");
exports.Joint = require("./Joint");
exports.World = require("./World");
exports.Circle = require("./shape/CircleShape");
exports.Edge = require("./shape/EdgeShape");
exports.Polygon = require("./shape/PolygonShape");
exports.Chain = require("./shape/ChainShape");
exports.Box = require("./shape/BoxShape");
require("./shape/CollideCircle");
require("./shape/CollideEdgeCircle");
exports.internal.CollidePolygons = require("./shape/CollidePolygon");
require("./shape/CollideCirclePolygone");
require("./shape/CollideEdgePolygon");
exports.DistanceJoint = require("./joint/DistanceJoint");
exports.FrictionJoint = require("./joint/FrictionJoint");
exports.GearJoint = require("./joint/GearJoint");
exports.MotorJoint = require("./joint/MotorJoint");
exports.MouseJoint = require("./joint/MouseJoint");
exports.PrismaticJoint = require("./joint/PrismaticJoint");
exports.PulleyJoint = require("./joint/PulleyJoint");
exports.RevoluteJoint = require("./joint/RevoluteJoint");
exports.RopeJoint = require("./joint/RopeJoint");
exports.WeldJoint = require("./joint/WeldJoint");
exports.WheelJoint = require("./joint/WheelJoint");
exports.internal.Sweep = require("./common/Sweep");
exports.internal.stats = require("./common/stats");
exports.internal.Manifold = require("./Manifold");
exports.internal.Distance = require("./collision/Distance");
exports.internal.TimeOfImpact = require("./collision/TimeOfImpact");
exports.internal.DynamicTree = require("./collision/DynamicTree");
exports.internal.Settings = require("./Settings");
},{"./Body":2,"./Contact":3,"./Fixture":4,"./Joint":5,"./Manifold":6,"./Settings":7,"./Shape":8,"./World":10,"./collision/AABB":11,"./collision/Distance":13,"./collision/DynamicTree":14,"./collision/TimeOfImpact":15,"./common/Math":18,"./common/Rot":20,"./common/Sweep":21,"./common/Transform":22,"./common/Vec2":23,"./common/stats":26,"./joint/DistanceJoint":28,"./joint/FrictionJoint":29,"./joint/GearJoint":30,"./joint/MotorJoint":31,"./joint/MouseJoint":32,"./joint/PrismaticJoint":33,"./joint/PulleyJoint":34,"./joint/RevoluteJoint":35,"./joint/RopeJoint":36,"./joint/WeldJoint":37,"./joint/WheelJoint":38,"./shape/BoxShape":39,"./shape/ChainShape":40,"./shape/CircleShape":41,"./shape/CollideCircle":42,"./shape/CollideCirclePolygone":43,"./shape/CollideEdgeCircle":44,"./shape/CollideEdgePolygon":45,"./shape/CollidePolygon":46,"./shape/EdgeShape":47,"./shape/PolygonShape":48}],28:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = DistanceJoint;
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
DistanceJoint.TYPE = "distance-joint";
DistanceJoint._super = Joint;
DistanceJoint.prototype = create(DistanceJoint._super.prototype);
var DistanceJointDef = {
frequencyHz: 0,
dampingRatio: 0
};
function DistanceJoint(def, bodyA, anchorA, bodyB, anchorB) {
if (!(this instanceof DistanceJoint)) {
return new DistanceJoint(def, bodyA, anchorA, bodyB, anchorB);
}
def = options(def, DistanceJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = DistanceJoint.TYPE;
this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchorA);
this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchorB);
this.m_length = Vec2.distance(anchorB, anchorA);
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = 0;
this.m_gamma = 0;
this.m_bias = 0;
this.m_u;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
}
DistanceJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
DistanceJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
DistanceJoint.prototype.setLength = function(length) {
this.m_length = length;
};
DistanceJoint.prototype.getLength = function() {
return this.m_length;
};
DistanceJoint.prototype.setFrequency = function(hz) {
this.m_frequencyHz = hz;
};
DistanceJoint.prototype.getFrequency = function() {
return this.m_frequencyHz;
};
DistanceJoint.prototype.setDampingRatio = function(ratio) {
this.m_dampingRatio = ratio;
};
DistanceJoint.prototype.getDampingRatio = function() {
return this.m_dampingRatio;
};
DistanceJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
DistanceJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
DistanceJoint.prototype.getReactionForce = function(inv_dt) {
var F = Vec2.mul(inv_dt * this.m_impulse, this.m_u);
return F;
};
DistanceJoint.prototype.getReactionTorque = function(inv_dt) {
return 0;
};
DistanceJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
this.m_u = Vec2.sub(Vec2.add(cB, this.m_rB), Vec2.add(cA, this.m_rA));
var length = this.m_u.length();
if (length > Settings.linearSlop) {
this.m_u.mul(1 / length);
} else {
this.m_u.set(0, 0);
}
var crAu = Vec2.cross(this.m_rA, this.m_u);
var crBu = Vec2.cross(this.m_rB, this.m_u);
var invMass = this.m_invMassA + this.m_invIA * crAu * crAu + this.m_invMassB + this.m_invIB * crBu * crBu;
this.m_mass = invMass != 0 ? 1 / invMass : 0;
if (this.m_frequencyHz > 0) {
var C = length - this.m_length;
var omega = 2 * Math.PI * this.m_frequencyHz;
var d = 2 * this.m_mass * this.m_dampingRatio * omega;
var k = this.m_mass * omega * omega;
var h = step.dt;
this.m_gamma = h * (d + h * k);
this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0;
this.m_bias = C * h * k * this.m_gamma;
invMass += this.m_gamma;
this.m_mass = invMass != 0 ? 1 / invMass : 0;
} else {
this.m_gamma = 0;
this.m_bias = 0;
}
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
var P = Vec2.mul(this.m_impulse, this.m_u);
vA.wSub(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.wAdd(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
} else {
this.m_impulse = 0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
DistanceJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA));
var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB));
var Cdot = Vec2.dot(this.m_u, vpB) - Vec2.dot(this.m_u, vpA);
var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse);
this.m_impulse += impulse;
var P = Vec2.mul(impulse, this.m_u);
vA.wSub(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.wAdd(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
DistanceJoint.prototype.solvePositionConstraints = function(step) {
if (this.m_frequencyHz > 0) {
return true;
}
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA);
var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB);
var u = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA));
var length = u.normalize();
var C = length - this.m_length;
C = Math.clamp(C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection);
var impulse = -this.m_mass * C;
var P = Vec2.mul(impulse, u);
cA.wSub(this.m_invMassA, P);
aA -= this.m_invIA * Vec2.cross(rA, P);
cB.wAdd(this.m_invMassB, P);
aB += this.m_invIB * Vec2.cross(rB, P);
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return Math.abs(C) < Settings.linearSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],29:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = FrictionJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
FrictionJoint.TYPE = "friction-joint";
FrictionJoint._super = Joint;
FrictionJoint.prototype = create(FrictionJoint._super.prototype);
var FrictionJointDef = {
maxForce: 0,
maxTorque: 0
};
function FrictionJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof FrictionJoint)) {
return new FrictionJoint(def, bodyA, bodyB, anchor);
}
def = options(def, FrictionJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = FrictionJoint.TYPE;
if (anchor) {
this.m_localAnchorA = bodyA.getLocalPoint(anchor);
this.m_localAnchorB = bodyB.getLocalPoint(anchor);
} else {
this.m_localAnchorA = Vec2.zero();
this.m_localAnchorB = Vec2.zero();
}
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_linearMass;
this.m_angularMass;
}
FrictionJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
FrictionJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
FrictionJoint.prototype.setMaxForce = function(force) {
ASSERT && common.assert(IsValid(force) && force >= 0);
this.m_maxForce = force;
};
FrictionJoint.prototype.getMaxForce = function() {
return this.m_maxForce;
};
FrictionJoint.prototype.setMaxTorque = function(torque) {
ASSERT && common.assert(IsValid(torque) && torque >= 0);
this.m_maxTorque = torque;
};
FrictionJoint.prototype.getMaxTorque = function() {
return this.m_maxTorque;
};
FrictionJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
FrictionJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
FrictionJoint.prototype.getReactionForce = function(inv_dt) {
return inv_dt * this.m_linearImpulse;
};
FrictionJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_angularImpulse;
};
FrictionJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA), qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var mA = this.m_invMassA, mB = this.m_invMassB;
var iA = this.m_invIA, iB = this.m_invIB;
var K = new Mat22();
K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y;
K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x;
this.m_linearMass = K.getInverse();
this.m_angularMass = iA + iB;
if (this.m_angularMass > 0) {
this.m_angularMass = 1 / this.m_angularMass;
}
if (step.warmStarting) {
this.m_linearImpulse.mul(step.dtRatio);
this.m_angularImpulse *= step.dtRatio;
var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse);
} else {
this.m_linearImpulse.setZero();
this.m_angularImpulse = 0;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
FrictionJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var mA = this.m_invMassA, mB = this.m_invMassB;
var iA = this.m_invIA, iB = this.m_invIB;
var h = step.dt;
{
var Cdot = wB - wA;
var impulse = -this.m_angularMass * Cdot;
var oldImpulse = this.m_angularImpulse;
var maxImpulse = h * this.m_maxTorque;
this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = this.m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
{
var Cdot = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, this.m_rB)), Vec2.add(vA, Vec2.cross(wA, this.m_rA)));
var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot));
var oldImpulse = this.m_linearImpulse;
this.m_linearImpulse.add(impulse);
var maxImpulse = h * this.m_maxForce;
if (this.m_linearImpulse.lengthSquared() > maxImpulse * maxImpulse) {
this.m_linearImpulse.normalize();
this.m_linearImpulse.mul(maxImpulse);
}
impulse = Vec2.sub(this.m_linearImpulse, oldImpulse);
vA.wSub(mA, impulse);
wA -= iA * Vec2.cross(this.m_rA, impulse);
vB.wAdd(mB, impulse);
wB += iB * Vec2.cross(this.m_rB, impulse);
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
FrictionJoint.prototype.solvePositionConstraints = function(step) {
return true;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],30:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = GearJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
var RevoluteJoint = require("./RevoluteJoint");
var PrismaticJoint = require("./PrismaticJoint");
GearJoint.TYPE = "gear-joint";
GearJoint._super = Joint;
GearJoint.prototype = create(GearJoint._super.prototype);
var GearJointDef = {
ratio: 1
};
function GearJoint(def, bodyA, bodyB, joint1, joint2, ratio) {
if (!(this instanceof GearJoint)) {
return new GearJoint(def, bodyA, bodyB, joint1, joint2, ratio);
}
def = options(def, GearJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = GearJoint.TYPE;
ASSERT && common.assert(joint1.m_type == RevoluteJoint.TYPE || joint1.m_type == PrismaticJoint.TYPE);
ASSERT && common.assert(joint2.m_type == RevoluteJoint.TYPE || joint2.m_type == PrismaticJoint.TYPE);
this.m_joint1 = joint1;
this.m_joint2 = joint2;
this.m_type1 = this.m_joint1.getType();
this.m_type2 = this.m_joint2.getType();
var coordinateA, coordinateB;
this.m_bodyC = this.m_joint1.getBodyA();
this.m_bodyA = this.m_joint1.getBodyB();
var xfA = this.m_bodyA.m_xf;
var aA = this.m_bodyA.m_sweep.a;
var xfC = this.m_bodyC.m_xf;
var aC = this.m_bodyC.m_sweep.a;
if (this.m_type1 == RevoluteJoint.TYPE) {
var revolute = joint1;
this.m_localAnchorC = revolute.m_localAnchorA;
this.m_localAnchorA = revolute.m_localAnchorB;
this.m_referenceAngleA = revolute.m_referenceAngle;
this.m_localAxisC = Vec2.zero();
coordinateA = aA - aC - this.m_referenceAngleA;
} else {
var prismatic = joint1;
this.m_localAnchorC = prismatic.m_localAnchorA;
this.m_localAnchorA = prismatic.m_localAnchorB;
this.m_referenceAngleA = prismatic.m_referenceAngle;
this.m_localAxisC = prismatic.m_localXAxisA;
var pC = this.m_localAnchorC;
var pA = Rot.mulT(xfC.q, Vec2.add(Rot.mul(xfA.q, this.m_localAnchorA), Vec2.sub(xfA.p, xfC.p)));
coordinateA = Vec2.dot(pA, this.m_localAxisC) - Vec2.dot(pC, this.m_localAxisC);
}
this.m_bodyD = this.m_joint2.getBodyA();
this.m_bodyB = this.m_joint2.getBodyB();
var xfB = this.m_bodyB.m_xf;
var aB = this.m_bodyB.m_sweep.a;
var xfD = this.m_bodyD.m_xf;
var aD = this.m_bodyD.m_sweep.a;
if (this.m_type2 == RevoluteJoint.TYPE) {
var revolute = joint2;
this.m_localAnchorD = revolute.m_localAnchorA;
this.m_localAnchorB = revolute.m_localAnchorB;
this.m_referenceAngleB = revolute.m_referenceAngle;
this.m_localAxisD = Vec2.zero();
coordinateB = aB - aD - this.m_referenceAngleB;
} else {
var prismatic = joint2;
this.m_localAnchorD = prismatic.m_localAnchorA;
this.m_localAnchorB = prismatic.m_localAnchorB;
this.m_referenceAngleB = prismatic.m_referenceAngle;
this.m_localAxisD = prismatic.m_localXAxisA;
var pD = this.m_localAnchorD;
var pB = Rot.mulT(xfD.q, Vec2.add(Rot.mul(xfB.q, this.m_localAnchorB), Vec2.sub(xfB.p, xfD.p)));
coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD);
}
this.m_ratio = ratio || def.ratio;
this.m_constant = coordinateA + this.m_ratio * coordinateB;
this.m_impulse = 0;
this.m_lcA, this.m_lcB, this.m_lcC, this.m_lcD;
this.m_mA, this.m_mB, this.m_mC, this.m_mD;
this.m_iA, this.m_iB, this.m_iC, this.m_iD;
this.m_JvAC, this.m_JvBD;
this.m_JwA, this.m_JwB, this.m_JwC, this.m_JwD;
this.m_mass;
}
GearJoint.prototype.getJoint1 = function() {
return this.m_joint1;
};
GearJoint.prototype.getJoint2 = function() {
return this.m_joint2;
};
GearJoint.prototype.setRatio = function(ratio) {
ASSERT && common.assert(IsValid(ratio));
this.m_ratio = ratio;
};
GearJoint.prototype.setRatio = function() {
return this.m_ratio;
};
GearJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
GearJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
GearJoint.prototype.getReactionForce = function(inv_dt) {
var P = this.m_impulse * this.m_JvAC;
return inv_dt * P;
};
GearJoint.prototype.getReactionTorque = function(inv_dt) {
var L = this.m_impulse * this.m_JwA;
return inv_dt * L;
};
GearJoint.prototype.initVelocityConstraints = function(step) {
this.m_lcA = this.m_bodyA.m_sweep.localCenter;
this.m_lcB = this.m_bodyB.m_sweep.localCenter;
this.m_lcC = this.m_bodyC.m_sweep.localCenter;
this.m_lcD = this.m_bodyD.m_sweep.localCenter;
this.m_mA = this.m_bodyA.m_invMass;
this.m_mB = this.m_bodyB.m_invMass;
this.m_mC = this.m_bodyC.m_invMass;
this.m_mD = this.m_bodyD.m_invMass;
this.m_iA = this.m_bodyA.m_invI;
this.m_iB = this.m_bodyB.m_invI;
this.m_iC = this.m_bodyC.m_invI;
this.m_iD = this.m_bodyD.m_invI;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var aC = this.m_bodyC.c_position.a;
var vC = this.m_bodyC.c_velocity.v;
var wC = this.m_bodyC.c_velocity.w;
var aD = this.m_bodyD.c_position.a;
var vD = this.m_bodyD.c_velocity.v;
var wD = this.m_bodyD.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var qC = Rot.neo(aC);
var qD = Rot.neo(aD);
this.m_mass = 0;
if (this.m_type1 == RevoluteJoint.TYPE) {
this.m_JvAC = Vec2.zero();
this.m_JwA = 1;
this.m_JwC = 1;
this.m_mass += this.m_iA + this.m_iC;
} else {
var u = Rot.mul(qC, this.m_localAxisC);
var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC);
var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA);
this.m_JvAC = u;
this.m_JwC = Vec2.cross(rC, u);
this.m_JwA = Vec2.cross(rA, u);
this.m_mass += this.m_mC + this.m_mA + this.m_iC * this.m_JwC * this.m_JwC + this.m_iA * this.m_JwA * this.m_JwA;
}
if (this.m_type2 == RevoluteJoint.TYPE) {
this.m_JvBD = Vec2.zero();
this.m_JwB = this.m_ratio;
this.m_JwD = this.m_ratio;
this.m_mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD);
} else {
var u = Rot.mul(qD, this.m_localAxisD);
var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD);
var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB);
this.m_JvBD = Vec2.mul(this.m_ratio, u);
this.m_JwD = this.m_ratio * Vec2.cross(rD, u);
this.m_JwB = this.m_ratio * Vec2.cross(rB, u);
this.m_mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * this.m_JwD * this.m_JwD + this.m_iB * this.m_JwB * this.m_JwB;
}
this.m_mass = this.m_mass > 0 ? 1 / this.m_mass : 0;
if (step.warmStarting) {
vA.wAdd(this.m_mA * this.m_impulse, this.m_JvAC);
wA += this.m_iA * this.m_impulse * this.m_JwA;
vB.wAdd(this.m_mB * this.m_impulse, this.m_JvBD);
wB += this.m_iB * this.m_impulse * this.m_JwB;
vC.wSub(this.m_mC * this.m_impulse, this.m_JvAC);
wC -= this.m_iC * this.m_impulse * this.m_JwC;
vD.wSub(this.m_mD * this.m_impulse, this.m_JvBD);
wD -= this.m_iD * this.m_impulse * this.m_JwD;
} else {
this.m_impulse = 0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
this.m_bodyC.c_velocity.v.set(vC);
this.m_bodyC.c_velocity.w = wC;
this.m_bodyD.c_velocity.v.set(vD);
this.m_bodyD.c_velocity.w = wD;
};
GearJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var vC = this.m_bodyC.c_velocity.v;
var wC = this.m_bodyC.c_velocity.w;
var vD = this.m_bodyD.c_velocity.v;
var wD = this.m_bodyD.c_velocity.w;
var Cdot = Vec2.dot(this.m_JvAC, vA) - Vec2.dot(this.m_JvAC, vC) + Vec2.dot(this.m_JvBD, vB) - Vec2.dot(this.m_JvBD, vD);
Cdot += this.m_JwA * wA - this.m_JwC * wC + (this.m_JwB * wB - this.m_JwD * wD);
var impulse = -this.m_mass * Cdot;
this.m_impulse += impulse;
vA.wAdd(this.m_mA * impulse, this.m_JvAC);
wA += this.m_iA * impulse * this.m_JwA;
vB.wAdd(this.m_mB * impulse, this.m_JvBD);
wB += this.m_iB * impulse * this.m_JwB;
vC.wSub(this.m_mC * impulse, this.m_JvAC);
wC -= this.m_iC * impulse * this.m_JwC;
vD.wSub(this.m_mD * impulse, this.m_JvBD);
wD -= this.m_iD * impulse * this.m_JwD;
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
this.m_bodyC.c_velocity.v.set(vC);
this.m_bodyC.c_velocity.w = wC;
this.m_bodyD.c_velocity.v.set(vD);
this.m_bodyD.c_velocity.w = wD;
};
GearJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var cC = this.m_bodyC.c_position.c;
var aC = this.m_bodyC.c_position.a;
var cD = this.m_bodyD.c_position.c;
var aD = this.m_bodyD.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var qC = Rot.neo(aC);
var qD = Rot.neo(aD);
var linearError = 0;
var coordinateA, coordinateB;
var JvAC, JvBD;
var JwA, JwB, JwC, JwD;
var mass = 0;
if (this.m_type1 == RevoluteJoint.TYPE) {
JvAC = Vec2.zero();
JwA = 1;
JwC = 1;
mass += this.m_iA + this.m_iC;
coordinateA = aA - aC - this.m_referenceAngleA;
} else {
var u = Rot.mul(qC, this.m_localAxisC);
var rC = Rot.mulSub(qC, this.m_localAnchorC, this.m_lcC);
var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_lcA);
JvAC = u;
JwC = Vec2.cross(rC, u);
JwA = Vec2.cross(rA, u);
mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA;
var pC = this.m_localAnchorC - this.m_lcC;
var pA = Rot.mulT(qC, Vec2.add(rA, Vec2.sub(cA, cC)));
coordinateA = Dot(pA - pC, this.m_localAxisC);
}
if (this.m_type2 == RevoluteJoint.TYPE) {
JvBD = Vec2.zero();
JwB = this.m_ratio;
JwD = this.m_ratio;
mass += this.m_ratio * this.m_ratio * (this.m_iB + this.m_iD);
coordinateB = aB - aD - this.m_referenceAngleB;
} else {
var u = Rot.mul(qD, this.m_localAxisD);
var rD = Rot.mulSub(qD, this.m_localAnchorD, this.m_lcD);
var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_lcB);
JvBD = Vec2.mul(this.m_ratio, u);
JwD = this.m_ratio * Vec2.cross(rD, u);
JwB = this.m_ratio * Vec2.cross(rB, u);
mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB;
var pD = Vec2.sub(this.m_localAnchorD, this.m_lcD);
var pB = Rot.mulT(qD, Vec2.add(rB, Vec2.sub(cB, cD)));
coordinateB = Vec2.dot(pB, this.m_localAxisD) - Vec2.dot(pD, this.m_localAxisD);
}
var C = coordinateA + this.m_ratio * coordinateB - this.m_constant;
var impulse = 0;
if (mass > 0) {
impulse = -C / mass;
}
cA.wAdd(this.m_mA * impulse, JvAC);
aA += this.m_iA * impulse * JwA;
cB.wAdd(this.m_mB * impulse, JvBD);
aB += this.m_iB * impulse * JwB;
cC.wAdd(this.m_mC * impulse, JvAC);
aC -= this.m_iC * impulse * JwC;
cD.wAdd(this.m_mD * impulse, JvBD);
aD -= this.m_iD * impulse * JwD;
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
this.m_bodyC.c_position.c.set(cC);
this.m_bodyC.c_position.a = aC;
this.m_bodyD.c_position.c.set(cD);
this.m_bodyD.c_position.a = aD;
return linearError < Settings.linearSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53,"./PrismaticJoint":33,"./RevoluteJoint":35}],31:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = MotorJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
MotorJoint.TYPE = "motor-joint";
MotorJoint._super = Joint;
MotorJoint.prototype = create(MotorJoint._super.prototype);
var MotorJointDef = {
maxForce: 1,
maxTorque: 1,
correctionFactor: .3
};
function MotorJoint(def, bodyA, bodyB) {
if (!(this instanceof MotorJoint)) {
return new MotorJoint(def, bodyA, bodyB);
}
def = options(def, MotorJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = MotorJoint.TYPE;
var xB = bodyB.getPosition();
this.m_linearOffset = bodyA.getLocalPoint(xB);
var angleA = bodyA.getAngle();
var angleB = bodyB.getAngle();
this.m_angularOffset = angleB - angleA;
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
this.m_correctionFactor = def.correctionFactor;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_linearError;
this.m_angularError;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_linearMass;
this.m_angularMass;
}
MotorJoint.prototype.setMaxForce = function(force) {
ASSERT && common.assert(IsValid(force) && force >= 0);
this.m_maxForce = force;
};
MotorJoint.prototype.getMaxForce = function() {
return this.m_maxForce;
};
MotorJoint.prototype.setMaxTorque = function(torque) {
ASSERT && common.assert(IsValid(torque) && torque >= 0);
this.m_maxTorque = torque;
};
MotorJoint.prototype.getMaxTorque = function() {
return this.m_maxTorque;
};
MotorJoint.prototype.setCorrectionFactor = function(factor) {
ASSERT && common.assert(IsValid(factor) && 0 <= factor && factor <= 1);
this.m_correctionFactor = factor;
};
MotorJoint.prototype.getCorrectionFactor = function() {
return this.m_correctionFactor;
};
MotorJoint.prototype.setLinearOffset = function(linearOffset) {
if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_linearOffset = linearOffset;
}
};
MotorJoint.prototype.getLinearOffset = function() {
return this.m_linearOffset;
};
MotorJoint.prototype.setAngularOffset = function(angularOffset) {
if (angularOffset != this.m_angularOffset) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_angularOffset = angularOffset;
}
};
MotorJoint.prototype.getAngularOffset = function() {
return this.m_angularOffset;
};
MotorJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getPosition();
};
MotorJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getPosition();
};
MotorJoint.prototype.getReactionForce = function(inv_dt) {
return inv_dt * this.m_linearImpulse;
};
MotorJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_angularImpulse;
};
MotorJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA), qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.neg(this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.neg(this.m_localCenterB));
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var K = new Mat22();
K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y;
K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x;
this.m_linearMass = K.getInverse();
this.m_angularMass = iA + iB;
if (this.m_angularMass > 0) {
this.m_angularMass = 1 / this.m_angularMass;
}
this.m_linearError = Vec2.zero();
this.m_linearError.wAdd(1, cB, 1, this.m_rB);
this.m_linearError.wSub(1, cA, 1, this.m_rA);
this.m_linearError.sub(Rot.mul(qA, this.m_linearOffset));
this.m_angularError = aB - aA - this.m_angularOffset;
if (step.warmStarting) {
this.m_linearImpulse.mul(step.dtRatio);
this.m_angularImpulse *= step.dtRatio;
var P = Vec2.neo(this.m_linearImpulse.x, this.m_linearImpulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_angularImpulse);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + this.m_angularImpulse);
} else {
this.m_linearImpulse.setZero();
this.m_angularImpulse = 0;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
MotorJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var mA = this.m_invMassA, mB = this.m_invMassB;
var iA = this.m_invIA, iB = this.m_invIB;
var h = step.dt;
var inv_h = step.inv_dt;
{
var Cdot = wB - wA + inv_h * this.m_correctionFactor * this.m_angularError;
var impulse = -this.m_angularMass * Cdot;
var oldImpulse = this.m_angularImpulse;
var maxImpulse = h * this.m_maxTorque;
this.m_angularImpulse = Math.clamp(this.m_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = this.m_angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
{
var Cdot = Vec2.zero();
Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA));
Cdot.wAdd(inv_h * this.m_correctionFactor, this.m_linearError);
var impulse = Vec2.neg(Mat22.mul(this.m_linearMass, Cdot));
var oldImpulse = Vec2.clone(this.m_linearImpulse);
this.m_linearImpulse.add(impulse);
var maxImpulse = h * this.m_maxForce;
this.m_linearImpulse.clamp(maxImpulse);
impulse = Vec2.sub(this.m_linearImpulse, oldImpulse);
vA.wSub(mA, impulse);
wA -= iA * Vec2.cross(this.m_rA, impulse);
vB.wAdd(mB, impulse);
wB += iB * Vec2.cross(this.m_rB, impulse);
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
MotorJoint.prototype.solvePositionConstraints = function(step) {
return true;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],32:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = MouseJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
MouseJoint.TYPE = "mouse-joint";
MouseJoint._super = Joint;
MouseJoint.prototype = create(MouseJoint._super.prototype);
var MouseJointDef = {
maxForce: 0,
frequencyHz: 5,
dampingRatio: .7
};
function MouseJoint(def, bodyA, bodyB, target) {
if (!(this instanceof MouseJoint)) {
return new MouseJoint(def, bodyA, bodyB, target);
}
def = options(def, MouseJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = MouseJoint.TYPE;
ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0);
ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0);
ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0);
this.m_targetA = Vec2.clone(target);
this.m_localAnchorB = Transform.mulT(this.m_bodyB.getTransform(), this.m_targetA);
this.m_maxForce = def.maxForce;
this.m_impulse = Vec2.zero();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_beta = 0;
this.m_gamma = 0;
this.m_rB = Vec2.zero();
this.m_localCenterB = Vec2.zero();
this.m_invMassB = 0;
this.m_invIB = 0;
this.mass = new Mat22();
this.m_C = Vec2.zero();
}
MouseJoint.prototype.setTarget = function(target) {
if (this.m_bodyB.isAwake() == false) {
this.m_bodyB.setAwake(true);
}
this.m_targetA = Vec2.clone(target);
};
MouseJoint.prototype.getTarget = function() {
return this.m_targetA;
};
MouseJoint.prototype.setMaxForce = function(force) {
this.m_maxForce = force;
};
MouseJoint.getMaxForce = function() {
return this.m_maxForce;
};
MouseJoint.prototype.setFrequency = function(hz) {
this.m_frequencyHz = hz;
};
MouseJoint.prototype.getFrequency = function() {
return this.m_frequencyHz;
};
MouseJoint.prototype.setDampingRatio = function(ratio) {
this.m_dampingRatio = ratio;
};
MouseJoint.prototype.getDampingRatio = function() {
return this.m_dampingRatio;
};
MouseJoint.prototype.getAnchorA = function() {
return Vec2.clone(this.m_targetA);
};
MouseJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
MouseJoint.prototype.getReactionForce = function(inv_dt) {
return Vec2.mul(inv_dt, this.m_impulse);
};
MouseJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * 0;
};
MouseJoint.prototype.shiftOrigin = function(newOrigin) {
this.m_targetA.sub(newOrigin);
};
MouseJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIB = this.m_bodyB.m_invI;
var position = this.m_bodyB.c_position;
var velocity = this.m_bodyB.c_velocity;
var cB = position.c;
var aB = position.a;
var vB = velocity.v;
var wB = velocity.w;
var qB = Rot.neo(aB);
var mass = this.m_bodyB.getMass();
var omega = 2 * Math.PI * this.m_frequencyHz;
var d = 2 * mass * this.m_dampingRatio * omega;
var k = mass * (omega * omega);
var h = step.dt;
ASSERT && common.assert(d + h * k > Math.EPSILON);
this.m_gamma = h * (d + h * k);
if (this.m_gamma != 0) {
this.m_gamma = 1 / this.m_gamma;
}
this.m_beta = h * k * this.m_gamma;
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var K = new Mat22();
K.ex.x = this.m_invMassB + this.m_invIB * this.m_rB.y * this.m_rB.y + this.m_gamma;
K.ex.y = -this.m_invIB * this.m_rB.x * this.m_rB.y;
K.ey.x = K.ex.y;
K.ey.y = this.m_invMassB + this.m_invIB * this.m_rB.x * this.m_rB.x + this.m_gamma;
this.m_mass = K.getInverse();
this.m_C.set(cB);
this.m_C.wAdd(1, this.m_rB, -1, this.m_targetA);
this.m_C.mul(this.m_beta);
wB *= .98;
if (step.warmStarting) {
this.m_impulse.mul(step.dtRatio);
vB.wAdd(this.m_invMassB, this.m_impulse);
wB += this.m_invIB * Vec2.cross(this.m_rB, this.m_impulse);
} else {
this.m_impulse.setZero();
}
velocity.v.set(vB);
velocity.w = wB;
};
MouseJoint.prototype.solveVelocityConstraints = function(step) {
var velocity = this.m_bodyB.c_velocity;
var vB = Vec2.clone(velocity.v);
var wB = velocity.w;
var Cdot = Vec2.cross(wB, this.m_rB);
Cdot.add(vB);
Cdot.wAdd(1, this.m_C, this.m_gamma, this.m_impulse);
Cdot.neg();
var impulse = Mat22.mul(this.m_mass, Cdot);
var oldImpulse = Vec2.clone(this.m_impulse);
this.m_impulse.add(impulse);
var maxImpulse = step.dt * this.m_maxForce;
this.m_impulse.clamp(maxImpulse);
impulse = Vec2.sub(this.m_impulse, oldImpulse);
vB.wAdd(this.m_invMassB, impulse);
wB += this.m_invIB * Vec2.cross(this.m_rB, impulse);
velocity.v.set(vB);
velocity.w = wB;
};
MouseJoint.prototype.solvePositionConstraints = function(step) {
return true;
};
},{"../Joint":5,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],33:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = PrismaticJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
var inactiveLimit = 0;
var atLowerLimit = 1;
var atUpperLimit = 2;
var equalLimits = 3;
PrismaticJoint.TYPE = "prismatic-joint";
PrismaticJoint._super = Joint;
PrismaticJoint.prototype = create(PrismaticJoint._super.prototype);
var PrismaticJointDef = {
enableLimit: false,
lowerTranslation: 0,
upperTranslation: 0,
enableMotor: false,
maxMotorForce: 0,
motorSpeed: 0
};
function PrismaticJoint(def, bodyA, bodyB, anchor, axis) {
if (!(this instanceof PrismaticJoint)) {
return new PrismaticJoint(def, bodyA, bodyB, anchor, axis);
}
def = options(def, PrismaticJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = PrismaticJoint.TYPE;
this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor);
this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor);
this.m_localXAxisA = def.localAxisA || bodyA.getLocalVector(axis);
this.m_localXAxisA.normalize();
this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA);
this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = Vec3();
this.m_motorMass = 0;
this.m_motorImpulse = 0;
this.m_lowerTranslation = def.lowerTranslation;
this.m_upperTranslation = def.upperTranslation;
this.m_maxMotorForce = def.maxMotorForce;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
this.m_limitState = inactiveLimit;
this.m_axis = Vec2.zero();
this.m_perp = Vec2.zero();
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_axis, this.m_perp;
this.m_s1, this.m_s2;
this.m_a1, this.m_a2;
this.m_K = new Mat33();
this.m_motorMass;
}
PrismaticJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
PrismaticJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
PrismaticJoint.prototype.getLocalAxisA = function() {
return this.m_localXAxisA;
};
PrismaticJoint.prototype.getReferenceAngle = function() {
return this.m_referenceAngle;
};
PrismaticJoint.prototype.getJointTranslation = function() {
var pA = this.m_bodyA.getWorldPoint(this.m_localAnchorA);
var pB = this.m_bodyB.getWorldPoint(this.m_localAnchorB);
var d = Vec2.sub(pB, pA);
var axis = this.m_bodyA.getWorldVector(this.m_localXAxisA);
var translation = Vec2.dot(d, axis);
return translation;
};
PrismaticJoint.prototype.getJointSpeed = function() {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var rA = Mul(bA.m_xf.q, this.m_localAnchorA - bA.m_sweep.localCenter);
var rB = Mul(bB.m_xf.q, this.m_localAnchorB - bB.m_sweep.localCenter);
var p1 = bA.m_sweep.c + rA;
var p2 = bB.m_sweep.c + rB;
var d = p2 - p1;
var axis = Mul(bA.m_xf.q, this.m_localXAxisA);
var vA = bA.m_linearVelocity;
var vB = bB.m_linearVelocity;
var wA = bA.m_angularVelocity;
var wB = bB.m_angularVelocity;
var speed = Dot(d, Cross(wA, axis)) + Dot(axis, vB + Cross(wB, rB) - vA - Cross(wA, rA));
return speed;
};
PrismaticJoint.prototype.isLimitEnabled = function() {
return this.m_enableLimit;
};
PrismaticJoint.prototype.enableLimit = function(flag) {
if (flag != this.m_enableLimit) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableLimit = flag;
this.m_impulse.z = 0;
}
};
PrismaticJoint.prototype.getLowerLimit = function() {
return this.m_lowerTranslation;
};
PrismaticJoint.prototype.getUpperLimit = function() {
return this.m_upperTranslation;
};
PrismaticJoint.prototype.setLimits = function(lower, upper) {
ASSERT && common.assert(lower <= upper);
if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_lowerTranslation = lower;
this.m_upperTranslation = upper;
this.m_impulse.z = 0;
}
};
PrismaticJoint.prototype.isMotorEnabled = function() {
return this.m_enableMotor;
};
PrismaticJoint.prototype.enableMotor = function(flag) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableMotor = flag;
};
PrismaticJoint.prototype.setMotorSpeed = function(speed) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_motorSpeed = speed;
};
PrismaticJoint.prototype.setMaxMotorForce = function(force) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_maxMotorForce = force;
};
PrismaticJoint.prototype.getMotorSpeed = function() {
return this.m_motorSpeed;
};
PrismaticJoint.prototype.getMotorForce = function(inv_dt) {
return inv_dt * this.m_motorImpulse;
};
PrismaticJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
PrismaticJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
PrismaticJoint.prototype.getReactionForce = function(inv_dt) {
return inv_dt * (this.m_impulse.x * this.m_perp + (this.m_motorImpulse + this.m_impulse.z) * this.m_axis);
};
PrismaticJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_impulse.y;
};
PrismaticJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var d = Vec2.zero();
d.wAdd(1, cB, 1, rB);
d.wSub(1, cA, 1, rA);
var mA = this.m_invMassA, mB = this.m_invMassB;
var iA = this.m_invIA, iB = this.m_invIB;
{
this.m_axis = Rot.mul(qA, this.m_localXAxisA);
this.m_a1 = Vec2.cross(Vec2.add(d, rA), this.m_axis);
this.m_a2 = Vec2.cross(rB, this.m_axis);
this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2;
if (this.m_motorMass > 0) {
this.m_motorMass = 1 / this.m_motorMass;
}
}
{
this.m_perp = Rot.mul(qA, this.m_localYAxisA);
this.m_s1 = Vec2.cross(Vec2.add(d, rA), this.m_perp);
this.m_s2 = Vec2.cross(rB, this.m_perp);
var s1test = Vec2.cross(rA, this.m_perp);
var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2;
var k12 = iA * this.m_s1 + iB * this.m_s2;
var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2;
var k22 = iA + iB;
if (k22 == 0) {
k22 = 1;
}
var k23 = iA * this.m_a1 + iB * this.m_a2;
var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2;
this.m_K.ex.set(k11, k12, k13);
this.m_K.ey.set(k12, k22, k23);
this.m_K.ez.set(k13, k23, k33);
}
if (this.m_enableLimit) {
var jointTranslation = Vec2.dot(this.m_axis, d);
if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * Settings.linearSlop) {
this.m_limitState = equalLimits;
} else if (jointTranslation <= this.m_lowerTranslation) {
if (this.m_limitState != atLowerLimit) {
this.m_limitState = atLowerLimit;
this.m_impulse.z = 0;
}
} else if (jointTranslation >= this.m_upperTranslation) {
if (this.m_limitState != atUpperLimit) {
this.m_limitState = atUpperLimit;
this.m_impulse.z = 0;
}
} else {
this.m_limitState = inactiveLimit;
this.m_impulse.z = 0;
}
} else {
this.m_limitState = inactiveLimit;
this.m_impulse.z = 0;
}
if (this.m_enableMotor == false) {
this.m_motorImpulse = 0;
}
if (step.warmStarting) {
this.m_impulse.mul(step.dtRatio);
this.m_motorImpulse *= step.dtRatio;
var P = Vec2.wAdd(this.m_impulse.x, this.m_perp, this.m_motorImpulse + this.m_impulse.z, this.m_axis);
var LA = this.m_impulse.x * this.m_s1 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a1;
var LB = this.m_impulse.x * this.m_s2 + this.m_impulse.y + (this.m_motorImpulse + this.m_impulse.z) * this.m_a2;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
} else {
this.m_impulse.setZero();
this.m_motorImpulse = 0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
PrismaticJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
if (this.m_enableMotor && this.m_limitState != equalLimits) {
var Cdot = Vec2.dot(this.m_axis, Vec2.sub(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA;
var impulse = this.m_motorMass * (this.m_motorSpeed - Cdot);
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorForce;
this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
var P = Vec2.zero().wSet(impulse, this.m_axis);
var LA = impulse * this.m_a1;
var LB = impulse * this.m_a2;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
}
var Cdot1 = Vec2.zero();
Cdot1.x += Vec2.dot(this.m_perp, vB) + this.m_s2 * wB;
Cdot1.x -= Vec2.dot(this.m_perp, vA) + this.m_s1 * wA;
Cdot1.y = wB - wA;
if (this.m_enableLimit && this.m_limitState != inactiveLimit) {
var Cdot2 = 0;
Cdot2 += Vec2.dot(this.m_axis, vB) + this.m_a2 * wB;
Cdot2 -= Vec2.dot(this.m_axis, vA) + this.m_a1 * wA;
var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2);
var f1 = Vec3(this.m_impulse);
var df = this.m_K.solve33(Vec3.neg(Cdot));
this.m_impulse.add(df);
if (this.m_limitState == atLowerLimit) {
this.m_impulse.z = Math.max(this.m_impulse.z, 0);
} else if (this.m_limitState == atUpperLimit) {
this.m_impulse.z = Math.min(this.m_impulse.z, 0);
}
var b = Vec2.wAdd(-1, Cdot1, -(this.m_impulse.z - f1.z), Vec2.neo(this.m_K.ez.x, this.m_K.ez.y));
var f2r = Vec2.add(this.m_K.solve22(b), Vec2.neo(f1.x, f1.y));
this.m_impulse.x = f2r.x;
this.m_impulse.y = f2r.y;
df = Vec3.sub(this.m_impulse, f1);
var P = Vec2.wAdd(df.x, this.m_perp, df.z, this.m_axis);
var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1;
var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
} else {
var df = this.m_K.solve22(Vec2.neg(Cdot1));
this.m_impulse.x += df.x;
this.m_impulse.y += df.y;
var P = Vec2.zero().wAdd(df.x, this.m_perp);
var LA = df.x * this.m_s1 + df.y;
var LB = df.x * this.m_s2 + df.y;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
PrismaticJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var d = Vec2.sub(Vec2.add(cB, rB), Vec2.add(cA, rA));
var axis = Rot.mul(qA, this.m_localXAxisA);
var a1 = Vec2.cross(Vec2.add(d, rA), axis);
var a2 = Vec2.cross(rB, axis);
var perp = Rot.mul(qA, this.m_localYAxisA);
var s1 = Vec2.cross(Vec2.add(d, rA), perp);
var s2 = Vec2.cross(rB, perp);
var impulse = Vec3();
var C1 = Vec2.zero();
C1.x = Vec2.dot(perp, d);
C1.y = aB - aA - this.m_referenceAngle;
var linearError = Math.abs(C1.x);
var angularError = Math.abs(C1.y);
var linearSlop = Settings.linearSlop;
var maxLinearCorrection = Settings.maxLinearCorrection;
var active = false;
var C2 = 0;
if (this.m_enableLimit) {
var translation = Vec2.dot(axis, d);
if (Math.abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * linearSlop) {
C2 = Math.clamp(translation, -maxLinearCorrection, maxLinearCorrection);
linearError = Math.max(linearError, Math.abs(translation));
active = true;
} else if (translation <= this.m_lowerTranslation) {
C2 = Math.clamp(translation - this.m_lowerTranslation + linearSlop, -maxLinearCorrection, 0);
linearError = Math.max(linearError, this.m_lowerTranslation - translation);
active = true;
} else if (translation >= this.m_upperTranslation) {
C2 = Math.clamp(translation - this.m_upperTranslation - linearSlop, 0, maxLinearCorrection);
linearError = Math.max(linearError, translation - this.m_upperTranslation);
active = true;
}
}
if (active) {
var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
var k12 = iA * s1 + iB * s2;
var k13 = iA * s1 * a1 + iB * s2 * a2;
var k22 = iA + iB;
if (k22 == 0) {
k22 = 1;
}
var k23 = iA * a1 + iB * a2;
var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
var K = new Mat33();
K.ex.set(k11, k12, k13);
K.ey.set(k12, k22, k23);
K.ez.set(k13, k23, k33);
var C = Vec3();
C.x = C1.x;
C.y = C1.y;
C.z = C2;
impulse = K.solve33(Vec3.neg(C));
} else {
var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
var k12 = iA * s1 + iB * s2;
var k22 = iA + iB;
if (k22 == 0) {
k22 = 1;
}
var K = new Mat22();
K.ex.set(k11, k12);
K.ey.set(k12, k22);
var impulse1 = K.solve(Vec2.neg(C1));
impulse.x = impulse1.x;
impulse.y = impulse1.y;
impulse.z = 0;
}
var P = Vec2.wAdd(impulse.x, perp, impulse.z, axis);
var LA = impulse.x * s1 + impulse.y + impulse.z * a1;
var LB = impulse.x * s2 + impulse.y + impulse.z * a2;
cA.wSub(mA, P);
aA -= iA * LA;
cB.wAdd(mB, P);
aB += iB * LB;
this.m_bodyA.c_position.c = cA;
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c = cB;
this.m_bodyB.c_position.a = aB;
return linearError <= Settings.linearSlop && angularError <= Settings.angularSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],34:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = PulleyJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
PulleyJoint.TYPE = "pulley-joint";
PulleyJoint.MIN_PULLEY_LENGTH = 2;
PulleyJoint._super = Joint;
PulleyJoint.prototype = create(PulleyJoint._super.prototype);
var PulleyJointDef = {
collideConnected: true
};
function PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio) {
if (!(this instanceof PulleyJoint)) {
return new PulleyJoint(def, bodyA, bodyB, groundA, groundB, anchorA, anchorB, ratio);
}
def = options(def, PulleyJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = PulleyJoint.TYPE;
this.m_groundAnchorA = groundA;
this.m_groundAnchorB = groundB;
this.m_localAnchorA = bodyA.getLocalPoint(anchorA);
this.m_localAnchorB = bodyB.getLocalPoint(anchorB);
this.m_lengthA = Vec2.distance(anchorA, groundA);
this.m_lengthB = Vec2.distance(anchorB, groundB);
this.m_ratio = def.ratio || ratio;
ASSERT && common.assert(ratio > Math.EPSILON);
this.m_constant = this.m_lengthA + this.m_ratio * this.m_lengthB;
this.m_impulse = 0;
this.m_uA;
this.m_uB;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
}
PulleyJoint.prototype.getGroundAnchorA = function() {
return this.m_groundAnchorA;
};
PulleyJoint.prototype.getGroundAnchorB = function() {
return this.m_groundAnchorB;
};
PulleyJoint.prototype.getLengthA = function() {
return this.m_lengthA;
};
PulleyJoint.prototype.getLengthB = function() {
return this.m_lengthB;
};
PulleyJoint.prototype.setRatio = function() {
return this.m_ratio;
};
PulleyJoint.prototype.getCurrentLengthA = function() {
var p = this.m_bodyA.getWorldPoint(this.m_localAnchorA);
var s = this.m_groundAnchorA;
return Vec2.distance(p, s);
};
PulleyJoint.prototype.getCurrentLengthB = function() {
var p = this.m_bodyB.getWorldPoint(this.m_localAnchorB);
var s = this.m_groundAnchorB;
return Vec2.distance(p, s);
};
PulleyJoint.prototype.shiftOrigin = function(newOrigin) {
this.m_groundAnchorA -= newOrigin;
this.m_groundAnchorB -= newOrigin;
};
PulleyJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
PulleyJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
PulleyJoint.prototype.getReactionForce = function(inv_dt) {
return Vec3.mul(inv_dt * this.m_impulse, this.m_uB);
};
PulleyJoint.prototype.getReactionTorque = function(inv_dt) {
return 0;
};
PulleyJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
this.m_uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA);
this.m_uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB);
var lengthA = this.m_uA.length();
var lengthB = this.m_uB.length();
if (lengthA > 10 * Settings.linearSlop) {
this.m_uA.mul(1 / lengthA);
} else {
this.m_uA.setZero();
}
if (lengthB > 10 * Settings.linearSlop) {
this.m_uB.mul(1 / lengthB);
} else {
this.m_uB.setZero();
}
var ruA = Vec2.cross(this.m_rA, this.m_uA);
var ruB = Vec2.cross(this.m_rB, this.m_uB);
var mA = this.m_invMassA + this.m_invIA * ruA * ruA;
var mB = this.m_invMassB + this.m_invIB * ruB * ruB;
this.m_mass = mA + this.m_ratio * this.m_ratio * mB;
if (this.m_mass > 0) {
this.m_mass = 1 / this.m_mass;
}
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
var PA = Vec2.mul(-this.m_impulse, this.m_uA);
var PB = Vec2.mul(-this.m_ratio * this.m_impulse, this.m_uB);
vA.wAdd(this.m_invMassA, PA);
wA += this.m_invIA * Vec2.cross(this.m_rA, PA);
vB.wAdd(this.m_invMassB, PB);
wB += this.m_invIB * Vec2.cross(this.m_rB, PB);
} else {
this.m_impulse = 0;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
PulleyJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var vpA = Vec2.add(vA, Vec2.cross(wA, this.m_rA));
var vpB = Vec2.add(vB, Vec2.cross(wB, this.m_rB));
var Cdot = -Vec2.dot(this.m_uA, vpA) - this.m_ratio * Vec2.dot(this.m_uB, vpB);
var impulse = -this.m_mass * Cdot;
this.m_impulse += impulse;
var PA = Vec2.zero().wSet(-impulse, this.m_uA);
var PB = Vec2.zero().wSet(-this.m_ratio * impulse, this.m_uB);
vA.wAdd(this.m_invMassA, PA);
wA += this.m_invIA * Vec2.cross(this.m_rA, PA);
vB.wAdd(this.m_invMassB, PB);
wB += this.m_invIB * Vec2.cross(this.m_rB, PB);
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
PulleyJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA), qB = Rot.neo(aB);
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var uA = Vec2.sub(Vec2.add(cA, this.m_rA), this.m_groundAnchorA);
var uB = Vec2.sub(Vec2.add(cB, this.m_rB), this.m_groundAnchorB);
var lengthA = uA.length();
var lengthB = uB.length();
if (lengthA > 10 * Settings.linearSlop) {
uA.mul(1 / lengthA);
} else {
uA.setZero();
}
if (lengthB > 10 * Settings.linearSlop) {
uB.mul(1 / lengthB);
} else {
uB.setZero();
}
var ruA = Vec2.cross(rA, uA);
var ruB = Vec2.cross(rB, uB);
var mA = this.m_invMassA + this.m_invIA * ruA * ruA;
var mB = this.m_invMassB + this.m_invIB * ruB * ruB;
var mass = mA + this.m_ratio * this.m_ratio * mB;
if (mass > 0) {
mass = 1 / mass;
}
var C = this.m_constant - lengthA - this.m_ratio * lengthB;
var linearError = Math.abs(C);
var impulse = -mass * C;
var PA = Vec2.zero().wSet(-impulse, uA);
var PB = Vec2.zero().wSet(-this.m_ratio * impulse, uB);
cA.wAdd(this.m_invMassA, PA);
aA += this.m_invIA * Vec2.cross(rA, PA);
cB.wAdd(this.m_invMassB, PB);
aB += this.m_invIB * Vec2.cross(rB, PB);
this.m_bodyA.c_position.c = cA;
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c = cB;
this.m_bodyB.c_position.a = aB;
return linearError < Settings.linearSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],35:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = RevoluteJoint;
var common = require("../util/common");
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
var inactiveLimit = 0;
var atLowerLimit = 1;
var atUpperLimit = 2;
var equalLimits = 3;
RevoluteJoint.TYPE = "revolute-joint";
RevoluteJoint._super = Joint;
RevoluteJoint.prototype = create(RevoluteJoint._super.prototype);
var RevoluteJointDef = {
lowerAngle: 0,
upperAngle: 0,
maxMotorTorque: 0,
motorSpeed: 0,
enableLimit: false,
enableMotor: false
};
function RevoluteJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RevoluteJoint)) {
return new RevoluteJoint(def, bodyA, bodyB, anchor);
}
def = options(def, RevoluteJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = RevoluteJoint.TYPE;
this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor);
this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor);
this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = Vec3();
this.m_motorImpulse = 0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass = new Mat33();
this.m_motorMass;
this.m_limitState = inactiveLimit;
}
RevoluteJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
RevoluteJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
RevoluteJoint.prototype.getReferenceAngle = function() {
return this.m_referenceAngle;
};
RevoluteJoint.prototype.getJointAngle = function() {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
};
RevoluteJoint.prototype.getJointSpeed = function() {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
return bB.m_angularVelocity - bA.m_angularVelocity;
};
RevoluteJoint.prototype.isMotorEnabled = function() {
return this.m_enableMotor;
};
RevoluteJoint.prototype.enableMotor = function(flag) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableMotor = flag;
};
RevoluteJoint.prototype.getMotorTorque = function(inv_dt) {
return inv_dt * this.m_motorImpulse;
};
RevoluteJoint.prototype.setMotorSpeed = function(speed) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_motorSpeed = speed;
};
RevoluteJoint.prototype.getMotorSpeed = function() {
return this.m_motorSpeed;
};
RevoluteJoint.prototype.setMaxMotorTorque = function(torque) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_maxMotorTorque = torque;
};
RevoluteJoint.prototype.isLimitEnabled = function() {
return this.m_enableLimit;
};
RevoluteJoint.prototype.enableLimit = function(flag) {
if (flag != this.m_enableLimit) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableLimit = flag;
this.m_impulse.z = 0;
}
};
RevoluteJoint.prototype.getLowerLimit = function() {
return this.m_lowerAngle;
};
RevoluteJoint.prototype.getUpperLimit = function() {
return this.m_upperAngle;
};
RevoluteJoint.prototype.setLimits = function(lower, upper) {
ASSERT && common.assert(lower <= upper);
if (lower != this.m_lowerAngle || upper != this.m_upperAngle) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_impulse.z = 0;
this.m_lowerAngle = lower;
this.m_upperAngle = upper;
}
};
RevoluteJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
RevoluteJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
RevoluteJoint.prototype.getReactionForce = function(inv_dt) {
var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y);
return inv_dt * P;
};
RevoluteJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_impulse.z;
};
RevoluteJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var fixedRotation = iA + iB == 0;
this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB;
this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB;
this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB;
this.m_mass.ex.y = this.m_mass.ey.x;
this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB;
this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB;
this.m_mass.ex.z = this.m_mass.ez.x;
this.m_mass.ey.z = this.m_mass.ez.y;
this.m_mass.ez.z = iA + iB;
this.m_motorMass = iA + iB;
if (this.m_motorMass > 0) {
this.m_motorMass = 1 / this.m_motorMass;
}
if (this.m_enableMotor == false || fixedRotation) {
this.m_motorImpulse = 0;
}
if (this.m_enableLimit && fixedRotation == false) {
var jointAngle = aB - aA - this.m_referenceAngle;
if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2 * Settings.angularSlop) {
this.m_limitState = equalLimits;
} else if (jointAngle <= this.m_lowerAngle) {
if (this.m_limitState != atLowerLimit) {
this.m_impulse.z = 0;
}
this.m_limitState = atLowerLimit;
} else if (jointAngle >= this.m_upperAngle) {
if (this.m_limitState != atUpperLimit) {
this.m_impulse.z = 0;
}
this.m_limitState = atUpperLimit;
} else {
this.m_limitState = inactiveLimit;
this.m_impulse.z = 0;
}
} else {
this.m_limitState = inactiveLimit;
}
if (step.warmStarting) {
this.m_impulse.mul(step.dtRatio);
this.m_motorImpulse *= step.dtRatio;
var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z);
} else {
this.m_impulse.setZero();
this.m_motorImpulse = 0;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
RevoluteJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var fixedRotation = iA + iB == 0;
if (this.m_enableMotor && this.m_limitState != equalLimits && fixedRotation == false) {
var Cdot = wB - wA - this.m_motorSpeed;
var impulse = -this.m_motorMass * Cdot;
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorTorque;
this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) {
var Cdot1 = Vec2.zero();
Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA));
var Cdot2 = wB - wA;
var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2);
var impulse = Vec3.neg(this.m_mass.solve33(Cdot));
if (this.m_limitState == equalLimits) {
this.m_impulse.add(impulse);
} else if (this.m_limitState == atLowerLimit) {
var newImpulse = this.m_impulse.z + impulse.z;
if (newImpulse < 0) {
var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y));
var reduced = this.m_mass.solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -this.m_impulse.z;
this.m_impulse.x += reduced.x;
this.m_impulse.y += reduced.y;
this.m_impulse.z = 0;
} else {
this.m_impulse.add(impulse);
}
} else if (this.m_limitState == atUpperLimit) {
var newImpulse = this.m_impulse.z + impulse.z;
if (newImpulse > 0) {
var rhs = Vec2.wAdd(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y));
var reduced = this.m_mass.solve22(rhs);
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -this.m_impulse.z;
this.m_impulse.x += reduced.x;
this.m_impulse.y += reduced.y;
this.m_impulse.z = 0;
} else {
this.m_impulse.add(impulse);
}
}
var P = Vec2.neo(impulse.x, impulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z);
} else {
var Cdot = Vec2.zero();
Cdot.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA));
var impulse = this.m_mass.solve22(Vec2.neg(Cdot));
this.m_impulse.x += impulse.x;
this.m_impulse.y += impulse.y;
vA.wSub(mA, impulse);
wA -= iA * Vec2.cross(this.m_rA, impulse);
vB.wAdd(mB, impulse);
wB += iB * Vec2.cross(this.m_rB, impulse);
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
RevoluteJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var angularError = 0;
var positionError = 0;
var fixedRotation = this.m_invIA + this.m_invIB == 0;
if (this.m_enableLimit && this.m_limitState != inactiveLimit && fixedRotation == false) {
var angle = aB - aA - this.m_referenceAngle;
var limitImpulse = 0;
if (this.m_limitState == equalLimits) {
var C = Math.clamp(angle - this.m_lowerAngle, -Settings.maxAngularCorrection, Settings.maxAngularCorrection);
limitImpulse = -this.m_motorMass * C;
angularError = Math.abs(C);
} else if (this.m_limitState == atLowerLimit) {
var C = angle - this.m_lowerAngle;
angularError = -C;
C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection, 0);
limitImpulse = -this.m_motorMass * C;
} else if (this.m_limitState == atUpperLimit) {
var C = angle - this.m_upperAngle;
angularError = C;
C = Math.clamp(C - Settings.angularSlop, 0, Settings.maxAngularCorrection);
limitImpulse = -this.m_motorMass * C;
}
aA -= this.m_invIA * limitImpulse;
aB += this.m_invIB * limitImpulse;
}
{
qA.set(aA);
qB.set(aB);
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var C = Vec2.zero();
C.wAdd(1, cB, 1, rB);
C.wSub(1, cA, 1, rA);
positionError = C.length();
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var K = new Mat22();
K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
var impulse = Vec2.neg(K.solve(C));
cA.wSub(mA, impulse);
aA -= iA * Vec2.cross(rA, impulse);
cB.wAdd(mB, impulse);
aB += iB * Vec2.cross(rB, impulse);
}
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/common":51,"../util/create":52,"../util/options":53}],36:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = RopeJoint;
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
var inactiveLimit = 0;
var atLowerLimit = 1;
var atUpperLimit = 2;
var equalLimits = 3;
RopeJoint.TYPE = "rope-joint";
RopeJoint._super = Joint;
RopeJoint.prototype = create(RopeJoint._super.prototype);
var RopeJointDef = {
maxLength: 0
};
function RopeJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RopeJoint)) {
return new RopeJoint(def, bodyA, bodyB, anchor);
}
def = options(def, RopeJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = RopeJoint.TYPE;
this.m_localAnchorA = def.localAnchorA || bodyA.getLocalPoint(anchor);
this.m_localAnchorB = def.localAnchorB || bodyB.getLocalPoint(anchor);
this.m_maxLength = def.maxLength;
this.m_mass = 0;
this.m_impulse = 0;
this.m_length = 0;
this.m_state = inactiveLimit;
this.m_u;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
}
RopeJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
RopeJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
RopeJoint.prototype.setMaxLength = function(length) {
this.m_maxLength = length;
};
RopeJoint.prototype.getMaxLength = function() {
return this.m_maxLength;
};
RopeJoint.prototype.getLimitState = function() {
return this.m_state;
};
RopeJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
RopeJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
RopeJoint.prototype.getReactionForce = function(inv_dt) {
var F = inv_dt * this.m_impulse * this.m_u;
return F;
};
RopeJoint.prototype.getReactionTorque = function(inv_dt) {
return 0;
};
RopeJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
this.m_rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA);
this.m_rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB);
this.m_u = Vec2.zero();
this.m_u.wAdd(1, cB, 1, this.m_rB);
this.m_u.wSub(1, cA, 1, this.m_rA);
this.m_length = this.m_u.length();
var C = this.m_length - this.m_maxLength;
if (C > 0) {
this.m_state = atUpperLimit;
} else {
this.m_state = inactiveLimit;
}
if (this.m_length > Settings.linearSlop) {
this.m_u.mul(1 / this.m_length);
} else {
this.m_u.setZero();
this.m_mass = 0;
this.m_impulse = 0;
return;
}
var crA = Vec2.cross(this.m_rA, this.m_u);
var crB = Vec2.cross(this.m_rB, this.m_u);
var invMass = this.m_invMassA + this.m_invIA * crA * crA + this.m_invMassB + this.m_invIB * crB * crB;
this.m_mass = invMass != 0 ? 1 / invMass : 0;
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
var P = Vec2.mul(this.m_impulse, this.m_u);
vA.wSub(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.wAdd(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
} else {
this.m_impulse = 0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
RopeJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var vpA = Vec2.addCross(vA, wA, this.m_rA);
var vpB = Vec2.addCross(vB, wB, this.m_rB);
var C = this.m_length - this.m_maxLength;
var Cdot = Vec2.dot(this.m_u, Vec2.sub(vpB, vpA));
if (C < 0) {
Cdot += step.inv_dt * C;
}
var impulse = -this.m_mass * Cdot;
var oldImpulse = this.m_impulse;
this.m_impulse = Math.min(0, this.m_impulse + impulse);
impulse = this.m_impulse - oldImpulse;
var P = Vec2.mul(impulse, this.m_u);
vA.wSub(this.m_invMassA, P);
wA -= this.m_invIA * Vec2.cross(this.m_rA, P);
vB.wAdd(this.m_invMassB, P);
wB += this.m_invIB * Vec2.cross(this.m_rB, P);
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
RopeJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var rA = Rot.mulSub(qA, this.m_localAnchorA, this.m_localCenterA);
var rB = Rot.mulSub(qB, this.m_localAnchorB, this.m_localCenterB);
var u = Vec2.zero();
u.wAdd(1, cB, 1, rB);
u.wSub(1, cA, 1, rA);
var length = u.normalize();
var C = length - this.m_maxLength;
C = Math.clamp(C, 0, Settings.maxLinearCorrection);
var impulse = -this.m_mass * C;
var P = Vec2.mul(impulse, u);
cA.wSub(this.m_invMassA, P);
aA -= this.m_invIA * Vec2.cross(rA, P);
cB.wAdd(this.m_invMassB, P);
aB += this.m_invIB * Vec2.cross(rB, P);
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return length - this.m_maxLength < Settings.linearSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],37:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = WeldJoint;
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
WeldJoint.TYPE = "weld-joint";
WeldJoint._super = Joint;
WeldJoint.prototype = create(WeldJoint._super.prototype);
var WeldJointDef = {
frequencyHz: 0,
dampingRatio: 0
};
function WeldJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof WeldJoint)) {
return new WeldJoint(def, bodyA, bodyB, anchor);
}
def = options(def, WeldJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = WeldJoint.TYPE;
this.m_localAnchorA = bodyA.getLocalPoint(anchor);
this.m_localAnchorB = bodyB.getLocalPoint(anchor);
this.m_referenceAngle = bodyB.getAngle() - bodyA.getAngle();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = Vec3();
this.m_bias = 0;
this.m_gamma = 0;
this.m_rA;
this.m_rB;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass = new Mat33();
}
WeldJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
WeldJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
WeldJoint.prototype.getReferenceAngle = function() {
return this.m_referenceAngle;
};
WeldJoint.prototype.setFrequency = function(hz) {
this.m_frequencyHz = hz;
};
WeldJoint.prototype.getFrequency = function() {
return this.m_frequencyHz;
};
WeldJoint.prototype.setDampingRatio = function(ratio) {
this.m_dampingRatio = ratio;
};
WeldJoint.prototype.getDampingRatio = function() {
return this.m_dampingRatio;
};
WeldJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
WeldJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
WeldJoint.prototype.getReactionForce = function(inv_dt) {
var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y);
return inv_dt * P;
};
WeldJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_impulse.z;
};
WeldJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA), qB = Rot.neo(aB);
this.m_rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var K = new Mat33();
K.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y * this.m_rB.y * iB;
K.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y * this.m_rB.x * iB;
K.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB;
K.ex.y = K.ey.x;
K.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x * this.m_rB.x * iB;
K.ez.y = this.m_rA.x * iA + this.m_rB.x * iB;
K.ex.z = K.ez.x;
K.ey.z = K.ez.y;
K.ez.z = iA + iB;
if (this.m_frequencyHz > 0) {
K.getInverse22(this.m_mass);
var invM = iA + iB;
var m = invM > 0 ? 1 / invM : 0;
var C = aB - aA - this.m_referenceAngle;
var omega = 2 * Math.PI * this.m_frequencyHz;
var d = 2 * m * this.m_dampingRatio * omega;
var k = m * omega * omega;
var h = step.dt;
this.m_gamma = h * (d + h * k);
this.m_gamma = this.m_gamma != 0 ? 1 / this.m_gamma : 0;
this.m_bias = C * h * k * this.m_gamma;
invM += this.m_gamma;
this.m_mass.ez.z = invM != 0 ? 1 / invM : 0;
} else if (K.ez.z == 0) {
K.getInverse22(this.m_mass);
this.m_gamma = 0;
this.m_bias = 0;
} else {
K.getSymInverse33(this.m_mass);
this.m_gamma = 0;
this.m_bias = 0;
}
if (step.warmStarting) {
this.m_impulse.mul(step.dtRatio);
var P = Vec2.neo(this.m_impulse.x, this.m_impulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_impulse.z);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + this.m_impulse.z);
} else {
this.m_impulse.setZero();
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
WeldJoint.prototype.solveVelocityConstraints = function(step) {
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
if (this.m_frequencyHz > 0) {
var Cdot2 = wB - wA;
var impulse2 = -this.m_mass.ez.z * (Cdot2 + this.m_bias + this.m_gamma * this.m_impulse.z);
this.m_impulse.z += impulse2;
wA -= iA * impulse2;
wB += iB * impulse2;
var Cdot1 = Vec2.zero();
Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA));
var impulse1 = Vec2.neg(Mat33.mul(this.m_mass, Cdot1));
this.m_impulse.x += impulse1.x;
this.m_impulse.y += impulse1.y;
var P = Vec2.clone(impulse1);
vA.wSub(mA, P);
wA -= iA * Vec2.cross(this.m_rA, P);
vB.wAdd(mB, P);
wB += iB * Vec2.cross(this.m_rB, P);
} else {
var Cdot1 = Vec2.zero();
Cdot1.wAdd(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot1.wSub(1, vA, 1, Vec2.cross(wA, this.m_rA));
var Cdot2 = wB - wA;
var Cdot = Vec3(Cdot1.x, Cdot1.y, Cdot2);
var impulse = Vec3.neg(Mat33.mul(this.m_mass, Cdot));
this.m_impulse.add(impulse);
var P = Vec2.neo(impulse.x, impulse.y);
vA.wSub(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z);
vB.wAdd(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z);
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
};
WeldJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA), qB = Rot.neo(aB);
var mA = this.m_invMassA, mB = this.m_invMassB;
var iA = this.m_invIA, iB = this.m_invIB;
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var positionError, angularError;
var K = new Mat33();
K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB;
K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB;
K.ez.x = -rA.y * iA - rB.y * iB;
K.ex.y = K.ey.x;
K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB;
K.ez.y = rA.x * iA + rB.x * iB;
K.ex.z = K.ez.x;
K.ey.z = K.ez.y;
K.ez.z = iA + iB;
if (this.m_frequencyHz > 0) {
var C1 = Vec2.zero();
C1.wAdd(1, cB, 1, rB);
C1.wSub(1, cA, 1, rA);
positionError = C1.length();
angularError = 0;
var P = Vec2.neg(K.solve22(C1));
cA.wSub(mA, P);
aA -= iA * Vec2.cross(rA, P);
cB.wAdd(mB, P);
aB += iB * Vec2.cross(rB, P);
} else {
var C1 = Vec2.zero();
C1.wAdd(1, cB, 1, rB);
C1.wSub(1, cA, 1, rA);
var C2 = aB - aA - this.m_referenceAngle;
positionError = C1.length();
angularError = Math.abs(C2);
var C = Vec3(C1.x, C1.y, C2);
var impulse = Vec3();
if (K.ez.z > 0) {
impulse = Vec3.neg(K.solve33(C));
} else {
var impulse2 = Vec2.neg(K.solve22(C1));
impulse.set(impulse2.x, impulse2.y, 0);
}
var P = Vec2.neo(impulse.x, impulse.y);
cA.wSub(mA, P);
aA -= iA * (Vec2.cross(rA, P) + impulse.z);
cB.wAdd(mB, P);
aB += iB * (Vec2.cross(rB, P) + impulse.z);
}
this.m_bodyA.c_position.c = cA;
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c = cB;
this.m_bodyB.c_position.a = aB;
return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],38:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = WheelJoint;
var options = require("../util/options");
var create = require("../util/create");
var Settings = require("../Settings");
var Math = require("../common/Math");
var Vec2 = require("../common/Vec2");
var Vec3 = require("../common/Vec3");
var Mat22 = require("../common/Mat22");
var Mat33 = require("../common/Mat33");
var Rot = require("../common/Rot");
var Sweep = require("../common/Sweep");
var Transform = require("../common/Transform");
var Velocity = require("../common/Velocity");
var Position = require("../common/Position");
var Joint = require("../Joint");
WheelJoint.TYPE = "wheel-joint";
WheelJoint._super = Joint;
WheelJoint.prototype = create(WheelJoint._super.prototype);
var WheelJointDef = {
enableMotor: false,
maxMotorTorque: 0,
motorSpeed: 0,
frequencyHz: 2,
dampingRatio: .7
};
function WheelJoint(def, bodyA, bodyB, anchor, axis) {
if (!(this instanceof WheelJoint)) {
return new WheelJoint(def, bodyA, bodyB, anchor, axis);
}
def = options(def, WheelJointDef);
Joint.call(this, def, bodyA, bodyB);
this.m_type = WheelJoint.TYPE;
this.m_localAnchorA = bodyA.getLocalPoint(anchor);
this.m_localAnchorB = bodyB.getLocalPoint(anchor);
this.m_localXAxisA = bodyA.getLocalVector(axis || Vec2.neo(1, 0));
this.m_localYAxisA = Vec2.cross(1, this.m_localXAxisA);
this.m_mass = 0;
this.m_impulse = 0;
this.m_motorMass = 0;
this.m_motorImpulse = 0;
this.m_springMass = 0;
this.m_springImpulse = 0;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableMotor = def.enableMotor;
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_bias = 0;
this.m_gamma = 0;
this.m_localCenterA;
this.m_localCenterB;
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_ax = Vec2.zero();
this.m_ay = Vec2.zero();
this.m_sAx;
this.m_sBx;
this.m_sAy;
this.m_sBy;
}
WheelJoint.prototype.getLocalAnchorA = function() {
return this.m_localAnchorA;
};
WheelJoint.prototype.getLocalAnchorB = function() {
return this.m_localAnchorB;
};
WheelJoint.prototype.getLocalAxisA = function() {
return this.m_localXAxisA;
};
WheelJoint.prototype.getJointTranslation = function() {
var bA = this.m_bodyA;
var bB = this.m_bodyB;
var pA = bA.getWorldPoint(this.m_localAnchorA);
var pB = bB.getWorldPoint(this.m_localAnchorB);
var d = pB - pA;
var axis = bA.getWorldVector(this.m_localXAxisA);
var translation = Dot(d, axis);
return translation;
};
WheelJoint.prototype.getJointSpeed = function() {
var wA = this.m_bodyA.m_angularVelocity;
var wB = this.m_bodyB.m_angularVelocity;
return wB - wA;
};
WheelJoint.prototype.isMotorEnabled = function() {
return this.m_enableMotor;
};
WheelJoint.prototype.enableMotor = function(flag) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableMotor = flag;
};
WheelJoint.prototype.setMotorSpeed = function(speed) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_motorSpeed = speed;
};
WheelJoint.prototype.getMotorSpeed = function() {
return this.m_motorSpeed;
};
WheelJoint.prototype.setMaxMotorTorque = function(torque) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_maxMotorTorque = torque;
};
WheelJoint.prototype.getMaxMotorTorque = function() {
return this.m_maxMotorTorque;
};
WheelJoint.prototype.getMotorTorque = function(inv_dt) {
return inv_dt * this.m_motorImpulse;
};
WheelJoint.prototype.setSpringFrequencyHz = function(hz) {
this.m_frequencyHz = hz;
};
WheelJoint.prototype.getSpringFrequencyHz = function() {
return this.m_frequencyHz;
};
WheelJoint.prototype.setSpringDampingRatio = function(ratio) {
this.m_dampingRatio = ratio;
};
WheelJoint.prototype.getSpringDampingRatio = function() {
return this.m_dampingRatio;
};
WheelJoint.prototype.getAnchorA = function() {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
};
WheelJoint.prototype.getAnchorB = function() {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
};
WheelJoint.prototype.getReactionForce = function(inv_dt) {
return inv_dt * (this.m_impulse * this.m_ay + this.m_springImpulse * this.m_ax);
};
WheelJoint.prototype.getReactionTorque = function(inv_dt) {
return inv_dt * this.m_motorImpulse;
};
WheelJoint.prototype.initVelocityConstraints = function(step) {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var d = Vec2.zero();
d.wAdd(1, cB, 1, rB);
d.wSub(1, cA, 1, rA);
{
this.m_ay = Rot.mul(qA, this.m_localYAxisA);
this.m_sAy = Vec2.cross(Vec2.add(d, rA), this.m_ay);
this.m_sBy = Vec2.cross(rB, this.m_ay);
this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy;
if (this.m_mass > 0) {
this.m_mass = 1 / this.m_mass;
}
}
this.m_springMass = 0;
this.m_bias = 0;
this.m_gamma = 0;
if (this.m_frequencyHz > 0) {
this.m_ax = Rot.mul(qA, this.m_localXAxisA);
this.m_sAx = Vec2.cross(Vec2.add(d, rA), this.m_ax);
this.m_sBx = Vec2.cross(rB, this.m_ax);
var invMass = mA + mB + iA * this.m_sAx * this.m_sAx + iB * this.m_sBx * this.m_sBx;
if (invMass > 0) {
this.m_springMass = 1 / invMass;
var C = Vec2.dot(d, this.m_ax);
var omega = 2 * Math.PI * this.m_frequencyHz;
var d = 2 * this.m_springMass * this.m_dampingRatio * omega;
var k = this.m_springMass * omega * omega;
var h = step.dt;
this.m_gamma = h * (d + h * k);
if (this.m_gamma > 0) {
this.m_gamma = 1 / this.m_gamma;
}
this.m_bias = C * h * k * this.m_gamma;
this.m_springMass = invMass + this.m_gamma;
if (this.m_springMass > 0) {
this.m_springMass = 1 / this.m_springMass;
}
}
} else {
this.m_springImpulse = 0;
}
if (this.m_enableMotor) {
this.m_motorMass = iA + iB;
if (this.m_motorMass > 0) {
this.m_motorMass = 1 / this.m_motorMass;
}
} else {
this.m_motorMass = 0;
this.m_motorImpulse = 0;
}
if (step.warmStarting) {
this.m_impulse *= step.dtRatio;
this.m_springImpulse *= step.dtRatio;
this.m_motorImpulse *= step.dtRatio;
var P = Vec2.wAdd(this.m_impulse, this.m_ay, this.m_springImpulse, this.m_ax);
var LA = this.m_impulse * this.m_sAy + this.m_springImpulse * this.m_sAx + this.m_motorImpulse;
var LB = this.m_impulse * this.m_sBy + this.m_springImpulse * this.m_sBx + this.m_motorImpulse;
vA.wSub(this.m_invMassA, P);
wA -= this.m_invIA * LA;
vB.wAdd(this.m_invMassB, P);
wB += this.m_invIB * LB;
} else {
this.m_impulse = 0;
this.m_springImpulse = 0;
this.m_motorImpulse = 0;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
WheelJoint.prototype.solveVelocityConstraints = function(step) {
var mA = this.m_invMassA;
var mB = this.m_invMassB;
var iA = this.m_invIA;
var iB = this.m_invIB;
var vA = this.m_bodyA.c_velocity.v;
var wA = this.m_bodyA.c_velocity.w;
var vB = this.m_bodyB.c_velocity.v;
var wB = this.m_bodyB.c_velocity.w;
{
var Cdot = Vec2.dot(this.m_ax, vB) - Vec2.dot(this.m_ax, vA) + this.m_sBx * wB - this.m_sAx * wA;
var impulse = -this.m_springMass * (Cdot + this.m_bias + this.m_gamma * this.m_springImpulse);
this.m_springImpulse += impulse;
var P = Vec2.zero().wSet(impulse, this.m_ax);
var LA = impulse * this.m_sAx;
var LB = impulse * this.m_sBx;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
}
{
var Cdot = wB - wA - this.m_motorSpeed;
var impulse = -this.m_motorMass * Cdot;
var oldImpulse = this.m_motorImpulse;
var maxImpulse = step.dt * this.m_maxMotorTorque;
this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
{
var Cdot = Vec2.dot(this.m_ay, vB) - Vec2.dot(this.m_ay, vA) + this.m_sBy * wB - this.m_sAy * wA;
var impulse = -this.m_mass * Cdot;
this.m_impulse += impulse;
var P = Vec2.zero().wSet(impulse, this.m_ay);
var LA = impulse * this.m_sAy;
var LB = impulse * this.m_sBy;
vA.wSub(mA, P);
wA -= iA * LA;
vB.wAdd(mB, P);
wB += iB * LB;
}
this.m_bodyA.c_velocity.v.set(vA);
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v.set(vB);
this.m_bodyB.c_velocity.w = wB;
};
WheelJoint.prototype.solvePositionConstraints = function(step) {
var cA = this.m_bodyA.c_position.c;
var aA = this.m_bodyA.c_position.a;
var cB = this.m_bodyB.c_position.c;
var aB = this.m_bodyB.c_position.a;
var qA = Rot.neo(aA);
var qB = Rot.neo(aB);
var rA = Rot.mul(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
var rB = Rot.mul(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
var d = Vec2.zero();
d.wAdd(1, cB, 1, rB);
d.wSub(1, cA, 1, rA);
var ay = Rot.mul(qA, this.m_localYAxisA);
var sAy = Vec2.cross(Vec2.sub(d, rA), ay);
var sBy = Vec2.cross(rB, ay);
var C = Vec2.dot(d, ay);
var k = this.m_invMassA + this.m_invMassB + this.m_invIA * this.m_sAy * this.m_sAy + this.m_invIB * this.m_sBy * this.m_sBy;
var impulse;
if (k != 0) {
impulse = -C / k;
} else {
impulse = 0;
}
var P = Vec2.zero().wSet(impulse, ay);
var LA = impulse * sAy;
var LB = impulse * sBy;
cA.wSub(this.m_invMassA, P);
aA -= this.m_invIA * LA;
cB.wAdd(this.m_invMassB, P);
aB += this.m_invIB * LB;
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return Math.abs(C) <= Settings.linearSlop;
};
},{"../Joint":5,"../Settings":7,"../common/Mat22":16,"../common/Mat33":17,"../common/Math":18,"../common/Position":19,"../common/Rot":20,"../common/Sweep":21,"../common/Transform":22,"../common/Vec2":23,"../common/Vec3":24,"../common/Velocity":25,"../util/create":52,"../util/options":53}],39:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = BoxShape;
var common = require("../util/common");
var create = require("../util/create");
var options = require("../util/options");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var PolygonShape = require("./PolygonShape");
BoxShape._super = PolygonShape;
BoxShape.prototype = create(BoxShape._super.prototype);
BoxShape.TYPE = "polygon";
function BoxShape(hx, hy, center, angle) {
if (!(this instanceof BoxShape)) {
return new BoxShape(hx, hy, center, angle);
}
BoxShape._super.call(this);
this.m_vertices[0] = Vec2.neo(-hx, -hy);
this.m_vertices[1] = Vec2.neo(hx, -hy);
this.m_vertices[2] = Vec2.neo(hx, hy);
this.m_vertices[3] = Vec2.neo(-hx, hy);
this.m_normals[0] = Vec2.neo(0, -1);
this.m_normals[1] = Vec2.neo(1, 0);
this.m_normals[2] = Vec2.neo(0, 1);
this.m_normals[3] = Vec2.neo(-1, 0);
this.m_count = 4;
if (center && "x" in center && "y" in center) {
angle = angle || 0;
this.m_centroid.set(center);
var xf = Transform.identity();
xf.p.set(center);
xf.q.set(angle);
for (var i = 0; i < this.m_count; ++i) {
this.m_vertices[i] = Transform.mul(xf, this.m_vertices[i]);
this.m_normals[i] = Rot.mul(xf.q, this.m_normals[i]);
}
}
}
},{"../Settings":7,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./PolygonShape":48}],40:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = ChainShape;
var common = require("../util/common");
var create = require("../util/create");
var options = require("../util/options");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var Shape = require("../Shape");
var EdgeShape = require("./EdgeShape");
ChainShape._super = Shape;
ChainShape.prototype = create(ChainShape._super.prototype);
ChainShape.TYPE = "chain";
function ChainShape(vertices, loop) {
if (!(this instanceof ChainShape)) {
return new ChainShape(vertices, loop);
}
ChainShape._super.call(this);
this.m_type = ChainShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_vertices = [];
this.m_count = 0;
this.m_prevVertex = null;
this.m_nextVertex = null;
this.m_hasPrevVertex = false;
this.m_hasNextVertex = false;
if (vertices && vertices.length) {
if (loop) {
this._createLoop(vertices);
} else {
this._createChain(vertices);
}
}
}
ChainShape.prototype._createLoop = function(vertices) {
ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0);
ASSERT && common.assert(vertices.length >= 3);
for (var i = 1; i < vertices.length; ++i) {
var v1 = vertices[i - 1];
var v2 = vertices[i];
ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared);
}
this.m_vertices.length = 0;
this.m_count = vertices.length + 1;
for (var i = 0; i < vertices.length; ++i) {
this.m_vertices[i] = vertices[i].clone();
}
this.m_vertices[vertices.length] = vertices[0].clone();
this.m_prevVertex = this.m_vertices[this.m_count - 2];
this.m_nextVertex = this.m_vertices[1];
this.m_hasPrevVertex = true;
this.m_hasNextVertex = true;
return this;
};
ChainShape.prototype._createChain = function(vertices) {
ASSERT && common.assert(this.m_vertices.length == 0 && this.m_count == 0);
ASSERT && common.assert(vertices.length >= 2);
for (var i = 1; i < vertices.length; ++i) {
var v1 = vertices[i - 1];
var v2 = vertices[i];
ASSERT && common.assert(Vec2.distanceSquared(v1, v2) > Settings.linearSlopSquared);
}
this.m_count = vertices.length;
for (var i = 0; i < vertices.length; ++i) {
this.m_vertices[i] = vertices[i].clone();
}
this.m_hasPrevVertex = false;
this.m_hasNextVertex = false;
this.m_prevVertex = null;
this.m_nextVertex = null;
return this;
};
ChainShape.prototype._setPrevVertex = function(prevVertex) {
this.m_prevVertex = prevVertex;
this.m_hasPrevVertex = true;
};
ChainShape.prototype._setNextVertex = function(nextVertex) {
this.m_nextVertex = nextVertex;
this.m_hasNextVertex = true;
};
ChainShape.prototype._clone = function() {
var clone = new ChainShape();
clone.createChain(this.m_vertices);
clone.m_type = this.m_type;
clone.m_radius = this.m_radius;
clone.m_prevVertex = this.m_prevVertex;
clone.m_nextVertex = this.m_nextVertex;
clone.m_hasPrevVertex = this.m_hasPrevVertex;
clone.m_hasNextVertex = this.m_hasNextVertex;
return clone;
};
ChainShape.prototype.getChildCount = function() {
return this.m_count - 1;
};
ChainShape.prototype.getChildEdge = function(edge, childIndex) {
ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count - 1);
edge.m_type = EdgeShape.TYPE;
edge.m_radius = this.m_radius;
edge.m_vertex1 = this.m_vertices[childIndex];
edge.m_vertex2 = this.m_vertices[childIndex + 1];
if (childIndex > 0) {
edge.m_vertex0 = this.m_vertices[childIndex - 1];
edge.m_hasVertex0 = true;
} else {
edge.m_vertex0 = this.m_prevVertex;
edge.m_hasVertex0 = this.m_hasPrevVertex;
}
if (childIndex < this.m_count - 2) {
edge.m_vertex3 = this.m_vertices[childIndex + 2];
edge.m_hasVertex3 = true;
} else {
edge.m_vertex3 = this.m_nextVertex;
edge.m_hasVertex3 = this.m_hasNextVertex;
}
};
ChainShape.prototype.getVertex = function(index) {
ASSERT && common.assert(0 <= index && index <= this.m_count);
if (index < this.m_count) {
return this.m_vertices[index];
} else {
return this.m_vertices[0];
}
};
ChainShape.prototype.testPoint = function(xf, p) {
return false;
};
ChainShape.prototype.rayCast = function(output, input, xf, childIndex) {
ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count);
var edgeShape = new EdgeShape(this.getVertex(childIndex), this.getVertex(childIndex + 1));
return edgeShape.rayCast(output, input, xf, 0);
};
ChainShape.prototype.computeAABB = function(aabb, xf, childIndex) {
ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count);
var v1 = Transform.mul(xf, this.getVertex(childIndex));
var v2 = Transform.mul(xf, this.getVertex(childIndex + 1));
aabb.combinePoints(v1, v2);
};
ChainShape.prototype.computeMass = function(massData, density) {
massData.mass = 0;
massData.center = Vec2.neo();
massData.I = 0;
};
ChainShape.prototype.computeDistanceProxy = function(proxy, childIndex) {
ASSERT && common.assert(0 <= childIndex && childIndex < this.m_count);
proxy.m_buffer[0] = this.getVertex(childIndex);
proxy.m_buffer[1] = this.getVertex(childIndex + 1);
proxy.m_vertices = proxy.m_buffer;
proxy.m_count = 2;
proxy.m_radius = this.m_radius;
};
},{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53,"./EdgeShape":47}],41:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = CircleShape;
var common = require("../util/common");
var create = require("../util/create");
var options = require("../util/options");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var Shape = require("../Shape");
CircleShape._super = Shape;
CircleShape.prototype = create(CircleShape._super.prototype);
CircleShape.TYPE = "circle";
function CircleShape(a, b) {
if (!(this instanceof CircleShape)) {
return new CircleShape(a, b);
}
CircleShape._super.call(this);
this.m_type = CircleShape.TYPE;
this.m_p = Vec2.zero();
this.m_radius = 1;
if (typeof a === "object" && Vec2.isValid(a)) {
this.m_p.set(a);
if (typeof b === "number") {
this.m_radius = b;
}
} else if (typeof a === "number") {
this.m_radius = a;
}
}
CircleShape.prototype.getRadius = function() {
return this.m_radius;
};
CircleShape.prototype.getCenter = function() {
return this.m_p;
};
CircleShape.prototype.getSupportVertex = function(d) {
return this.m_p;
};
CircleShape.prototype.getVertex = function(index) {
ASSERT && common.assert(index == 0);
return this.m_p;
};
CircleShape.prototype.getVertexCount = function(index) {
return 1;
};
CircleShape.prototype._clone = function() {
var clone = new CircleShape();
clone.m_type = this.m_type;
clone.m_radius = this.m_radius;
clone.m_p = this.m_p.clone();
return clone;
};
CircleShape.prototype.getChildCount = function() {
return 1;
};
CircleShape.prototype.testPoint = function(xf, p) {
var center = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p));
var d = Vec2.sub(p, center);
return Vec2.dot(d, d) <= this.m_radius * this.m_radius;
};
CircleShape.prototype.rayCast = function(output, input, xf, childIndex) {
var position = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p));
var s = Vec2.sub(input.p1, position);
var b = Vec2.dot(s, s) - this.m_radius * this.m_radius;
var r = Vec2.sub(input.p2, input.p1);
var c = Vec2.dot(s, r);
var rr = Vec2.dot(r, r);
var sigma = c * c - rr * b;
if (sigma < 0 || rr < Math.EPSILON) {
return false;
}
var a = -(c + Math.sqrt(sigma));
if (0 <= a && a <= input.maxFraction * rr) {
a /= rr;
output.fraction = a;
output.normal = Vec2.add(s, Vec2.mul(a, r));
output.normal.normalize();
return true;
}
return false;
};
CircleShape.prototype.computeAABB = function(aabb, xf, childIndex) {
var p = Vec2.add(xf.p, Rot.mul(xf.q, this.m_p));
aabb.lowerBound.set(p.x - this.m_radius, p.y - this.m_radius);
aabb.upperBound.set(p.x + this.m_radius, p.y + this.m_radius);
};
CircleShape.prototype.computeMass = function(massData, density) {
massData.mass = density * Math.PI * this.m_radius * this.m_radius;
massData.center = this.m_p;
massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + Vec2.dot(this.m_p, this.m_p));
};
CircleShape.prototype.computeDistanceProxy = function(proxy) {
proxy.m_vertices.push(this.m_p);
proxy.m_count = 1;
proxy.m_radius = this.m_radius;
};
},{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],42:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var create = require("../util/create");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Vec2 = require("../common/Vec2");
var Settings = require("../Settings");
var Shape = require("../Shape");
var Contact = require("../Contact");
var Manifold = require("../Manifold");
var CircleShape = require("./CircleShape");
Contact.addType(CircleShape.TYPE, CircleShape.TYPE, CircleCircleContact);
function CircleCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) {
ASSERT && common.assert(fixtureA.getType() == CircleShape.TYPE);
ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE);
CollideCircles(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB);
}
function CollideCircles(manifold, circleA, xfA, circleB, xfB) {
manifold.pointCount = 0;
var pA = Transform.mul(xfA, circleA.m_p);
var pB = Transform.mul(xfB, circleB.m_p);
var distSqr = Vec2.distanceSquared(pB, pA);
var rA = circleA.m_radius;
var rB = circleB.m_radius;
var radius = rA + rB;
if (distSqr > radius * radius) {
return;
}
manifold.type = Manifold.e_circles;
manifold.localPoint.set(circleA.m_p);
manifold.localNormal.setZero();
manifold.pointCount = 1;
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
}
exports.CollideCircles = CollideCircles;
},{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./CircleShape":41}],43:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var Manifold = require("../Manifold");
var Contact = require("../Contact");
var Shape = require("../Shape");
var CircleShape = require("./CircleShape");
var PolygonShape = require("./PolygonShape");
Contact.addType(PolygonShape.TYPE, CircleShape.TYPE, PolygonCircleContact);
function PolygonCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) {
ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE);
ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE);
CollidePolygonCircle(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB);
}
function CollidePolygonCircle(manifold, polygonA, xfA, circleB, xfB) {
manifold.pointCount = 0;
var c = Transform.mul(xfB, circleB.m_p);
var cLocal = Transform.mulT(xfA, c);
var normalIndex = 0;
var separation = -Infinity;
var radius = polygonA.m_radius + circleB.m_radius;
var vertexCount = polygonA.m_count;
var vertices = polygonA.m_vertices;
var normals = polygonA.m_normals;
for (var i = 0; i < vertexCount; ++i) {
var s = Vec2.dot(normals[i], Vec2.sub(cLocal, vertices[i]));
if (s > radius) {
return;
}
if (s > separation) {
separation = s;
normalIndex = i;
}
}
var vertIndex1 = normalIndex;
var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;
var v1 = vertices[vertIndex1];
var v2 = vertices[vertIndex2];
if (separation < Math.EPSILON) {
manifold.pointCount = 1;
manifold.type = Manifold.e_faceA;
manifold.localNormal.set(normals[normalIndex]);
manifold.localPoint.wSet(.5, v1, .5, v2);
manifold.points[0].localPoint = circleB.m_p;
manifold.points[0].id.key = 0;
return;
}
var u1 = Vec2.dot(Vec2.sub(cLocal, v1), Vec2.sub(v2, v1));
var u2 = Vec2.dot(Vec2.sub(cLocal, v2), Vec2.sub(v1, v2));
if (u1 <= 0) {
if (Vec2.distanceSquared(cLocal, v1) > radius * radius) {
return;
}
manifold.pointCount = 1;
manifold.type = Manifold.e_faceA;
manifold.localNormal.wSet(1, cLocal, -1, v1);
manifold.localNormal.normalize();
manifold.localPoint = v1;
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
} else if (u2 <= 0) {
if (Vec2.distanceSquared(cLocal, v2) > radius * radius) {
return;
}
manifold.pointCount = 1;
manifold.type = Manifold.e_faceA;
manifold.localNormal.wSet(1, cLocal, -1, v2);
manifold.localNormal.normalize();
manifold.localPoint.set(v2);
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
} else {
var faceCenter = Vec2.mid(v1, v2);
var separation = Vec2.dot(cLocal, normals[vertIndex1]) - Vec2.dot(faceCenter, normals[vertIndex1]);
if (separation > radius) {
return;
}
manifold.pointCount = 1;
manifold.type = Manifold.e_faceA;
manifold.localNormal.set(normals[vertIndex1]);
manifold.localPoint.set(faceCenter);
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
}
}
},{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./CircleShape":41,"./PolygonShape":48}],44:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var create = require("../util/create");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Vec2 = require("../common/Vec2");
var Rot = require("../common/Rot");
var Settings = require("../Settings");
var Shape = require("../Shape");
var Contact = require("../Contact");
var Manifold = require("../Manifold");
var EdgeShape = require("./EdgeShape");
var ChainShape = require("./ChainShape");
var CircleShape = require("./CircleShape");
Contact.addType(EdgeShape.TYPE, CircleShape.TYPE, EdgeCircleContact);
Contact.addType(ChainShape.TYPE, CircleShape.TYPE, ChainCircleContact);
function EdgeCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) {
ASSERT && common.assert(fixtureA.getType() == EdgeShape.TYPE);
ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE);
var shapeA = fixtureA.getShape();
var shapeB = fixtureB.getShape();
CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB);
}
function ChainCircleContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) {
ASSERT && common.assert(fixtureA.getType() == ChainShape.TYPE);
ASSERT && common.assert(fixtureB.getType() == CircleShape.TYPE);
var chain = fixtureA.getShape();
var edge = new EdgeShape();
chain.getChildEdge(edge, indexA);
var shapeA = edge;
var shapeB = fixtureB.getShape();
CollideEdgeCircle(manifold, shapeA, xfA, shapeB, xfB);
}
function CollideEdgeCircle(manifold, edgeA, xfA, circleB, xfB) {
manifold.pointCount = 0;
var Q = Transform.mulT(xfA, Transform.mul(xfB, circleB.m_p));
var A = edgeA.m_vertex1;
var B = edgeA.m_vertex2;
var e = Vec2.sub(B, A);
var u = Vec2.dot(e, Vec2.sub(B, Q));
var v = Vec2.dot(e, Vec2.sub(Q, A));
var radius = edgeA.m_radius + circleB.m_radius;
if (v <= 0) {
var P = Vec2.clone(A);
var d = Vec2.sub(Q, P);
var dd = Vec2.dot(d, d);
if (dd > radius * radius) {
return;
}
if (edgeA.m_hasVertex0) {
var A1 = edgeA.m_vertex0;
var B1 = A;
var e1 = Vec2.sub(B1, A1);
var u1 = Vec2.dot(e1, Vec2.sub(B1, Q));
if (u1 > 0) {
return;
}
}
manifold.type = Manifold.e_circles;
manifold.localNormal.setZero();
manifold.localPoint.set(P);
manifold.pointCount = 1;
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
manifold.points[0].id.cf.indexA = 0;
manifold.points[0].id.cf.typeA = Manifold.e_vertex;
manifold.points[0].id.cf.indexB = 0;
manifold.points[0].id.cf.typeB = Manifold.e_vertex;
return;
}
if (u <= 0) {
var P = Vec2.clone(B);
var d = Vec2.sub(Q, P);
var dd = Vec2.dot(d, d);
if (dd > radius * radius) {
return;
}
if (edgeA.m_hasVertex3) {
var B2 = edgeA.m_vertex3;
var A2 = B;
var e2 = Vec2.sub(B2, A2);
var v2 = Vec2.dot(e2, Vec2.sub(Q, A2));
if (v2 > 0) {
return;
}
}
manifold.type = Manifold.e_circles;
manifold.localNormal.setZero();
manifold.localPoint.set(P);
manifold.pointCount = 1;
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
manifold.points[0].id.cf.indexA = 1;
manifold.points[0].id.cf.typeA = Manifold.e_vertex;
manifold.points[0].id.cf.indexB = 0;
manifold.points[0].id.cf.typeB = Manifold.e_vertex;
return;
}
var den = Vec2.dot(e, e);
ASSERT && common.assert(den > 0);
var P = Vec2.wAdd(u / den, A, v / den, B);
var d = Vec2.sub(Q, P);
var dd = Vec2.dot(d, d);
if (dd > radius * radius) {
return;
}
var n = Vec2.neo(-e.y, e.x);
if (Vec2.dot(n, Vec2.sub(Q, A)) < 0) {
n.set(-n.x, -n.y);
}
n.normalize();
manifold.type = Manifold.e_faceA;
manifold.localNormal = n;
manifold.localPoint.set(A);
manifold.pointCount = 1;
manifold.points[0].localPoint.set(circleB.m_p);
manifold.points[0].id.key = 0;
manifold.points[0].id.cf.indexA = 0;
manifold.points[0].id.cf.typeA = Manifold.e_face;
manifold.points[0].id.cf.indexB = 0;
manifold.points[0].id.cf.typeB = Manifold.e_vertex;
}
},{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./CircleShape":41,"./EdgeShape":47}],45:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var create = require("../util/create");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Vec2 = require("../common/Vec2");
var Rot = require("../common/Rot");
var Settings = require("../Settings");
var Shape = require("../Shape");
var Contact = require("../Contact");
var Manifold = require("../Manifold");
var EdgeShape = require("./EdgeShape");
var ChainShape = require("./ChainShape");
var PolygonShape = require("./PolygonShape");
Contact.addType(EdgeShape.TYPE, PolygonShape.TYPE, EdgePolygonContact);
Contact.addType(ChainShape.TYPE, PolygonShape.TYPE, ChainPolygonContact);
function EdgePolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) {
ASSERT && common.assert(fA.getType() == EdgeShape.TYPE);
ASSERT && common.assert(fB.getType() == PolygonShape.TYPE);
CollideEdgePolygon(manifold, fA.getShape(), xfA, fB.getShape(), xfB);
}
function ChainPolygonContact(manifold, xfA, fA, indexA, xfB, fB, indexB) {
ASSERT && common.assert(fA.getType() == ChainShape.TYPE);
ASSERT && common.assert(fB.getType() == PolygonShape.TYPE);
var chain = fA.getShape();
var edge = new EdgeShape();
chain.getChildEdge(edge, indexA);
CollideEdgePolygon(manifold, edge, xfA, fB.getShape(), xfB);
}
var e_unknown = -1;
var e_edgeA = 1;
var e_edgeB = 2;
var e_isolated = 0;
var e_concave = 1;
var e_convex = 2;
function EPAxis() {
this.type;
this.index;
this.separation;
}
function TempPolygon() {
this.vertices = [];
this.normals = [];
this.count = 0;
}
function ReferenceFace() {
this.i1, this.i2;
this.v1, this.v2;
this.normal = Vec2.zero();
this.sideNormal1 = Vec2.zero();
this.sideOffset1;
this.sideNormal2 = Vec2.zero();
this.sideOffset2;
}
var edgeAxis = new EPAxis();
var polygonAxis = new EPAxis();
var polygonBA = new TempPolygon();
var rf = new ReferenceFace();
function CollideEdgePolygon(manifold, edgeA, xfA, polygonB, xfB) {
DEBUG && common.debug("CollideEdgePolygon");
var m_type1, m_type2;
var xf = Transform.mulT(xfA, xfB);
var centroidB = Transform.mul(xf, polygonB.m_centroid);
var v0 = edgeA.m_vertex0;
var v1 = edgeA.m_vertex1;
var v2 = edgeA.m_vertex2;
var v3 = edgeA.m_vertex3;
var hasVertex0 = edgeA.m_hasVertex0;
var hasVertex3 = edgeA.m_hasVertex3;
var edge1 = Vec2.sub(v2, v1);
edge1.normalize();
var normal1 = Vec2.neo(edge1.y, -edge1.x);
var offset1 = Vec2.dot(normal1, Vec2.sub(centroidB, v1));
var offset0 = 0;
var offset2 = 0;
var convex1 = false;
var convex2 = false;
if (hasVertex0) {
var edge0 = Vec2.sub(v1, v0);
edge0.normalize();
var normal0 = Vec2.neo(edge0.y, -edge0.x);
convex1 = Vec2.cross(edge0, edge1) >= 0;
offset0 = Vec2.dot(normal0, centroidB) - Vec2.dot(normal0, v0);
}
if (hasVertex3) {
var edge2 = Vec2.sub(v3, v2);
edge2.normalize();
var normal2 = Vec2.neo(edge2.y, -edge2.x);
convex2 = Vec2.cross(edge1, edge2) > 0;
offset2 = Vec2.dot(normal2, centroidB) - Vec2.dot(normal2, v2);
}
var front;
var normal = Vec2.zero();
var lowerLimit = Vec2.zero();
var upperLimit = Vec2.zero();
if (hasVertex0 && hasVertex3) {
if (convex1 && convex2) {
front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal0);
upperLimit.set(normal2);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.wSet(-1, normal1);
}
} else if (convex1) {
front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal0);
upperLimit.set(normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal2);
upperLimit.wSet(-1, normal1);
}
} else if (convex2) {
front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal1);
upperLimit.set(normal2);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.wSet(-1, normal0);
}
} else {
front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal1);
upperLimit.set(normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal2);
upperLimit.wSet(-1, normal0);
}
}
} else if (hasVertex0) {
if (convex1) {
front = offset0 >= 0 || offset1 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal0);
upperLimit.wSet(-1, normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.set(normal1);
upperLimit.wSet(-1, normal1);
}
} else {
front = offset0 >= 0 && offset1 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.set(normal1);
upperLimit.wSet(-1, normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.set(normal1);
upperLimit.wSet(-1, normal0);
}
}
} else if (hasVertex3) {
if (convex2) {
front = offset1 >= 0 || offset2 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.set(normal2);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.set(normal1);
}
} else {
front = offset1 >= 0 && offset2 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.set(normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.wSet(-1, normal2);
upperLimit.set(normal1);
}
}
} else {
front = offset1 >= 0;
if (front) {
normal.set(normal1);
lowerLimit.wSet(-1, normal1);
upperLimit.wSet(-1, normal1);
} else {
normal.wSet(-1, normal1);
lowerLimit.set(normal1);
upperLimit.set(normal1);
}
}
polygonBA.count = polygonB.m_count;
for (var i = 0; i < polygonB.m_count; ++i) {
polygonBA.vertices[i] = Transform.mul(xf, polygonB.m_vertices[i]);
polygonBA.normals[i] = Rot.mul(xf.q, polygonB.m_normals[i]);
}
var radius = 2 * Settings.polygonRadius;
manifold.pointCount = 0;
{
edgeAxis.type = e_edgeA;
edgeAxis.index = front ? 0 : 1;
edgeAxis.separation = Infinity;
for (var i = 0; i < polygonBA.count; ++i) {
var s = Vec2.dot(normal, Vec2.sub(polygonBA.vertices[i], v1));
if (s < edgeAxis.separation) {
edgeAxis.separation = s;
}
}
}
if (edgeAxis.type == e_unknown) {
return;
}
if (edgeAxis.separation > radius) {
return;
}
{
polygonAxis.type = e_unknown;
polygonAxis.index = -1;
polygonAxis.separation = -Infinity;
var perp = Vec2.neo(-normal.y, normal.x);
for (var i = 0; i < polygonBA.count; ++i) {
var n = Vec2.neg(polygonBA.normals[i]);
var s1 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v1));
var s2 = Vec2.dot(n, Vec2.sub(polygonBA.vertices[i], v2));
var s = Math.min(s1, s2);
if (s > radius) {
polygonAxis.type = e_edgeB;
polygonAxis.index = i;
polygonAxis.separation = s;
break;
}
if (Vec2.dot(n, perp) >= 0) {
if (Vec2.dot(Vec2.sub(n, upperLimit), normal) < -Settings.angularSlop) {
continue;
}
} else {
if (Vec2.dot(Vec2.sub(n, lowerLimit), normal) < -Settings.angularSlop) {
continue;
}
}
if (s > polygonAxis.separation) {
polygonAxis.type = e_edgeB;
polygonAxis.index = i;
polygonAxis.separation = s;
}
}
}
if (polygonAxis.type != e_unknown && polygonAxis.separation > radius) {
return;
}
var k_relativeTol = .98;
var k_absoluteTol = .001;
var primaryAxis;
if (polygonAxis.type == e_unknown) {
primaryAxis = edgeAxis;
} else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) {
primaryAxis = polygonAxis;
} else {
primaryAxis = edgeAxis;
}
var ie = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
if (primaryAxis.type == e_edgeA) {
manifold.type = Manifold.e_faceA;
var bestIndex = 0;
var bestValue = Vec2.dot(normal, polygonBA.normals[0]);
for (var i = 1; i < polygonBA.count; ++i) {
var value = Vec2.dot(normal, polygonBA.normals[i]);
if (value < bestValue) {
bestValue = value;
bestIndex = i;
}
}
var i1 = bestIndex;
var i2 = i1 + 1 < polygonBA.count ? i1 + 1 : 0;
ie[0].v = polygonBA.vertices[i1];
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = i1;
ie[0].id.cf.typeA = Manifold.e_face;
ie[0].id.cf.typeB = Manifold.e_vertex;
ie[1].v = polygonBA.vertices[i2];
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = i2;
ie[1].id.cf.typeA = Manifold.e_face;
ie[1].id.cf.typeB = Manifold.e_vertex;
if (front) {
rf.i1 = 0;
rf.i2 = 1;
rf.v1 = v1;
rf.v2 = v2;
rf.normal.set(normal1);
} else {
rf.i1 = 1;
rf.i2 = 0;
rf.v1 = v2;
rf.v2 = v1;
rf.normal.wSet(-1, normal1);
}
} else {
manifold.type = Manifold.e_faceB;
ie[0].v = v1;
ie[0].id.cf.indexA = 0;
ie[0].id.cf.indexB = primaryAxis.index;
ie[0].id.cf.typeA = Manifold.e_vertex;
ie[0].id.cf.typeB = Manifold.e_face;
ie[1].v = v2;
ie[1].id.cf.indexA = 0;
ie[1].id.cf.indexB = primaryAxis.index;
ie[1].id.cf.typeA = Manifold.e_vertex;
ie[1].id.cf.typeB = Manifold.e_face;
rf.i1 = primaryAxis.index;
rf.i2 = rf.i1 + 1 < polygonBA.count ? rf.i1 + 1 : 0;
rf.v1 = polygonBA.vertices[rf.i1];
rf.v2 = polygonBA.vertices[rf.i2];
rf.normal.set(polygonBA.normals[rf.i1]);
}
rf.sideNormal1.set(rf.normal.y, -rf.normal.x);
rf.sideNormal2.wSet(-1, rf.sideNormal1);
rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1);
rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2);
var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
var np;
np = Manifold.clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1);
if (np < Settings.maxManifoldPoints) {
return;
}
np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2);
if (np < Settings.maxManifoldPoints) {
return;
}
if (primaryAxis.type == e_edgeA) {
manifold.localNormal = Vec2.clone(rf.normal);
manifold.localPoint = Vec2.clone(rf.v1);
} else {
manifold.localNormal = Vec2.clone(polygonB.m_normals[rf.i1]);
manifold.localPoint = Vec2.clone(polygonB.m_vertices[rf.i1]);
}
var pointCount = 0;
for (var i = 0; i < Settings.maxManifoldPoints; ++i) {
var separation = Vec2.dot(rf.normal, Vec2.sub(clipPoints2[i].v, rf.v1));
if (separation <= radius) {
var cp = manifold.points[pointCount];
if (primaryAxis.type == e_edgeA) {
cp.localPoint = Transform.mulT(xf, clipPoints2[i].v);
cp.id = clipPoints2[i].id;
} else {
cp.localPoint = clipPoints2[i].v;
cp.id.cf.typeA = clipPoints2[i].id.cf.typeB;
cp.id.cf.typeB = clipPoints2[i].id.cf.typeA;
cp.id.cf.indexA = clipPoints2[i].id.cf.indexB;
cp.id.cf.indexB = clipPoints2[i].id.cf.indexA;
}
++pointCount;
}
}
manifold.pointCount = pointCount;
}
},{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"./ChainShape":40,"./EdgeShape":47,"./PolygonShape":48}],46:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var common = require("../util/common");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var Manifold = require("../Manifold");
var Contact = require("../Contact");
var Shape = require("../Shape");
var PolygonShape = require("./PolygonShape");
module.exports = CollidePolygons;
Contact.addType(PolygonShape.TYPE, PolygonShape.TYPE, PolygonContact);
function PolygonContact(manifold, xfA, fixtureA, indexA, xfB, fixtureB, indexB) {
ASSERT && common.assert(fixtureA.getType() == PolygonShape.TYPE);
ASSERT && common.assert(fixtureB.getType() == PolygonShape.TYPE);
CollidePolygons(manifold, fixtureA.getShape(), xfA, fixtureB.getShape(), xfB);
}
function FindMaxSeparation(poly1, xf1, poly2, xf2) {
var count1 = poly1.m_count;
var count2 = poly2.m_count;
var n1s = poly1.m_normals;
var v1s = poly1.m_vertices;
var v2s = poly2.m_vertices;
var xf = Transform.mulT(xf2, xf1);
var bestIndex = 0;
var maxSeparation = -Infinity;
for (var i = 0; i < count1; ++i) {
var n = Rot.mul(xf.q, n1s[i]);
var v1 = Transform.mul(xf, v1s[i]);
var si = Infinity;
for (var j = 0; j < count2; ++j) {
var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);
if (sij < si) {
si = sij;
}
}
if (si > maxSeparation) {
maxSeparation = si;
bestIndex = i;
}
}
FindMaxSeparation._maxSeparation = maxSeparation;
FindMaxSeparation._bestIndex = bestIndex;
}
function FindIncidentEdge(c, poly1, xf1, edge1, poly2, xf2) {
var normals1 = poly1.m_normals;
var count2 = poly2.m_count;
var vertices2 = poly2.m_vertices;
var normals2 = poly2.m_normals;
ASSERT && common.assert(0 <= edge1 && edge1 < poly1.m_count);
var normal1 = Rot.mulT(xf2.q, Rot.mul(xf1.q, normals1[edge1]));
var index = 0;
var minDot = Infinity;
for (var i = 0; i < count2; ++i) {
var dot = Vec2.dot(normal1, normals2[i]);
if (dot < minDot) {
minDot = dot;
index = i;
}
}
var i1 = index;
var i2 = i1 + 1 < count2 ? i1 + 1 : 0;
c[0].v = Transform.mul(xf2, vertices2[i1]);
c[0].id.cf.indexA = edge1;
c[0].id.cf.indexB = i1;
c[0].id.cf.typeA = Manifold.e_face;
c[0].id.cf.typeB = Manifold.e_vertex;
c[1].v = Transform.mul(xf2, vertices2[i2]);
c[1].id.cf.indexA = edge1;
c[1].id.cf.indexB = i2;
c[1].id.cf.typeA = Manifold.e_face;
c[1].id.cf.typeB = Manifold.e_vertex;
}
function CollidePolygons(manifold, polyA, xfA, polyB, xfB) {
manifold.pointCount = 0;
var totalRadius = polyA.m_radius + polyB.m_radius;
FindMaxSeparation(polyA, xfA, polyB, xfB);
var edgeA = FindMaxSeparation._bestIndex;
var separationA = FindMaxSeparation._maxSeparation;
if (separationA > totalRadius) return;
FindMaxSeparation(polyB, xfB, polyA, xfA);
var edgeB = FindMaxSeparation._bestIndex;
var separationB = FindMaxSeparation._maxSeparation;
if (separationB > totalRadius) return;
var poly1;
var poly2;
var xf1;
var xf2;
var edge1;
var flip;
var k_tol = .1 * Settings.linearSlop;
if (separationB > separationA + k_tol) {
poly1 = polyB;
poly2 = polyA;
xf1 = xfB;
xf2 = xfA;
edge1 = edgeB;
manifold.type = Manifold.e_faceB;
flip = 1;
} else {
poly1 = polyA;
poly2 = polyB;
xf1 = xfA;
xf2 = xfB;
edge1 = edgeA;
manifold.type = Manifold.e_faceA;
flip = 0;
}
var incidentEdge = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
var count1 = poly1.m_count;
var vertices1 = poly1.m_vertices;
var iv1 = edge1;
var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;
var v11 = vertices1[iv1];
var v12 = vertices1[iv2];
var localTangent = Vec2.sub(v12, v11);
localTangent.normalize();
var localNormal = Vec2.cross(localTangent, 1);
var planePoint = Vec2.wAdd(.5, v11, .5, v12);
var tangent = Rot.mul(xf1.q, localTangent);
var normal = Vec2.cross(tangent, 1);
v11 = Transform.mul(xf1, v11);
v12 = Transform.mul(xf1, v12);
var frontOffset = Vec2.dot(normal, v11);
var sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius;
var sideOffset2 = Vec2.dot(tangent, v12) + totalRadius;
var clipPoints1 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
var clipPoints2 = [ new Manifold.clipVertex(), new Manifold.clipVertex() ];
var np;
np = Manifold.clipSegmentToLine(clipPoints1, incidentEdge, Vec2.neg(tangent), sideOffset1, iv1);
if (np < 2) {
return;
}
np = Manifold.clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2);
if (np < 2) {
return;
}
manifold.localNormal = localNormal;
manifold.localPoint = planePoint;
var pointCount = 0;
for (var i = 0; i < clipPoints2.length; ++i) {
var separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset;
if (separation <= totalRadius) {
var cp = manifold.points[pointCount];
cp.localPoint.set(Transform.mulT(xf2, clipPoints2[i].v));
cp.id = clipPoints2[i].id;
if (flip) {
var cf = cp.id.cf;
var indexA = cf.indexA;
var indexB = cf.indexB;
var typeA = cf.typeA;
var typeB = cf.typeB;
cf.indexA = indexB;
cf.indexB = indexA;
cf.typeA = typeB;
cf.typeB = typeA;
}
++pointCount;
}
}
manifold.pointCount = pointCount;
}
},{"../Contact":3,"../Manifold":6,"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"./PolygonShape":48}],47:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = EdgeShape;
var create = require("../util/create");
var options = require("../util/options");
var Settings = require("../Settings");
var Shape = require("../Shape");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
EdgeShape._super = Shape;
EdgeShape.prototype = create(EdgeShape._super.prototype);
EdgeShape.TYPE = "edge";
function EdgeShape(v1, v2) {
if (!(this instanceof EdgeShape)) {
return new EdgeShape(v1, v2);
}
EdgeShape._super.call(this);
this.m_type = EdgeShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_vertex1 = v1 ? Vec2.clone(v1) : Vec2.zero();
this.m_vertex2 = v2 ? Vec2.clone(v2) : Vec2.zero();
this.m_vertex0 = Vec2.zero();
this.m_vertex3 = Vec2.zero();
this.m_hasVertex0 = false;
this.m_hasVertex3 = false;
}
EdgeShape.prototype.setNext = function(v3) {
if (v3) {
this.m_vertex3.set(v3);
this.m_hasVertex3 = true;
} else {
this.m_vertex3.setZero();
this.m_hasVertex3 = false;
}
return this;
};
EdgeShape.prototype.setPrev = function(v0) {
if (v0) {
this.m_vertex0.set(v0);
this.m_hasVertex0 = true;
} else {
this.m_vertex0.setZero();
this.m_hasVertex0 = false;
}
return this;
};
EdgeShape.prototype._set = function(v1, v2) {
this.m_vertex1.set(v1);
this.m_vertex2.set(v2);
this.m_hasVertex0 = false;
this.m_hasVertex3 = false;
return this;
};
EdgeShape.prototype._clone = function() {
var clone = new EdgeShape();
clone.m_type = this.m_type;
clone.m_radius = this.m_radius;
clone.m_vertex1.set(this.m_vertex1);
clone.m_vertex2.set(this.m_vertex2);
clone.m_vertex0.set(this.m_vertex0);
clone.m_vertex3.set(this.m_vertex3);
clone.m_hasVertex0 = this.m_hasVertex0;
clone.m_hasVertex3 = this.m_hasVertex3;
return clone;
};
EdgeShape.prototype.getChildCount = function() {
return 1;
};
EdgeShape.prototype.testPoint = function(xf, p) {
return false;
};
EdgeShape.prototype.rayCast = function(output, input, xf, childIndex) {
var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p));
var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p));
var d = Vec2.sub(p2, p1);
var v1 = this.m_vertex1;
var v2 = this.m_vertex2;
var e = Vec2.sub(v2, v1);
var normal = Vec2.neo(e.y, -e.x);
normal.normalize();
var numerator = Vec2.dot(normal, Vec2.sub(v1, p1));
var denominator = Vec2.dot(normal, d);
if (denominator == 0) {
return false;
}
var t = numerator / denominator;
if (t < 0 || input.maxFraction < t) {
return false;
}
var q = Vec2.add(p1, Vec2.mul(t, d));
var r = Vec2.sub(v2, v1);
var rr = Vec2.dot(r, r);
if (rr == 0) {
return false;
}
var s = Vec2.dot(Vec2.sub(q, v1), r) / rr;
if (s < 0 || 1 < s) {
return false;
}
output.fraction = t;
if (numerator > 0) {
output.normal = Rot.mul(xf.q, normal).neg();
} else {
output.normal = Rot.mul(xf.q, normal);
}
return true;
};
EdgeShape.prototype.computeAABB = function(aabb, xf, childIndex) {
var v1 = Transform.mul(xf, this.m_vertex1);
var v2 = Transform.mul(xf, this.m_vertex2);
aabb.combinePoints(v1, v2);
aabb.extend(this.m_radius);
};
EdgeShape.prototype.computeMass = function(massData, density) {
massData.mass = 0;
massData.center.wSet(.5, this.m_vertex1, .5, this.m_vertex2);
massData.I = 0;
};
EdgeShape.prototype.computeDistanceProxy = function(proxy) {
proxy.m_vertices.push(this.m_vertex1);
proxy.m_vertices.push(this.m_vertex2);
proxy.m_count = 2;
proxy.m_radius = this.m_radius;
};
},{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/create":52,"../util/options":53}],48:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = PolygonShape;
var common = require("../util/common");
var create = require("../util/create");
var options = require("../util/options");
var Math = require("../common/Math");
var Transform = require("../common/Transform");
var Rot = require("../common/Rot");
var Vec2 = require("../common/Vec2");
var AABB = require("../collision/AABB");
var Settings = require("../Settings");
var Shape = require("../Shape");
PolygonShape._super = Shape;
PolygonShape.prototype = create(PolygonShape._super.prototype);
PolygonShape.TYPE = "polygon";
function PolygonShape(vertices) {
if (!(this instanceof PolygonShape)) {
return new PolygonShape(vertices);
}
PolygonShape._super.call(this);
this.m_type = PolygonShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_centroid = Vec2.zero();
this.m_vertices = [];
this.m_normals = [];
this.m_count = 0;
if (vertices && vertices.length) {
this._set(vertices);
}
}
PolygonShape.prototype.getVertex = function(index) {
ASSERT && common.assert(0 <= index && index < this.m_count);
return this.m_vertices[index];
};
PolygonShape.prototype._clone = function() {
var clone = new PolygonShape();
clone.m_type = this.m_type;
clone.m_radius = this.m_radius;
clone.m_count = this.m_count;
clone.m_centroid.set(this.m_centroid);
for (var i = 0; i < this.m_count; i++) {
clone.m_vertices.push(this.m_vertices[i].clone());
}
for (var i = 0; i < this.m_normals.length; i++) {
clone.m_normals.push(this.m_normals[i].clone());
}
return clone;
};
PolygonShape.prototype.getChildCount = function() {
return 1;
};
function ComputeCentroid(vs, count) {
ASSERT && common.assert(count >= 3);
var c = Vec2.zero();
var area = 0;
var pRef = Vec2.zero();
if (false) {
for (var i = 0; i < count; ++i) {
pRef.add(vs[i]);
}
pRef.mul(1 / count);
}
var inv3 = 1 / 3;
for (var i = 0; i < count; ++i) {
var p1 = pRef;
var p2 = vs[i];
var p3 = i + 1 < count ? vs[i + 1] : vs[0];
var e1 = Vec2.sub(p2, p1);
var e2 = Vec2.sub(p3, p1);
var D = Vec2.cross(e1, e2);
var triangleArea = .5 * D;
area += triangleArea;
c.wAdd(triangleArea * inv3, p1);
c.wAdd(triangleArea * inv3, p2);
c.wAdd(triangleArea * inv3, p3);
}
ASSERT && common.assert(area > Math.EPSILON);
c.mul(1 / area);
return c;
}
PolygonShape.prototype._set = function(vertices) {
ASSERT && common.assert(3 <= vertices.length && vertices.length <= Settings.maxPolygonVertices);
if (vertices.length < 3) {
SetAsBox(1, 1);
return;
}
var n = Math.min(vertices.length, Settings.maxPolygonVertices);
var ps = [];
var tempCount = 0;
for (var i = 0; i < n; ++i) {
var v = vertices[i];
var unique = true;
for (var j = 0; j < tempCount; ++j) {
if (Vec2.distanceSquared(v, ps[j]) < .25 * Settings.linearSlopSquared) {
unique = false;
break;
}
}
if (unique) {
ps[tempCount++] = v;
}
}
n = tempCount;
if (n < 3) {
ASSERT && common.assert(false);
SetAsBox(1, 1);
return;
}
var i0 = 0;
var x0 = ps[0].x;
for (var i = 1; i < n; ++i) {
var x = ps[i].x;
if (x > x0 || x == x0 && ps[i].y < ps[i0].y) {
i0 = i;
x0 = x;
}
}
var hull = [];
var m = 0;
var ih = i0;
for (;;) {
hull[m] = ih;
var ie = 0;
for (var j = 1; j < n; ++j) {
if (ie == ih) {
ie = j;
continue;
}
var r = Vec2.sub(ps[ie], ps[hull[m]]);
var v = Vec2.sub(ps[j], ps[hull[m]]);
var c = Vec2.cross(r, v);
if (c < 0) {
ie = j;
}
if (c == 0 && v.lengthSquared() > r.lengthSquared()) {
ie = j;
}
}
++m;
ih = ie;
if (ie == i0) {
break;
}
}
if (m < 3) {
ASSERT && common.assert(false);
SetAsBox(1, 1);
return;
}
this.m_count = m;
for (var i = 0; i < m; ++i) {
this.m_vertices[i] = ps[hull[i]];
}
for (var i = 0; i < m; ++i) {
var i1 = i;
var i2 = i + 1 < m ? i + 1 : 0;
var edge = Vec2.sub(this.m_vertices[i2], this.m_vertices[i1]);
ASSERT && common.assert(edge.lengthSquared() > Math.EPSILON * Math.EPSILON);
this.m_normals[i] = Vec2.cross(edge, 1);
this.m_normals[i].normalize();
}
this.m_centroid = ComputeCentroid(this.m_vertices, m);
};
PolygonShape.prototype.testPoint = function(xf, p) {
var pLocal = Rot.mulT(xf.q, Vec2.sub(p, xf.p));
for (var i = 0; i < this.m_count; ++i) {
var dot = Vec2.dot(this.m_normals[i], Vec2.sub(pLocal, this.m_vertices[i]));
if (dot > 0) {
return false;
}
}
return true;
};
PolygonShape.prototype.rayCast = function(output, input, xf, childIndex) {
var p1 = Rot.mulT(xf.q, Vec2.sub(input.p1, xf.p));
var p2 = Rot.mulT(xf.q, Vec2.sub(input.p2, xf.p));
var d = Vec2.sub(p2, p1);
var lower = 0;
var upper = input.maxFraction;
var index = -1;
for (var i = 0; i < this.m_count; ++i) {
var numerator = Vec2.dot(this.m_normals[i], Vec2.sub(this.m_vertices[i], p1));
var denominator = Vec2.dot(this.m_normals[i], d);
if (denominator == 0) {
if (numerator < 0) {
return false;
}
} else {
if (denominator < 0 && numerator < lower * denominator) {
lower = numerator / denominator;
index = i;
} else if (denominator > 0 && numerator < upper * denominator) {
upper = numerator / denominator;
}
}
if (upper < lower) {
return false;
}
}
ASSERT && common.assert(0 <= lower && lower <= input.maxFraction);
if (index >= 0) {
output.fraction = lower;
output.normal = Rot.mul(xf.q, this.m_normals[index]);
return true;
}
return false;
};
PolygonShape.prototype.computeAABB = function(aabb, xf, childIndex) {
var minX = Infinity, minY = Infinity;
var maxX = -Infinity, maxY = -Infinity;
for (var i = 0; i < this.m_count; ++i) {
var v = Transform.mul(xf, this.m_vertices[i]);
minX = Math.min(minX, v.x);
maxX = Math.max(maxX, v.x);
minY = Math.min(minY, v.y);
maxY = Math.max(maxY, v.y);
}
aabb.lowerBound.set(minX, minY);
aabb.upperBound.set(maxX, maxY);
aabb.extend(this.m_radius);
};
PolygonShape.prototype.computeMass = function(massData, density) {
ASSERT && common.assert(this.m_count >= 3);
var center = Vec2.zero();
var area = 0;
var I = 0;
var s = Vec2.zero();
for (var i = 0; i < this.m_count; ++i) {
s.add(this.m_vertices[i]);
}
s.mul(1 / this.m_count);
var k_inv3 = 1 / 3;
for (var i = 0; i < this.m_count; ++i) {
var e1 = Vec2.sub(this.m_vertices[i], s);
var e2 = i + 1 < this.m_count ? Vec2.sub(this.m_vertices[i + 1], s) : Vec2.sub(this.m_vertices[0], s);
var D = Vec2.cross(e1, e2);
var triangleArea = .5 * D;
area += triangleArea;
center.wAdd(triangleArea * k_inv3, e1, triangleArea * k_inv3, e2);
var ex1 = e1.x;
var ey1 = e1.y;
var ex2 = e2.x;
var ey2 = e2.y;
var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
I += .25 * k_inv3 * D * (intx2 + inty2);
}
massData.mass = density * area;
ASSERT && common.assert(area > Math.EPSILON);
center.mul(1 / area);
massData.center.wSet(1, center, 1, s);
massData.I = density * I;
massData.I += massData.mass * (Vec2.dot(massData.center, massData.center) - Vec2.dot(center, center));
};
PolygonShape.prototype.validate = function() {
for (var i = 0; i < this.m_count; ++i) {
var i1 = i;
var i2 = i < this.m_count - 1 ? i1 + 1 : 0;
var p = this.m_vertices[i1];
var e = Vec2.sub(this.m_vertices[i2], p);
for (var j = 0; j < this.m_count; ++j) {
if (j == i1 || j == i2) {
continue;
}
var v = Vec2.sub(this.m_vertices[j], p);
var c = Vec2.cross(e, v);
if (c < 0) {
return false;
}
}
}
return true;
};
PolygonShape.prototype.computeDistanceProxy = function(proxy) {
proxy.m_vertices = this.m_vertices;
proxy.m_count = this.m_count;
proxy.m_radius = this.m_radius;
};
},{"../Settings":7,"../Shape":8,"../collision/AABB":11,"../common/Math":18,"../common/Rot":20,"../common/Transform":22,"../common/Vec2":23,"../util/common":51,"../util/create":52,"../util/options":53}],49:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports = Pool;
function Pool(opts) {
var _list = [];
var _max = opts.max || Infinity;
var _createFn = opts.create;
var _outFn = opts.allocate;
var _inFn = opts.release;
var _discardFn = opts.discard;
var _createCount = 0;
var _outCount = 0;
var _inCount = 0;
var _discardCount = 0;
this.max = function(n) {
if (typeof n === "number") {
_max = n;
return this;
}
return _max;
};
this.size = function() {
return _list.length;
};
this.allocate = function() {
var item;
if (_list.length > 0) {
item = _list.shift();
} else {
_createCount++;
if (typeof _createFn === "function") {
item = _createFn();
} else {
item = {};
}
}
_outCount++;
if (typeof _outFn === "function") {
_outFn(item);
}
return item;
};
this.release = function(item) {
if (_list.length < _max) {
_inCount++;
if (typeof _inFn === "function") {
_inFn(item);
}
_list.push(item);
} else {
_discardCount++;
if (typeof _discardFn === "function") {
item = _discardFn(item);
}
}
};
this.toString = function() {
return " +" + _createCount + " >" + _outCount + " <" + _inCount + " -" + _discardCount + " =" + _list.length + "/" + _max;
};
}
},{}],50:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
module.exports.now = function() {
return Date.now();
};
module.exports.diff = function(time) {
return Date.now() - time;
};
},{}],51:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
exports.debug = function() {
if (!DEBUG) return;
console.log.apply(console, arguments);
};
exports.assert = function(statement, err, log) {
if (!ASSERT) return;
if (statement) return;
log && console.log(log);
throw new Error(err);
};
},{}],52:[function(require,module,exports){
if (typeof Object.create == "function") {
module.exports = function(proto, props) {
return Object.create.call(Object, proto, props);
};
} else {
module.exports = function(proto, props) {
if (props) throw Error("Second argument is not supported!");
if (typeof proto !== "object" || proto === null) throw Error("Invalid prototype!");
noop.prototype = proto;
return new noop();
};
function noop() {}
}
},{}],53:[function(require,module,exports){
DEBUG = typeof DEBUG === "undefined" ? false : DEBUG;
ASSERT = typeof ASSERT === "undefined" ? false : ASSERT;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
module.exports = function(to, from) {
if (to === null || typeof to === "undefined") {
to = {};
}
for (var key in from) {
if (from.hasOwnProperty(key) && typeof to[key] === "undefined") {
to[key] = from[key];
}
}
if (typeof Object.getOwnPropertySymbols === "function") {
var symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
var symbol = symbols[i];
if (from.propertyIsEnumerable(symbol) && typeof to[key] === "undefined") {
to[symbol] = from[symbol];
}
}
}
return to;
};
},{}],54:[function(require,module,exports){
function _identity(x) {
return x;
};
var _cache = {};
var _modes = {};
var _easings = {};
function Easing(token) {
if (typeof token === 'function') {
return token;
}
if (typeof token !== 'string') {
return _identity;
}
var fn = _cache[token];
if (fn) {
return fn;
}
var match = /^(\w+)(-(in|out|in-out|out-in))?(\((.*)\))?$/i.exec(token);
if (!match || !match.length) {
return _identity;
}
var easing = _easings[match[1]];
var mode = _modes[match[3]];
var params = match[5];
if (easing && easing.fn) {
fn = easing.fn;
} else if (easing && easing.fc) {
fn = easing.fc.apply(easing.fc, params
&& params.replace(/\s+/, '').split(','));
} else {
fn = _identity;
}
if (mode) {
fn = mode.fn(fn);
}
// TODO: It can be a memory leak with different `params`.
_cache[token] = fn;
return fn;
};
Easing.add = function(data) {
// TODO: create a map of all { name-mode : data }
var names = (data.name || data.mode).split(/\s+/);
for (var i = 0; i < names.length; i++) {
var name = names[i];
if (name) {
(data.name ? _easings : _modes)[name] = data;
}
}
};
Easing.add({
mode : 'in',
fn : function(f) {
return f;
}
});
Easing.add({
mode : 'out',
fn : function(f) {
return function(t) {
return 1 - f(1 - t);
};
}
});
Easing.add({
mode : 'in-out',
fn : function(f) {
return function(t) {
return (t < 0.5) ? (f(2 * t) / 2) : (1 - f(2 * (1 - t)) / 2);
};
}
});
Easing.add({
mode : 'out-in',
fn : function(f) {
return function(t) {
return (t < 0.5) ? (1 - f(2 * (1 - t)) / 2) : (f(2 * t) / 2);
};
}
});
Easing.add({
name : 'linear',
fn : function(t) {
return t;
}
});
Easing.add({
name : 'quad',
fn : function(t) {
return t * t;
}
});
Easing.add({
name : 'cubic',
fn : function(t) {
return t * t * t;
}
});
Easing.add({
name : 'quart',
fn : function(t) {
return t * t * t * t;
}
});
Easing.add({
name : 'quint',
fn : function(t) {
return t * t * t * t * t;
}
});
Easing.add({
name : 'sin sine',
fn : function(t) {
return 1 - Math.cos(t * Math.PI / 2);
}
});
Easing.add({
name : 'exp expo',
fn : function(t) {
return t == 0 ? 0 : Math.pow(2, 10 * (t - 1));
}
});
Easing.add({
name : 'circle circ',
fn : function(t) {
return 1 - Math.sqrt(1 - t * t);
}
});
Easing.add({
name : 'bounce',
fn : function(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625
* (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625
* (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t
+ .984375;
}
});
Easing.add({
name : 'poly',
fc : function(e) {
return function(t) {
return Math.pow(t, e);
};
}
});
Easing.add({
name : 'elastic',
fc : function(a, p) {
p = p || 0.45;
a = a || 1;
var s = p / (2 * Math.PI) * Math.asin(1 / a);
return function(t) {
return 1 + a * Math.pow(2, -10 * t)
* Math.sin((t - s) * (2 * Math.PI) / p);
};
}
});
Easing.add({
name : 'back',
fc : function(s) {
s = typeof s !== 'undefined' ? s : 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
});
module.exports = Easing;
},{}],55:[function(require,module,exports){
if (typeof DEBUG === 'undefined')
DEBUG = true;
require('../core')._load(function(stage, elem) {
Mouse.subscribe(stage, elem);
});
// TODO: capture mouse
Mouse.CLICK = 'click';
Mouse.START = 'touchstart mousedown';
Mouse.MOVE = 'touchmove mousemove';
Mouse.END = 'touchend mouseup';
Mouse.CANCEL = 'touchcancel mousecancel';
Mouse.subscribe = function(stage, elem) {
if (stage.mouse) {
return;
}
stage.mouse = new Mouse(stage, elem);
// `click` events are synthesized from start/end events on same nodes
// `mousecancel` events are synthesized on blur or mouseup outside element
elem.addEventListener('touchstart', handleStart);
elem.addEventListener('touchend', handleEnd);
elem.addEventListener('touchmove', handleMove);
elem.addEventListener('touchcancel', handleCancel);
elem.addEventListener('mousedown', handleStart);
elem.addEventListener('mouseup', handleEnd);
elem.addEventListener('mousemove', handleMove);
document.addEventListener('mouseup', handleCancel);
window.addEventListener("blur", handleCancel);
var clicklist = [], cancellist = [];
function handleStart(event) {
event.preventDefault();
stage.mouse.locate(event);
// DEBUG && console.log('Mouse Start: ' + event.type + ' ' + mouse);
stage.mouse.publish(event.type, event);
stage.mouse.lookup('click', clicklist);
stage.mouse.lookup('mousecancel', cancellist);
}
function handleMove(event) {
event.preventDefault();
stage.mouse.locate(event);
stage.mouse.publish(event.type, event);
}
function handleEnd(event) {
event.preventDefault();
// up/end location is not available, last one is used instead
// DEBUG && console.log('Mouse End: ' + event.type + ' ' + mouse);
stage.mouse.publish(event.type, event);
if (clicklist.length) {
// DEBUG && console.log('Mouse Click: ' + clicklist.length);
stage.mouse.publish('click', event, clicklist);
}
cancellist.length = 0;
}
function handleCancel(event) {
if (cancellist.length) {
// DEBUG && console.log('Mouse Cancel: ' + event.type);
stage.mouse.publish('mousecancel', event, cancellist);
}
clicklist.length = 0;
}
};
function Mouse(stage, elem) {
if (!(this instanceof Mouse)) {
// old-style mouse subscription
return;
}
var ratio = stage.viewport().ratio || 1;
stage.on('viewport', function(size) {
ratio = size.ratio || ratio;
});
this.x = 0;
this.y = 0;
this.toString = function() {
return (this.x | 0) + 'x' + (this.y | 0);
};
this.locate = function(event) {
locateElevent(elem, event, this);
this.x *= ratio;
this.y *= ratio;
};
this.lookup = function(type, collect) {
this.type = type;
this.root = stage;
this.event = null;
collect.length = 0;
this.collect = collect;
this.root.visit(this.visitor, this);
};
this.publish = function(type, event, targets) {
this.type = type;
this.root = stage;
this.event = event;
this.collect = false;
this.timeStamp = Date.now();
if (type !== 'mousemove' && type !== 'touchmove') {
DEBUG && console.log(this.type + ' ' + this);
}
if (targets) {
while (targets.length)
if (this.visitor.end(targets.shift(), this))
break;
targets.length = 0;
} else {
this.root.visit(this.visitor, this);
}
};
this.visitor = {
reverse : true,
visible : true,
start : function(node, mouse) {
return !node._flag(mouse.type);
},
end : function(node, mouse) {
// mouse: event/collect, type, root
rel.raw = mouse.event;
rel.type = mouse.type;
rel.timeStamp = mouse.timeStamp;
rel.abs.x = mouse.x;
rel.abs.y = mouse.y;
var listeners = node.listeners(mouse.type);
if (!listeners) {
return;
}
node.matrix().inverse().map(mouse, rel);
if (!(node === mouse.root || node.hitTest(rel))) {
return;
}
if (mouse.collect) {
mouse.collect.push(node);
}
if (mouse.event) {
var cancel = false;
for (var l = 0; l < listeners.length; l++) {
cancel = listeners[l].call(node, rel) ? true : cancel;
}
return cancel;
}
}
};
};
// TODO: define per mouse object with get-only x and y
var rel = {}, abs = {};
defineValue(rel, 'clone', function(obj) {
obj = obj || {}, obj.x = this.x, obj.y = this.y;
return obj;
});
defineValue(rel, 'toString', function() {
return (this.x | 0) + 'x' + (this.y | 0) + ' (' + this.abs + ')';
});
defineValue(rel, 'abs', abs);
defineValue(abs, 'clone', function(obj) {
obj = obj || {}, obj.x = this.x, obj.y = this.y;
return obj;
});
defineValue(abs, 'toString', function() {
return (this.x | 0) + 'x' + (this.y | 0);
});
function defineValue(obj, name, value) {
Object.defineProperty(obj, name, {
value : value
});
}
function locateElevent(el, ev, loc) {
// pageX/Y if available?
if (ev.touches && ev.touches.length) {
loc.x = ev.touches[0].clientX;
loc.y = ev.touches[0].clientY;
} else {
loc.x = ev.clientX;
loc.y = ev.clientY;
}
var rect = el.getBoundingClientRect();
loc.x -= rect.left;
loc.y -= rect.top;
loc.x -= el.clientLeft | 0;
loc.y -= el.clientTop | 0;
return loc;
};
module.exports = Mouse;
},{"../core":60}],56:[function(require,module,exports){
var Easing = require('./easing');
var Class = require('../core');
var Pin = require('../pin');
Class.prototype.tween = function(duration, delay, append) {
if (typeof duration !== 'number') {
append = duration, delay = 0, duration = 0;
} else if (typeof delay !== 'number') {
append = delay, delay = 0;
}
if (!this._tweens) {
this._tweens = [];
var ticktime = 0;
this.tick(function(elapsed, now, last) {
if (!this._tweens.length) {
return;
}
// ignore old elapsed
var ignore = ticktime != last;
ticktime = now;
if (ignore) {
return true;
}
var next = this._tweens[0].tick(this, elapsed, now, last);
if (next) {
this._tweens.shift();
}
if (typeof next === 'object') {
this._tweens.unshift(next);
}
return true;
}, true);
}
this.touch();
if (!append) {
this._tweens.length = 0;
}
var tween = new Tween(this, duration, delay);
this._tweens.push(tween);
return tween;
};
function Tween(owner, duration, delay) {
this._end = {};
this._duration = duration || 400;
this._delay = delay || 0;
this._owner = owner;
this._time = 0;
};
Tween.prototype.tick = function(node, elapsed, now, last) {
this._time += elapsed;
if (this._time < this._delay) {
return;
}
var time = this._time - this._delay;
if (!this._start) {
this._start = {};
for ( var key in this._end) {
this._start[key] = this._owner.pin(key);
}
}
var p, over;
if (time < this._duration) {
p = time / this._duration, over = false;
} else {
p = 1, over = true;
}
p = typeof this._easing == 'function' ? this._easing(p) : p;
var q = 1 - p;
for ( var key in this._end) {
this._owner.pin(key, this._start[key] * q + this._end[key] * p);
}
if (over) {
try {
this._done && this._done.call(this._owner);
} catch (e) {
console.log(e);
}
return this._next || true;
}
};
Tween.prototype.tween = function(duration, delay) {
return this._next = new Tween(this._owner, duration, delay);
};
Tween.prototype.duration = function(duration) {
this._duration = duration;
return this;
};
Tween.prototype.delay = function(delay) {
this._delay = delay;
return this;
};
Tween.prototype.ease = function(easing) {
this._easing = Easing(easing);
return this;
};
Tween.prototype.done = function(fn) {
this._done = fn;
return this;
};
Tween.prototype.hide = function() {
this.done(function() {
this.hide();
});
return this;
};
Tween.prototype.remove = function() {
this.done(function() {
this.remove();
});
return this;
};
Tween.prototype.pin = function(a, b) {
if (typeof a === 'object') {
for ( var attr in a) {
pinning(this._owner, this._end, attr, a[attr]);
}
} else if (typeof b !== 'undefined') {
pinning(this._owner, this._end, a, b);
}
return this;
};
function pinning(node, map, key, value) {
if (typeof node.pin(key) === 'number') {
map[key] = value;
} else if (typeof node.pin(key + 'X') === 'number'
&& typeof node.pin(key + 'Y') === 'number') {
map[key + 'X'] = value;
map[key + 'Y'] = value;
}
}
Pin._add_shortcuts(Tween);
/**
* @deprecated Use .done(fn) instead.
*/
Tween.prototype.then = function(fn) {
this.done(fn);
return this;
};
/**
* @deprecated Use .done(fn) instead.
*/
Tween.prototype.then = function(fn) {
this.done(fn);
return this;
};
/**
* @deprecated NOOP
*/
Tween.prototype.clear = function(forward) {
return this;
};
module.exports = Tween;
},{"../core":60,"../pin":68,"./easing":54}],57:[function(require,module,exports){
var Class = require('./core');
require('./pin');
require('./loop');
var create = require('./util/create');
var math = require('./util/math');
Class.anim = function(frames, fps) {
var anim = new Anim();
anim.frames(frames).gotoFrame(0);
fps && anim.fps(fps);
return anim;
};
Anim._super = Class;
Anim.prototype = create(Anim._super.prototype);
// TODO: replace with atlas fps or texture time
Class.Anim = {
FPS : 15
};
function Anim() {
Anim._super.call(this);
this.label('Anim');
this._textures = [];
this._fps = Class.Anim.FPS;
this._ft = 1000 / this._fps;
this._time = -1;
this._repeat = 0;
this._index = 0;
this._frames = [];
var lastTime = 0;
this.tick(function(t, now, last) {
if (this._time < 0 || this._frames.length <= 1) {
return;
}
// ignore old elapsed
var ignore = lastTime != last;
lastTime = now;
if (ignore) {
return true;
}
this._time += t;
if (this._time < this._ft) {
return true;
}
var n = this._time / this._ft | 0;
this._time -= n * this._ft;
this.moveFrame(n);
if (this._repeat > 0 && (this._repeat -= n) <= 0) {
this.stop();
this._callback && this._callback();
return false;
}
return true;
}, false);
};
Anim.prototype.fps = function(fps) {
if (typeof fps === 'undefined') {
return this._fps;
}
this._fps = fps > 0 ? fps : Class.Anim.FPS;
this._ft = 1000 / this._fps;
return this;
};
/**
* @deprecated Use frames
*/
Anim.prototype.setFrames = function(a, b, c) {
return this.frames(a, b, c);
};
Anim.prototype.frames = function(frames) {
this._index = 0;
this._frames = Class.texture(frames).array();
this.touch();
return this;
};
Anim.prototype.length = function() {
return this._frames ? this._frames.length : 0;
};
Anim.prototype.gotoFrame = function(frame, resize) {
this._index = math.rotate(frame, this._frames.length) | 0;
resize = resize || !this._textures[0];
this._textures[0] = this._frames[this._index];
if (resize) {
this.pin('width', this._textures[0].width);
this.pin('height', this._textures[0].height);
}
this.touch();
return this;
};
Anim.prototype.moveFrame = function(move) {
return this.gotoFrame(this._index + move);
};
Anim.prototype.repeat = function(repeat, callback) {
this._repeat = repeat * this._frames.length - 1;
this._callback = callback;
this.play();
return this;
};
Anim.prototype.play = function(frame) {
if (typeof frame !== 'undefined') {
this.gotoFrame(frame);
this._time = 0;
} else if (this._time < 0) {
this._time = 0;
}
this.touch();
return this;
};
Anim.prototype.stop = function(frame) {
this._time = -1;
if (typeof frame !== 'undefined') {
this.gotoFrame(frame);
}
return this;
};
},{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/math":78}],58:[function(require,module,exports){
if (typeof DEBUG === 'undefined')
DEBUG = true;
var Class = require('./core');
var Texture = require('./texture');
var extend = require('./util/extend');
var create = require('./util/create');
var is = require('./util/is');
var string = require('./util/string');
// name : atlas
var _atlases_map = {};
// [atlas]
var _atlases_arr = [];
// TODO: print subquery not found error
// TODO: index textures
Class.atlas = function(def) {
var atlas = is.fn(def.draw) ? def : new Atlas(def);
if (def.name) {
_atlases_map[def.name] = atlas;
}
_atlases_arr.push(atlas);
deprecated(def, 'imagePath');
deprecated(def, 'imageRatio');
var url = def.imagePath;
var ratio = def.imageRatio || 1;
if (is.string(def.image)) {
url = def.image;
} else if (is.hash(def.image)) {
url = def.image.src || def.image.url;
ratio = def.image.ratio || ratio;
}
url && Class.preload(function(done) {
url = Class.resolve(url);
DEBUG && console.log('Loading atlas: ' + url);
var imageloader = Class.config('image-loader');
imageloader(url, function(image) {
DEBUG && console.log('Image loaded: ' + url);
atlas.src(image, ratio);
done();
}, function(err) {
DEBUG && console.log('Error loading atlas: ' + url, err);
done();
});
});
return atlas;
};
Atlas._super = Texture;
Atlas.prototype = create(Atlas._super.prototype);
function Atlas(def) {
Atlas._super.call(this);
var atlas = this;
deprecated(def, 'filter');
deprecated(def, 'cutouts');
deprecated(def, 'sprites');
deprecated(def, 'factory');
var map = def.map || def.filter;
var ppu = def.ppu || def.ratio || 1;
var trim = def.trim || 0;
var textures = def.textures;
var factory = def.factory;
var cutouts = def.cutouts || def.sprites;
function make(def) {
if (!def || is.fn(def.draw)) {
return def;
}
def = extend({}, def);
if (is.fn(map)) {
def = map(def);
}
if (ppu != 1) {
def.x *= ppu, def.y *= ppu;
def.width *= ppu, def.height *= ppu;
def.top *= ppu, def.bottom *= ppu;
def.left *= ppu, def.right *= ppu;
}
if (trim != 0) {
def.x += trim, def.y += trim;
def.width -= 2 * trim, def.height -= 2 * trim;
def.top -= trim, def.bottom -= trim;
def.left -= trim, def.right -= trim;
}
var texture = atlas.pipe();
texture.top = def.top, texture.bottom = def.bottom;
texture.left = def.left, texture.right = def.right;
texture.src(def.x, def.y, def.width, def.height);
return texture;
}
function find(query) {
if (textures) {
if (is.fn(textures)) {
return textures(query);
} else if (is.hash(textures)) {
return textures[query];
}
}
if (cutouts) { // deprecated
var result = null, n = 0;
for (var i = 0; i < cutouts.length; i++) {
if (string.startsWith(cutouts[i].name, query)) {
if (n === 0) {
result = cutouts[i];
} else if (n === 1) {
result = [ result, cutouts[i] ];
} else {
result.push(cutouts[i]);
}
n++;
}
}
if (n === 0 && is.fn(factory)) {
result = function(subquery) {
return factory(query + (subquery ? subquery : ''));
};
}
return result;
}
}
this.select = function(query) {
if (!query) {
// TODO: if `textures` is texture def, map or fn?
return new Selection(this.pipe());
}
var found = find(query);
if (found) {
return new Selection(found, find, make);
}
};
};
var nfTexture = new Texture();
nfTexture.x = nfTexture.y = nfTexture.width = nfTexture.height = 0;
nfTexture.pipe = nfTexture.src = nfTexture.dest = function() {
return this;
};
nfTexture.draw = function() {
};
var nfSelection = new Selection(nfTexture);
function Selection(result, find, make) {
function link(result, subquery) {
if (!result) {
return nfTexture;
} else if (is.fn(result.draw)) {
return result;
} else if (is.hash(result) && is.number(result.width)
&& is.number(result.height) && is.fn(make)) {
return make(result);
} else if (is.hash(result) && is.defined(subquery)) {
return link(result[subquery]);
} else if (is.fn(result)) {
return link(result(subquery));
} else if (is.array(result)) {
return link(result[0]);
} else if (is.string(result) && is.fn(find)) {
return link(find(result));
}
}
this.one = function(subquery) {
return link(result, subquery);
};
this.array = function(arr) {
var array = is.array(arr) ? arr : [];
if (is.array(result)) {
for (var i = 0; i < result.length; i++) {
array[i] = link(result[i]);
}
} else {
array[0] = link(result);
}
return array;
};
}
Class.texture = function(query) {
if (!is.string(query)) {
return new Selection(query);
}
var result = null, atlas, i;
if ((i = query.indexOf(':')) > 0 && query.length > i + 1) {
atlas = _atlases_map[query.slice(0, i)];
result = atlas && atlas.select(query.slice(i + 1));
}
if (!result && (atlas = _atlases_map[query])) {
result = atlas.select();
}
for (i = 0; !result && i < _atlases_arr.length; i++) {
result = _atlases_arr[i].select(query);
}
if (!result) {
console.error('Texture not found: ' + query);
result = nfSelection;
}
return result;
};
function deprecated(hash, name, msg) {
if (name in hash)
console.log(msg ? msg.replace('%name', name) : '\'' + name
+ '\' field of texture atlas is deprecated.');
};
module.exports = Atlas;
},{"./core":60,"./texture":71,"./util/create":74,"./util/extend":76,"./util/is":77,"./util/string":81}],59:[function(require,module,exports){
var Class = require('./core');
var Texture = require('./texture');
Class.canvas = function(type, attributes, callback) {
if (typeof type === 'string') {
if (typeof attributes === 'object') {
} else {
if (typeof attributes === 'function') {
callback = attributes;
}
attributes = {};
}
} else {
if (typeof type === 'function') {
callback = type;
}
attributes = {};
type = '2d';
}
var canvas = document.createElement('canvas');
var context = canvas.getContext(type, attributes);
var texture = new Texture(canvas);
texture.context = function() {
return context;
};
texture.size = function(width, height, ratio) {
ratio = ratio || 1;
canvas.width = width * ratio;
canvas.height = height * ratio;
this.src(canvas, ratio);
return this;
};
texture.canvas = function(fn) {
if (typeof fn === 'function') {
fn.call(this, context);
} else if (typeof fn === 'undefined' && typeof callback === 'function') {
callback.call(this, context);
}
return this;
};
if (typeof callback === 'function') {
callback.call(texture, context);
}
return texture;
};
},{"./core":60,"./texture":71}],60:[function(require,module,exports){
if (typeof DEBUG === 'undefined')
DEBUG = true;
var stats = require('./util/stats');
var extend = require('./util/extend');
var is = require('./util/is');
var _await = require('./util/await');
stats.create = 0;
function Class(arg) {
if (!(this instanceof Class)) {
if (is.fn(arg)) {
return Class.app.apply(Class, arguments);
} else if (is.object(arg)) {
return Class.atlas.apply(Class, arguments);
} else {
return arg;
}
}
stats.create++;
for (var i = 0; i < _init.length; i++) {
_init[i].call(this);
}
}
var _init = [];
Class._init = function(fn) {
_init.push(fn);
};
var _load = [];
Class._load = function(fn) {
_load.push(fn);
};
var _config = {};
Class.config = function() {
if (arguments.length === 1 && is.string(arguments[0])) {
return _config[arguments[0]];
}
if (arguments.length === 1 && is.object(arguments[0])) {
extend(_config, arguments[0]);
}
if (arguments.length === 2 && is.string(arguments[0])) {
_config[arguments[0], arguments[1]];
}
};
var _app_queue = [];
var _preload_queue = [];
var _stages = [];
var _loaded = false;
var _paused = false;
Class.app = function(app, opts) {
if (!_loaded) {
_app_queue.push(arguments);
return;
}
DEBUG && console.log('Creating app...');
var loader = Class.config('app-loader');
loader(function(stage, canvas) {
DEBUG && console.log('Initing app...');
for (var i = 0; i < _load.length; i++) {
_load[i].call(this, stage, canvas);
}
app(stage, canvas);
_stages.push(stage);
DEBUG && console.log('Starting app...');
stage.start();
}, opts);
};
var loading = _await();
Class.preload = function(load) {
if (typeof load === 'string') {
var url = Class.resolve(load);
if (/\.js($|\?|\#)/.test(url)) {
DEBUG && console.log('Loading script: ' + url);
load = function(callback) {
loadScript(url, callback);
};
}
}
if (typeof load !== 'function') {
return;
}
// if (!_started) {
// _preload_queue.push(load);
// return;
// }
load(loading());
};
Class.start = function(config) {
DEBUG && console.log('Starting...');
Class.config(config);
// DEBUG && console.log('Preloading...');
// _started = true;
// while (_preload_queue.length) {
// var load = _preload_queue.shift();
// load(loading());
// }
loading.then(function() {
DEBUG && console.log('Loading apps...');
_loaded = true;
while (_app_queue.length) {
var args = _app_queue.shift();
Class.app.apply(Class, args);
}
});
};
Class.pause = function() {
if (!_paused) {
_paused = true;
for (var i = _stages.length - 1; i >= 0; i--) {
_stages[i].pause();
}
}
};
Class.resume = function() {
if (_paused) {
_paused = false;
for (var i = _stages.length - 1; i >= 0; i--) {
_stages[i].resume();
}
}
};
Class.create = function() {
return new Class();
};
Class.resolve = (function() {
if (typeof window === 'undefined' || typeof document === 'undefined') {
return function(url) {
return url;
};
}
var scripts = document.getElementsByTagName('script');
function getScriptSrc() {
// HTML5
if (document.currentScript) {
return document.currentScript.src;
}
// IE>=10
var stack;
try {
var err = new Error();
if (err.stack) {
stack = err.stack;
} else {
throw err;
}
} catch (err) {
stack = err.stack;
}
if (typeof stack === 'string') {
stack = stack.split('\n');
// Uses the last line, where the call started
for (var i = stack.length; i--;) {
var url = stack[i].match(/(\w+\:\/\/[^/]*?\/.+?)(:\d+)(:\d+)?/);
if (url) {
return url[1];
}
}
}
// IE<11
if (scripts.length && 'readyState' in scripts[0]) {
for (var i = scripts.length; i--;) {
if (scripts[i].readyState === 'interactive') {
return scripts[i].src;
}
}
}
return location.href;
}
return function(url) {
if (/^\.\//.test(url)) {
var src = getScriptSrc();
var base = src.substring(0, src.lastIndexOf('/') + 1);
url = base + url.substring(2);
// } else if (/^\.\.\//.test(url)) {
// url = base + url;
}
return url;
};
})();
module.exports = Class;
function loadScript(src, callback) {
var el = document.createElement('script');
el.addEventListener('load', function() {
callback();
});
el.addEventListener('error', function(err) {
callback(err || 'Error loading script: ' + src);
});
el.src = src;
el.id = 'preload-' + Date.now();
document.body.appendChild(el);
};
},{"./util/await":73,"./util/extend":76,"./util/is":77,"./util/stats":80}],61:[function(require,module,exports){
require('./util/event')(require('./core').prototype, function(obj, name, on) {
obj._flag(name, on);
});
},{"./core":60,"./util/event":75}],62:[function(require,module,exports){
var Class = require('./core');
require('./pin');
require('./loop');
var repeat = require('./util/repeat');
var create = require('./util/create');
Class.image = function(image) {
var img = new Image();
image && img.image(image);
return img;
};
Image._super = Class;
Image.prototype = create(Image._super.prototype);
function Image() {
Image._super.call(this);
this.label('Image');
this._textures = [];
this._image = null;
};
/**
* @deprecated Use image
*/
Image.prototype.setImage = function(a, b, c) {
return this.image(a, b, c);
};
Image.prototype.image = function(image) {
this._image = Class.texture(image).one();
this.pin('width', this._image ? this._image.width : 0);
this.pin('height', this._image ? this._image.height : 0);
this._textures[0] = this._image.pipe();
this._textures.length = 1;
return this;
};
Image.prototype.tile = function(inner) {
this._repeat(false, inner);
return this;
};
Image.prototype.stretch = function(inner) {
this._repeat(true, inner);
return this;
};
Image.prototype._repeat = function(stretch, inner) {
var self = this;
this.untick(this._repeatTicker);
this.tick(this._repeatTicker = function() {
if (this._mo_stretch == this._pin._ts_transform) {
return;
}
this._mo_stretch = this._pin._ts_transform;
var width = this.pin('width');
var height = this.pin('height');
this._textures.length = repeat(this._image, width, height, stretch, inner,
insert);
});
function insert(i, sx, sy, sw, sh, dx, dy, dw, dh) {
var repeat = self._textures.length > i ? self._textures[i]
: self._textures[i] = self._image.pipe();
repeat.src(sx, sy, sw, sh);
repeat.dest(dx, dy, dw, dh);
}
};
},{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/repeat":79}],63:[function(require,module,exports){
module.exports = require('./core');
module.exports.Matrix = require('./matrix');
module.exports.Texture = require('./texture');
require('./atlas');
require('./tree');
require('./event');
require('./pin');
require('./loop');
require('./root');
},{"./atlas":58,"./core":60,"./event":61,"./loop":66,"./matrix":67,"./pin":68,"./root":69,"./texture":71,"./tree":72}],64:[function(require,module,exports){
var Class = require('./core');
require('./pin');
require('./loop');
var create = require('./util/create');
Class.row = function(align) {
return Class.create().row(align).label('Row');
};
Class.prototype.row = function(align) {
this.sequence('row', align);
return this;
};
Class.column = function(align) {
return Class.create().column(align).label('Row');
};
Class.prototype.column = function(align) {
this.sequence('column', align);
return this;
};
Class.sequence = function(type, align) {
return Class.create().sequence(type, align).label('Sequence');
};
Class.prototype.sequence = function(type, align) {
this._padding = this._padding || 0;
this._spacing = this._spacing || 0;
this.untick(this._layoutTiker);
this.tick(this._layoutTiker = function() {
if (this._mo_seq == this._ts_touch) {
return;
}
this._mo_seq = this._ts_touch;
var alignChildren = (this._mo_seqAlign != this._ts_children);
this._mo_seqAlign = this._ts_children;
var width = 0, height = 0;
var child, next = this.first(true);
var first = true;
while (child = next) {
next = child.next(true);
child.matrix(true);
var w = child.pin('boxWidth');
var h = child.pin('boxHeight');
if (type == 'column') {
!first && (height += this._spacing);
child.pin('offsetY') != height && child.pin('offsetY', height);
width = Math.max(width, w);
height = height + h;
alignChildren && child.pin('alignX', align);
} else if (type == 'row') {
!first && (width += this._spacing);
child.pin('offsetX') != width && child.pin('offsetX', width);
width = width + w;
height = Math.max(height, h);
alignChildren && child.pin('alignY', align);
}
first = false;
}
width += 2 * this._padding;
height += 2 * this._padding;
this.pin('width') != width && this.pin('width', width);
this.pin('height') != height && this.pin('height', height);
});
return this;
};
Class.box = function() {
return Class.create().box().label('Box');
};
Class.prototype.box = function() {
this._padding = this._padding || 0;
this.untick(this._layoutTiker);
this.tick(this._layoutTiker = function() {
if (this._mo_box == this._ts_touch) {
return;
}
this._mo_box = this._ts_touch;
var width = 0, height = 0;
var child, next = this.first(true);
while (child = next) {
next = child.next(true);
child.matrix(true);
var w = child.pin('boxWidth');
var h = child.pin('boxHeight');
width = Math.max(width, w);
height = Math.max(height, h);
}
width += 2 * this._padding;
height += 2 * this._padding;
this.pin('width') != width && this.pin('width', width);
this.pin('height') != height && this.pin('height', height);
});
return this;
};
Class.layer = function() {
return Class.create().layer().label('Layer');
};
Class.prototype.layer = function() {
this.untick(this._layoutTiker);
this.tick(this._layoutTiker = function() {
var parent = this.parent();
if (parent) {
var width = parent.pin('width');
if (this.pin('width') != width) {
this.pin('width', width);
}
var height = parent.pin('height');
if (this.pin('height') != height) {
this.pin('height', height);
}
}
}, true);
return this;
};
// TODO: move padding to pin
Class.prototype.padding = function(pad) {
this._padding = pad;
return this;
};
Class.prototype.spacing = function(space) {
this._spacing = space;
return this;
};
},{"./core":60,"./loop":66,"./pin":68,"./util/create":74}],65:[function(require,module,exports){
/**
* Default loader for web.
*/
if (typeof DEBUG === 'undefined')
DEBUG = true;
var Class = require('../core');
Class._supported = (function() {
var elem = document.createElement('canvas');
return (elem.getContext && elem.getContext('2d')) ? true : false;
})();
window.addEventListener('load', function() {
DEBUG && console.log('On load.');
if (Class._supported) {
Class.start();
}
// TODO if not supported
}, false);
Class.config({
'app-loader' : AppLoader,
'image-loader' : ImageLoader
});
function AppLoader(app, configs) {
configs = configs || {};
var canvas = configs.canvas, context = null, full = false;
var width = 0, height = 0, ratio = 1;
if (typeof canvas === 'string') {
canvas = document.getElementById(canvas);
}
if (!canvas) {
canvas = document.getElementById('cutjs')
|| document.getElementById('stage');
}
if (!canvas) {
full = true;
DEBUG && console.log('Creating Canvas...');
canvas = document.createElement('canvas');
canvas.style.position = 'absolute';
canvas.style.top = '0';
canvas.style.left = '0';
var body = document.body;
body.insertBefore(canvas, body.firstChild);
}
context = canvas.getContext('2d');
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = context.webkitBackingStorePixelRatio
|| context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio
|| context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
ratio = devicePixelRatio / backingStoreRatio;
var requestAnimationFrame = window.requestAnimationFrame
|| window.msRequestAnimationFrame || window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame || window.oRequestAnimationFrame
|| function(callback) {
return window.setTimeout(callback, 1000 / 60);
};
DEBUG && console.log('Creating stage...');
var root = Class.root(requestAnimationFrame, render);
function render() {
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, width, height);
root.render(context);
}
root.background = function(color) {
canvas.style.backgroundColor = color;
return this;
};
app(root, canvas);
resize();
window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);
function resize() {
if (full) {
// screen.availWidth/Height?
width = (window.innerWidth > 0 ? window.innerWidth : screen.width);
height = (window.innerHeight > 0 ? window.innerHeight : screen.height);
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
} else {
width = canvas.clientWidth;
height = canvas.clientHeight;
}
width *= ratio;
height *= ratio;
if (canvas.width === width && canvas.height === height) {
return;
}
canvas.width = width;
canvas.height = height;
DEBUG && console.log('Resize: ' + width + ' x ' + height + ' / ' + ratio);
root.viewport(width, height, ratio);
render();
}
}
function ImageLoader(src, success, error) {
DEBUG && console.log('Loading image: ' + src);
var image = new Image();
image.onload = function() {
success(image);
};
image.onerror = error;
image.src = src;
}
},{"../core":60}],66:[function(require,module,exports){
var Class = require('./core');
require('./pin');
var stats = require('./util/stats');
Class.prototype._textures = null;
Class.prototype._alpha = 1;
Class.prototype.render = function(context) {
if (!this._visible) {
return;
}
stats.node++;
var m = this.matrix();
context.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);
// move this elsewhere!
this._alpha = this._pin._alpha * (this._parent ? this._parent._alpha : 1);
var alpha = this._pin._textureAlpha * this._alpha;
if (context.globalAlpha != alpha) {
context.globalAlpha = alpha;
}
if (this._textures !== null) {
for (var i = 0, n = this._textures.length; i < n; i++) {
this._textures[i].draw(context);
}
}
if (context.globalAlpha != this._alpha) {
context.globalAlpha = this._alpha;
}
var child, next = this._first;
while (child = next) {
next = child._next;
child.render(context);
}
};
Class.prototype._tickBefore = null;
Class.prototype._tickAfter = null;
Class.prototype.MAX_ELAPSE = Infinity;
Class.prototype._tick = function(elapsed, now, last) {
if (!this._visible) {
return;
}
if (elapsed > this.MAX_ELAPSE) {
elapsed = this.MAX_ELAPSE;
}
var ticked = false;
if (this._tickBefore !== null) {
for (var i = 0, n = this._tickBefore.length; i < n; i++) {
stats.tick++;
ticked = this._tickBefore[i].call(this, elapsed, now, last) === true
|| ticked;
}
}
var child, next = this._first;
while (child = next) {
next = child._next;
if (child._flag('_tick')) {
ticked = child._tick(elapsed, now, last) === true ? true : ticked;
}
}
if (this._tickAfter !== null) {
for (var i = 0, n = this._tickAfter.length; i < n; i++) {
stats.tick++;
ticked = this._tickAfter[i].call(this, elapsed, now, last) === true
|| ticked;
}
}
return ticked;
};
Class.prototype.tick = function(ticker, before) {
if (typeof ticker !== 'function') {
return;
}
if (before) {
if (this._tickBefore === null) {
this._tickBefore = [];
}
this._tickBefore.push(ticker);
} else {
if (this._tickAfter === null) {
this._tickAfter = [];
}
this._tickAfter.push(ticker);
}
this._flag('_tick', this._tickAfter !== null && this._tickAfter.length > 0
|| this._tickBefore !== null && this._tickBefore.length > 0);
};
Class.prototype.untick = function(ticker) {
if (typeof ticker !== 'function') {
return;
}
var i;
if (this._tickBefore !== null && (i = this._tickBefore.indexOf(ticker)) >= 0) {
this._tickBefore.splice(i, 1);
}
if (this._tickAfter !== null && (i = this._tickAfter.indexOf(ticker)) >= 0) {
this._tickAfter.splice(i, 1);
}
};
Class.prototype.timeout = function(fn, time) {
this.tick(function timer(t) {
if ((time -= t) < 0) {
this.untick(timer);
fn.call(this);
} else {
return true;
}
});
};
},{"./core":60,"./pin":68,"./util/stats":80}],67:[function(require,module,exports){
function Matrix(a, b, c, d, e, f) {
this.reset(a, b, c, d, e, f);
};
Matrix.prototype.toString = function() {
return '[' + this.a + ', ' + this.b + ', ' + this.c + ', ' + this.d + ', '
+ this.e + ', ' + this.f + ']';
};
Matrix.prototype.clone = function() {
return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f);
};
Matrix.prototype.reset = function(a, b, c, d, e, f) {
this._dirty = true;
if (typeof a === 'object') {
this.a = a.a, this.d = a.d;
this.b = a.b, this.c = a.c;
this.e = a.e, this.f = a.f;
} else {
this.a = a || 1, this.d = d || 1;
this.b = b || 0, this.c = c || 0;
this.e = e || 0, this.f = f || 0;
}
return this;
};
Matrix.prototype.identity = function() {
this._dirty = true;
this.a = 1;
this.b = 0;
this.c = 0;
this.d = 1;
this.e = 0;
this.f = 0;
return this;
};
Matrix.prototype.rotate = function(angle) {
if (!angle) {
return this;
}
this._dirty = true;
var u = angle ? Math.cos(angle) : 1;
// android bug may give bad 0 values
var v = angle ? Math.sin(angle) : 0;
var a = u * this.a - v * this.b;
var b = u * this.b + v * this.a;
var c = u * this.c - v * this.d;
var d = u * this.d + v * this.c;
var e = u * this.e - v * this.f;
var f = u * this.f + v * this.e;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
return this;
};
Matrix.prototype.translate = function(x, y) {
if (!x && !y) {
return this;
}
this._dirty = true;
this.e += x;
this.f += y;
return this;
};
Matrix.prototype.scale = function(x, y) {
if (!(x - 1) && !(y - 1)) {
return this;
}
this._dirty = true;
this.a *= x;
this.b *= y;
this.c *= x;
this.d *= y;
this.e *= x;
this.f *= y;
return this;
};
Matrix.prototype.skew = function(x, y) {
if (!x && !y) {
return this;
}
this._dirty = true;
var a = this.a + this.b * x;
var b = this.b + this.a * y;
var c = this.c + this.d * x;
var d = this.d + this.c * y;
var e = this.e + this.f * x;
var f = this.f + this.e * y;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
return this;
};
Matrix.prototype.concat = function(m) {
this._dirty = true;
var n = this;
var a = n.a * m.a + n.b * m.c;
var b = n.b * m.d + n.a * m.b;
var c = n.c * m.a + n.d * m.c;
var d = n.d * m.d + n.c * m.b;
var e = n.e * m.a + m.e + n.f * m.c;
var f = n.f * m.d + m.f + n.e * m.b;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
return this;
};
Matrix.prototype.inverse = Matrix.prototype.reverse = function() {
if (this._dirty) {
this._dirty = false;
this.inversed = this.inversed || new Matrix();
var z = this.a * this.d - this.b * this.c;
this.inversed.a = this.d / z;
this.inversed.b = -this.b / z;
this.inversed.c = -this.c / z;
this.inversed.d = this.a / z;
this.inversed.e = (this.c * this.f - this.e * this.d) / z;
this.inversed.f = (this.e * this.b - this.a * this.f) / z;
}
return this.inversed;
};
Matrix.prototype.map = function(p, q) {
q = q || {};
q.x = this.a * p.x + this.c * p.y + this.e;
q.y = this.b * p.x + this.d * p.y + this.f;
return q;
};
Matrix.prototype.mapX = function(x, y) {
if (typeof x === 'object')
y = x.y, x = x.x;
return this.a * x + this.c * y + this.e;
};
Matrix.prototype.mapY = function(x, y) {
if (typeof x === 'object')
y = x.y, x = x.x;
return this.b * x + this.d * y + this.f;
};
module.exports = Matrix;
},{}],68:[function(require,module,exports){
var Class = require('./core');
var Matrix = require('./matrix');
var iid = 0;
Class._init(function() {
this._pin = new Pin(this);
});
Class.prototype.matrix = function(relative) {
if (relative === true) {
return this._pin.relativeMatrix();
}
return this._pin.absoluteMatrix();
};
Class.prototype.pin = function(a, b) {
if (typeof a === 'object') {
this._pin.set(a);
return this;
} else if (typeof a === 'string') {
if (typeof b === 'undefined') {
return this._pin.get(a);
} else {
this._pin.set(a, b);
return this;
}
} else if (typeof a === 'undefined') {
return this._pin;
}
};
function Pin(owner) {
this._owner = owner;
this._parent = null;
// relative to parent
this._relativeMatrix = new Matrix();
// relative to stage
this._absoluteMatrix = new Matrix();
this.reset();
};
Pin.prototype.reset = function() {
this._textureAlpha = 1;
this._alpha = 1;
this._width = 0;
this._height = 0;
this._scaleX = 1;
this._scaleY = 1;
this._skewX = 0;
this._skewY = 0;
this._rotation = 0;
// scale/skew/rotate center
this._pivoted = false;
this._pivotX = null;
this._pivotY = null;
// self pin point
this._handled = false;
this._handleX = 0;
this._handleY = 0;
// parent pin point
this._aligned = false;
this._alignX = 0;
this._alignY = 0;
// as seen by parent px
this._offsetX = 0;
this._offsetY = 0;
this._boxX = 0;
this._boxY = 0;
this._boxWidth = this._width;
this._boxHeight = this._height;
// TODO: also set for owner
this._ts_translate = ++iid;
this._ts_transform = ++iid;
this._ts_matrix = ++iid;
};
Pin.prototype._update = function() {
this._parent = this._owner._parent && this._owner._parent._pin;
// if handled and transformed then be translated
if (this._handled && this._mo_handle != this._ts_transform) {
this._mo_handle = this._ts_transform;
this._ts_translate = ++iid;
}
if (this._aligned && this._parent
&& this._mo_align != this._parent._ts_transform) {
this._mo_align = this._parent._ts_transform;
this._ts_translate = ++iid;
}
return this;
};
Pin.prototype.toString = function() {
return this._owner + ' (' + (this._parent ? this._parent._owner : null) + ')';
};
// TODO: ts fields require refactoring
Pin.prototype.absoluteMatrix = function() {
this._update();
var ts = Math.max(this._ts_transform, this._ts_translate,
this._parent ? this._parent._ts_matrix : 0);
if (this._mo_abs == ts) {
return this._absoluteMatrix;
}
this._mo_abs = ts;
var abs = this._absoluteMatrix;
abs.reset(this.relativeMatrix());
this._parent && abs.concat(this._parent._absoluteMatrix);
this._ts_matrix = ++iid;
return abs;
};
Pin.prototype.relativeMatrix = function() {
this._update();
var ts = Math.max(this._ts_transform, this._ts_translate,
this._parent ? this._parent._ts_transform : 0);
if (this._mo_rel == ts) {
return this._relativeMatrix;
}
this._mo_rel = ts;
var rel = this._relativeMatrix;
rel.identity();
if (this._pivoted) {
rel.translate(-this._pivotX * this._width, -this._pivotY * this._height);
}
rel.scale(this._scaleX, this._scaleY);
rel.skew(this._skewX, this._skewY);
rel.rotate(this._rotation);
if (this._pivoted) {
rel.translate(this._pivotX * this._width, this._pivotY * this._height);
}
// calculate effective box
if (this._pivoted) {
// origin
this._boxX = 0;
this._boxY = 0;
this._boxWidth = this._width;
this._boxHeight = this._height;
} else {
// aabb
var p, q;
if (rel.a > 0 && rel.c > 0 || rel.a < 0 && rel.c < 0) {
p = 0, q = rel.a * this._width + rel.c * this._height;
} else {
p = rel.a * this._width, q = rel.c * this._height;
}
if (p > q) {
this._boxX = q;
this._boxWidth = p - q;
} else {
this._boxX = p;
this._boxWidth = q - p;
}
if (rel.b > 0 && rel.d > 0 || rel.b < 0 && rel.d < 0) {
p = 0, q = rel.b * this._width + rel.d * this._height;
} else {
p = rel.b * this._width, q = rel.d * this._height;
}
if (p > q) {
this._boxY = q;
this._boxHeight = p - q;
} else {
this._boxY = p;
this._boxHeight = q - p;
}
}
this._x = this._offsetX;
this._y = this._offsetY;
this._x -= this._boxX + this._handleX * this._boxWidth;
this._y -= this._boxY + this._handleY * this._boxHeight;
if (this._aligned && this._parent) {
this._parent.relativeMatrix();
this._x += this._alignX * this._parent._width;
this._y += this._alignY * this._parent._height;
}
rel.translate(this._x, this._y);
return this._relativeMatrix;
};
Pin.prototype.get = function(key) {
if (typeof getters[key] === 'function') {
return getters[key](this);
}
};
// TODO: Use defineProperty instead? What about multi-field pinning?
Pin.prototype.set = function(a, b) {
if (typeof a === 'string') {
if (typeof setters[a] === 'function' && typeof b !== 'undefined') {
setters[a](this, b);
}
} else if (typeof a === 'object') {
for (b in a) {
if (typeof setters[b] === 'function' && typeof a[b] !== 'undefined') {
setters[b](this, a[b], a);
}
}
}
if (this._owner) {
this._owner._ts_pin = ++iid;
this._owner.touch();
}
return this;
};
var getters = {
alpha : function(pin) {
return pin._alpha;
},
textureAlpha : function(pin) {
return pin._textureAlpha;
},
width : function(pin) {
return pin._width;
},
height : function(pin) {
return pin._height;
},
boxWidth : function(pin) {
return pin._boxWidth;
},
boxHeight : function(pin) {
return pin._boxHeight;
},
// scale : function(pin) {
// },
scaleX : function(pin) {
return pin._scaleX;
},
scaleY : function(pin) {
return pin._scaleY;
},
// skew : function(pin) {
// },
skewX : function(pin) {
return pin._skewX;
},
skewY : function(pin) {
return pin._skewY;
},
rotation : function(pin) {
return pin._rotation;
},
// pivot : function(pin) {
// },
pivotX : function(pin) {
return pin._pivotX;
},
pivotY : function(pin) {
return pin._pivotY;
},
// offset : function(pin) {
// },
offsetX : function(pin) {
return pin._offsetX;
},
offsetY : function(pin) {
return pin._offsetY;
},
// align : function(pin) {
// },
alignX : function(pin) {
return pin._alignX;
},
alignY : function(pin) {
return pin._alignY;
},
// handle : function(pin) {
// },
handleX : function(pin) {
return pin._handleX;
},
handleY : function(pin) {
return pin._handleY;
}
};
var setters = {
alpha : function(pin, value) {
pin._alpha = value;
},
textureAlpha : function(pin, value) {
pin._textureAlpha = value;
},
width : function(pin, value) {
pin._width_ = value;
pin._width = value;
pin._ts_transform = ++iid;
},
height : function(pin, value) {
pin._height_ = value;
pin._height = value;
pin._ts_transform = ++iid;
},
scale : function(pin, value) {
pin._scaleX = value;
pin._scaleY = value;
pin._ts_transform = ++iid;
},
scaleX : function(pin, value) {
pin._scaleX = value;
pin._ts_transform = ++iid;
},
scaleY : function(pin, value) {
pin._scaleY = value;
pin._ts_transform = ++iid;
},
skew : function(pin, value) {
pin._skewX = value;
pin._skewY = value;
pin._ts_transform = ++iid;
},
skewX : function(pin, value) {
pin._skewX = value;
pin._ts_transform = ++iid;
},
skewY : function(pin, value) {
pin._skewY = value;
pin._ts_transform = ++iid;
},
rotation : function(pin, value) {
pin._rotation = value;
pin._ts_transform = ++iid;
},
pivot : function(pin, value) {
pin._pivotX = value;
pin._pivotY = value;
pin._pivoted = true;
pin._ts_transform = ++iid;
},
pivotX : function(pin, value) {
pin._pivotX = value;
pin._pivoted = true;
pin._ts_transform = ++iid;
},
pivotY : function(pin, value) {
pin._pivotY = value;
pin._pivoted = true;
pin._ts_transform = ++iid;
},
offset : function(pin, value) {
pin._offsetX = value;
pin._offsetY = value;
pin._ts_translate = ++iid;
},
offsetX : function(pin, value) {
pin._offsetX = value;
pin._ts_translate = ++iid;
},
offsetY : function(pin, value) {
pin._offsetY = value;
pin._ts_translate = ++iid;
},
align : function(pin, value) {
this.alignX(pin, value);
this.alignY(pin, value);
},
alignX : function(pin, value) {
pin._alignX = value;
pin._aligned = true;
pin._ts_translate = ++iid;
this.handleX(pin, value);
},
alignY : function(pin, value) {
pin._alignY = value;
pin._aligned = true;
pin._ts_translate = ++iid;
this.handleY(pin, value);
},
handle : function(pin, value) {
this.handleX(pin, value);
this.handleY(pin, value);
},
handleX : function(pin, value) {
pin._handleX = value;
pin._handled = true;
pin._ts_translate = ++iid;
},
handleY : function(pin, value) {
pin._handleY = value;
pin._handled = true;
pin._ts_translate = ++iid;
},
resizeMode : function(pin, value, all) {
if (all) {
if (value == 'in') {
value = 'in-pad';
} else if (value == 'out') {
value = 'out-crop';
}
scaleTo(pin, all.resizeWidth, all.resizeHeight, value);
}
},
resizeWidth : function(pin, value, all) {
if (!all || !all.resizeMode) {
scaleTo(pin, value, null);
}
},
resizeHeight : function(pin, value, all) {
if (!all || !all.resizeMode) {
scaleTo(pin, null, value);
}
},
scaleMode : function(pin, value, all) {
if (all) {
scaleTo(pin, all.scaleWidth, all.scaleHeight, value);
}
},
scaleWidth : function(pin, value, all) {
if (!all || !all.scaleMode) {
scaleTo(pin, value, null);
}
},
scaleHeight : function(pin, value, all) {
if (!all || !all.scaleMode) {
scaleTo(pin, null, value);
}
},
matrix : function(pin, value) {
this.scaleX(pin, value.a);
this.skewX(pin, value.c / value.d);
this.skewY(pin, value.b / value.a);
this.scaleY(pin, value.d);
this.offsetX(pin, value.e);
this.offsetY(pin, value.f);
this.rotation(pin, 0);
}
};
function scaleTo(pin, width, height, mode) {
var w = typeof width === 'number';
var h = typeof height === 'number';
var m = typeof mode === 'string';
pin._ts_transform = ++iid;
if (w) {
pin._scaleX = width / pin._width_;
pin._width = pin._width_;
}
if (h) {
pin._scaleY = height / pin._height_;
pin._height = pin._height_;
}
if (w && h && m) {
if (mode == 'out' || mode == 'out-crop') {
pin._scaleX = pin._scaleY = Math.max(pin._scaleX, pin._scaleY);
} else if (mode == 'in' || mode == 'in-pad') {
pin._scaleX = pin._scaleY = Math.min(pin._scaleX, pin._scaleY);
}
if (mode == 'out-crop' || mode == 'in-pad') {
pin._width = width / pin._scaleX;
pin._height = height / pin._scaleY;
}
}
};
Class.prototype.scaleTo = function(a, b, c) {
if (typeof a === 'object')
c = b, b = a.y, a = a.x;
scaleTo(this._pin, a, b, c);
return this;
};
// Used by Tween class
Pin._add_shortcuts = function(Class) {
Class.prototype.size = function(w, h) {
this.pin('width', w);
this.pin('height', h);
return this;
};
Class.prototype.width = function(w) {
if (typeof w === 'undefined') {
return this.pin('width');
}
this.pin('width', w);
return this;
};
Class.prototype.height = function(h) {
if (typeof h === 'undefined') {
return this.pin('height');
}
this.pin('height', h);
return this;
};
Class.prototype.offset = function(a, b) {
if (typeof a === 'object')
b = a.y, a = a.x;
this.pin('offsetX', a);
this.pin('offsetY', b);
return this;
};
Class.prototype.rotate = function(a) {
this.pin('rotation', a);
return this;
};
Class.prototype.skew = function(a, b) {
if (typeof a === 'object')
b = a.y, a = a.x;
else if (typeof b === 'undefined')
b = a;
this.pin('skewX', a);
this.pin('skewY', b);
return this;
};
Class.prototype.scale = function(a, b) {
if (typeof a === 'object')
b = a.y, a = a.x;
else if (typeof b === 'undefined')
b = a;
this.pin('scaleX', a);
this.pin('scaleY', b);
return this;
};
Class.prototype.alpha = function(a, ta) {
this.pin('alpha', a);
if (typeof ta !== 'undefined') {
this.pin('textureAlpha', ta);
}
return this;
};
};
Pin._add_shortcuts(Class);
module.exports = Pin;
},{"./core":60,"./matrix":67}],69:[function(require,module,exports){
var Class = require('./core');
require('./pin');
require('./loop');
var stats = require('./util/stats');
var create = require('./util/create');
var extend = require('./util/extend');
Root._super = Class;
Root.prototype = create(Root._super.prototype);
Class.root = function(request, render) {
return new Root(request, render);
};
function Root(request, render) {
Root._super.call(this);
this.label('Root');
var paused = true;
var self = this;
var lastTime = 0;
var loop = function(now) {
if (paused === true) {
return;
}
stats.tick = stats.node = stats.draw = 0;
var last = lastTime || now;
var elapsed = now - last;
lastTime = now;
var ticked = self._tick(elapsed, now, last);
if (self._mo_touch != self._ts_touch) {
self._mo_touch = self._ts_touch;
render(self);
request(loop);
} else if (ticked) {
request(loop);
} else {
paused = true;
}
stats.fps = elapsed ? 1000 / elapsed : 0;
};
this.start = function() {
return this.resume();
};
this.resume = function() {
if (paused) {
this.publish('resume');
paused = false;
request(loop);
}
return this;
};
this.pause = function() {
if (!paused) {
this.publish('pause');
}
paused = true;
return this;
};
this.touch_root = this.touch;
this.touch = function() {
this.resume();
return this.touch_root();
};
};
Root.prototype.background = function(color) {
// to be implemented by loaders
return this;
};
Root.prototype.viewport = function(width, height, ratio) {
if (typeof width === 'undefined') {
return extend({}, this._viewport);
}
this._viewport = {
width : width,
height : height,
ratio : ratio || 1
};
this.viewbox();
var data = extend({}, this._viewport);
this.visit({
start : function(node) {
if (!node._flag('viewport')) {
return true;
}
node.publish('viewport', [ data ]);
}
});
return this;
};
// TODO: static/fixed viewbox
Root.prototype.viewbox = function(width, height, mode) {
if (typeof width === 'number' && typeof height === 'number') {
this._viewbox = {
width : width,
height : height,
mode : /^(in|out|in-pad|out-crop)$/.test(mode) ? mode : 'in-pad'
};
}
var box = this._viewbox;
var size = this._viewport;
if (size && box) {
this.pin({
width : box.width,
height : box.height
});
this.scaleTo(size.width, size.height, box.mode);
} else if (size) {
this.pin({
width : size.width,
height : size.height
});
}
return this;
};
},{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/extend":76,"./util/stats":80}],70:[function(require,module,exports){
var Class = require('./core');
require('./pin');
require('./loop');
var create = require('./util/create');
var is = require('./util/is');
Class.string = function(frames) {
return new Str().frames(frames);
};
Str._super = Class;
Str.prototype = create(Str._super.prototype);
function Str() {
Str._super.call(this);
this.label('String');
this._textures = [];
};
/**
* @deprecated Use frames
*/
Str.prototype.setFont = function(a, b, c) {
return this.frames(a, b, c);
};
Str.prototype.frames = function(frames) {
this._textures = [];
if (typeof frames == 'string') {
frames = Class.texture(frames);
this._item = function(value) {
return frames.one(value);
};
} else if (typeof frames === 'object') {
this._item = function(value) {
return frames[value];
};
} else if (typeof frames === 'function') {
this._item = frames;
}
return this;
};
/**
* @deprecated Use value
*/
Str.prototype.setValue = function(a, b, c) {
return this.value(a, b, c);
};
Str.prototype.value = function(value) {
if (typeof value === 'undefined') {
return this._value;
}
if (this._value === value) {
return this;
}
this._value = value;
if (value === null) {
value = '';
} else if (typeof value !== 'string' && !is.array(value)) {
value = value.toString();
}
this._spacing = this._spacing || 0;
var width = 0, height = 0;
for (var i = 0; i < value.length; i++) {
var image = this._textures[i] = this._item(value[i]);
width += i > 0 ? this._spacing : 0;
image.dest(width, 0);
width = width + image.width;
height = Math.max(height, image.height);
}
this.pin('width', width);
this.pin('height', height);
this._textures.length = value.length;
return this;
};
},{"./core":60,"./loop":66,"./pin":68,"./util/create":74,"./util/is":77}],71:[function(require,module,exports){
var stats = require('./util/stats');
var math = require('./util/math');
function Texture(image, ratio) {
if (typeof image === 'object') {
this.src(image, ratio);
}
}
Texture.prototype.pipe = function() {
return new Texture(this);
};
/**
* Signatures: (image), (x, y, w, h), (w, h)
*/
Texture.prototype.src = function(x, y, w, h) {
if (typeof x === 'object') {
var image = x, ratio = y || 1;
this._image = image;
this._sx = this._dx = 0;
this._sy = this._dy = 0;
this._sw = this._dw = image.width / ratio;
this._sh = this._dh = image.height / ratio;
this.width = image.width / ratio;
this.height = image.height / ratio;
this.ratio = ratio;
} else {
if (typeof w === 'undefined') {
w = x, h = y;
} else {
this._sx = x, this._sy = y;
}
this._sw = this._dw = w;
this._sh = this._dh = h;
this.width = w;
this.height = h;
}
return this;
};
/**
* Signatures: (x, y, w, h), (x, y)
*/
Texture.prototype.dest = function(x, y, w, h) {
this._dx = x, this._dy = y;
this._dx = x, this._dy = y;
if (typeof w !== 'undefined') {
this._dw = w, this._dh = h;
this.width = w, this.height = h;
}
return this;
};
Texture.prototype.draw = function(context, x1, y1, x2, y2, x3, y3, x4, y4) {
var image = this._image;
if (image === null || typeof image !== 'object') {
return;
}
var sx = this._sx, sy = this._sy;
var sw = this._sw, sh = this._sh;
var dx = this._dx, dy = this._dy;
var dw = this._dw, dh = this._dh;
if (typeof x3 !== 'undefined') {
x1 = math.limit(x1, 0, this._sw), x2 = math.limit(x2, 0, this._sw - x1);
y1 = math.limit(y1, 0, this._sh), y2 = math.limit(y2, 0, this._sh - y1);
sx += x1, sy += y1, sw = x2, sh = y2;
dx = x3, dy = y3, dw = x4, dh = y4;
} else if (typeof x2 !== 'undefined') {
dx = x1, dy = y1, dw = x2, dh = y2;
} else if (typeof x1 !== 'undefined') {
dw = x1, dh = y1;
}
var ratio = this.ratio || 1;
sx *= ratio, sy *= ratio, sw *= ratio, sh *= ratio;
try {
if (typeof image.draw === 'function') {
image.draw(context, sx, sy, sw, sh, dx, dy, dw, dh);
} else {
stats.draw++;
context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
}
} catch (ex) {
if (!image._draw_failed) {
console.log('Unable to draw: ', image);
console.log(ex);
image._draw_failed = true;
}
}
};
module.exports = Texture;
},{"./util/math":78,"./util/stats":80}],72:[function(require,module,exports){
var Class = require('./core');
var is = require('./util/is');
var iid = 0;
// TODO: do not clear next/prev/parent on remove
Class.prototype._label = '';
Class.prototype._visible = true;
Class.prototype._parent = null;
Class.prototype._next = null;
Class.prototype._prev = null;
Class.prototype._first = null;
Class.prototype._last = null;
Class.prototype._attrs = null;
Class.prototype._flags = null;
Class.prototype.toString = function() {
return '[' + this._label + ']';
};
/**
* @deprecated Use label()
*/
Class.prototype.id = function(id) {
return this.label(id);
};
Class.prototype.label = function(label) {
if (typeof label === 'undefined') {
return this._label;
}
this._label = label;
return this;
};
Class.prototype.attr = function(name, value) {
if (typeof value === 'undefined') {
return this._attrs !== null ? this._attrs[name] : undefined;
}
(this._attrs !== null ? this._attrs : this._attrs = {})[name] = value;
return this;
};
Class.prototype.visible = function(visible) {
if (typeof visible === 'undefined') {
return this._visible;
}
this._visible = visible;
this._parent && (this._parent._ts_children = ++iid);
this._ts_pin = ++iid;
this.touch();
return this;
};
Class.prototype.hide = function() {
return this.visible(false);
};
Class.prototype.show = function() {
return this.visible(true);
};
Class.prototype.parent = function() {
return this._parent;
};
Class.prototype.next = function(visible) {
var next = this._next;
while (next && visible && !next._visible) {
next = next._next;
}
return next;
};
Class.prototype.prev = function(visible) {
var prev = this._prev;
while (prev && visible && !prev._visible) {
prev = prev._prev;
}
return prev;
};
Class.prototype.first = function(visible) {
var next = this._first;
while (next && visible && !next._visible) {
next = next._next;
}
return next;
};
Class.prototype.last = function(visible) {
var prev = this._last;
while (prev && visible && !prev._visible) {
prev = prev._prev;
}
return prev;
};
Class.prototype.visit = function(visitor, data) {
var reverse = visitor.reverse;
var visible = visitor.visible;
if (visitor.start && visitor.start(this, data)) {
return;
}
var child, next = reverse ? this.last(visible) : this.first(visible);
while (child = next) {
next = reverse ? child.prev(visible) : child.next(visible);
if (child.visit(visitor, data)) {
return true;
}
}
return visitor.end && visitor.end(this, data);
};
Class.prototype.append = function(child, more) {
if (is.array(child))
for (var i = 0; i < child.length; i++)
append(this, child[i]);
else if (typeof more !== 'undefined') // deprecated
for (var i = 0; i < arguments.length; i++)
append(this, arguments[i]);
else if (typeof child !== 'undefined')
append(this, child);
return this;
};
Class.prototype.prepend = function(child, more) {
if (is.array(child))
for (var i = child.length - 1; i >= 0; i--)
prepend(this, child[i]);
else if (typeof more !== 'undefined') // deprecated
for (var i = arguments.length - 1; i >= 0; i--)
prepend(this, arguments[i]);
else if (typeof child !== 'undefined')
prepend(this, child);
return this;
};
Class.prototype.appendTo = function(parent) {
append(parent, this);
return this;
};
Class.prototype.prependTo = function(parent) {
prepend(parent, this);
return this;
};
Class.prototype.insertNext = function(sibling, more) {
if (is.array(sibling))
for (var i = 0; i < sibling.length; i++)
insertAfter(sibling[i], this);
else if (typeof more !== 'undefined') // deprecated
for (var i = 0; i < arguments.length; i++)
insertAfter(arguments[i], this);
else if (typeof sibling !== 'undefined')
insertAfter(sibling, this);
return this;
};
Class.prototype.insertPrev = function(sibling, more) {
if (is.array(sibling))
for (var i = sibling.length - 1; i >= 0; i--)
insertBefore(sibling[i], this);
else if (typeof more !== 'undefined') // deprecated
for (var i = arguments.length - 1; i >= 0; i--)
insertBefore(arguments[i], this);
else if (typeof sibling !== 'undefined')
insertBefore(sibling, this);
return this;
};
Class.prototype.insertAfter = function(prev) {
insertAfter(this, prev);
return this;
};
Class.prototype.insertBefore = function(next) {
insertBefore(this, next);
return this;
};
function append(parent, child) {
_ensure(child);
_ensure(parent);
child.remove();
if (parent._last) {
parent._last._next = child;
child._prev = parent._last;
}
child._parent = parent;
parent._last = child;
if (!parent._first) {
parent._first = child;
}
child._parent._flag(child, true);
child._ts_parent = ++iid;
parent._ts_children = ++iid;
parent.touch();
}
function prepend(parent, child) {
_ensure(child);
_ensure(parent);
child.remove();
if (parent._first) {
parent._first._prev = child;
child._next = parent._first;
}
child._parent = parent;
parent._first = child;
if (!parent._last) {
parent._last = child;
}
child._parent._flag(child, true);
child._ts_parent = ++iid;
parent._ts_children = ++iid;
parent.touch();
};
function insertBefore(self, next) {
_ensure(self);
_ensure(next);
self.remove();
var parent = next._parent;
var prev = next._prev;
next._prev = self;
prev && (prev._next = self) || parent && (parent._first = self);
self._parent = parent;
self._prev = prev;
self._next = next;
self._parent._flag(self, true);
self._ts_parent = ++iid;
self.touch();
};
function insertAfter(self, prev) {
_ensure(self);
_ensure(prev);
self.remove();
var parent = prev._parent;
var next = prev._next;
prev._next = self;
next && (next._prev = self) || parent && (parent._last = self);
self._parent = parent;
self._prev = prev;
self._next = next;
self._parent._flag(self, true);
self._ts_parent = ++iid;
self.touch();
};
Class.prototype.remove = function(child, more) {
if (typeof child !== 'undefined') {
if (is.array(child)) {
for (var i = 0; i < child.length; i++)
_ensure(child[i]).remove();
} else if (typeof more !== 'undefined') {
for (var i = 0; i < arguments.length; i++)
_ensure(arguments[i]).remove();
} else {
_ensure(child).remove();
}
return this;
}
if (this._prev) {
this._prev._next = this._next;
}
if (this._next) {
this._next._prev = this._prev;
}
if (this._parent) {
if (this._parent._first === this) {
this._parent._first = this._next;
}
if (this._parent._last === this) {
this._parent._last = this._prev;
}
this._parent._flag(this, false);
this._parent._ts_children = ++iid;
this._parent.touch();
}
this._prev = this._next = this._parent = null;
this._ts_parent = ++iid;
// this._parent.touch();
return this;
};
Class.prototype.empty = function() {
var child, next = this._first;
while (child = next) {
next = child._next;
child._prev = child._next = child._parent = null;
this._flag(child, false);
}
this._first = this._last = null;
this._ts_children = ++iid;
this.touch();
return this;
};
Class.prototype.touch = function() {
this._ts_touch = ++iid;
this._parent && this._parent.touch();
return this;
};
/**
* Deep flags used for optimizing event distribution.
*/
Class.prototype._flag = function(obj, name) {
if (typeof name === 'undefined') {
return this._flags !== null && this._flags[obj] || 0;
}
if (typeof obj === 'string') {
if (name) {
this._flags = this._flags || {};
if (!this._flags[obj] && this._parent) {
this._parent._flag(obj, true);
}
this._flags[obj] = (this._flags[obj] || 0) + 1;
} else if (this._flags && this._flags[obj] > 0) {
if (this._flags[obj] == 1 && this._parent) {
this._parent._flag(obj, false);
}
this._flags[obj] = this._flags[obj] - 1;
}
}
if (typeof obj === 'object') {
if (obj._flags) {
for ( var type in obj._flags) {
if (obj._flags[type] > 0) {
this._flag(type, name);
}
}
}
}
return this;
};
/**
* @private
*/
Class.prototype.hitTest = function(hit) {
if (this.attr('spy')) {
return true;
}
return hit.x >= 0 && hit.x <= this._pin._width && hit.y >= 0
&& hit.y <= this._pin._height;
};
function _ensure(obj) {
if (obj && obj instanceof Class) {
return obj;
}
throw 'Invalid node: ' + obj;
};
module.exports = Class;
},{"./core":60,"./util/is":77}],73:[function(require,module,exports){
module.exports = function() {
var count = 0;
function fork(fn, n) {
count += n = (typeof n === 'number' && n >= 1 ? n : 1);
return function() {
fn && fn.apply(this, arguments);
if (n > 0) {
n--, count--, call();
}
};
}
var then = [];
function call() {
if (count === 0) {
while (then.length) {
setTimeout(then.shift(), 0);
}
}
}
fork.then = function(fn) {
if (count === 0) {
setTimeout(fn, 0);
} else {
then.push(fn);
}
};
return fork;
};
},{}],74:[function(require,module,exports){
if (typeof Object.create == 'function') {
module.exports = function(proto, props) {
return Object.create.call(Object, proto, props);
};
} else {
module.exports = function(proto, props) {
if (props)
throw Error('Second argument is not supported!');
if (typeof proto !== 'object' || proto === null)
throw Error('Invalid prototype!');
noop.prototype = proto;
return new noop;
};
function noop() {
}
}
},{}],75:[function(require,module,exports){
module.exports = function(prototype, callback) {
prototype._listeners = null;
prototype.on = prototype.listen = function(types, listener) {
if (!types || !types.length || typeof listener !== 'function') {
return this;
}
if (this._listeners === null) {
this._listeners = {};
}
var isarray = typeof types !== 'string' && typeof types.join === 'function';
if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) {
for (var i = 0; i < types.length; i++) {
var type = types[i];
this._listeners[type] = this._listeners[type] || [];
this._listeners[type].push(listener);
if (typeof callback === 'function') {
callback(this, type, true);
}
}
}
return this;
};
prototype.off = function(types, listener) {
if (!types || !types.length || typeof listener !== 'function') {
return this;
}
if (this._listeners === null) {
return this;
}
var isarray = typeof types !== 'string' && typeof types.join === 'function';
if (types = (isarray ? types.join(' ') : types).match(/\S+/g)) {
for (var i = 0; i < types.length; i++) {
var type = types[i], all = this._listeners[type], index;
if (all && (index = all.indexOf(listener)) >= 0) {
all.splice(index, 1);
if (!all.length) {
delete this._listeners[type];
}
if (typeof callback === 'function') {
callback(this, type, false);
}
}
}
}
return this;
};
prototype.listeners = function(type) {
return this._listeners && this._listeners[type];
};
prototype.publish = function(name, args) {
var listeners = this.listeners(name);
if (!listeners || !listeners.length) {
return 0;
}
for (var l = 0; l < listeners.length; l++) {
listeners[l].apply(this, args);
}
return listeners.length;
};
prototype.trigger = function(name, args) {
this.publish(name, args);
return this;
};
};
},{}],76:[function(require,module,exports){
module.exports = function(base) {
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
for ( var key in obj) {
if (obj.hasOwnProperty(key)) {
base[key] = obj[key];
}
}
}
return base;
};
},{}],77:[function(require,module,exports){
/**
* ! is the definitive JavaScript type testing library
*
* @copyright 2013-2014 Enrico Marino / Jordan Harband
* @license MIT
*/
var objProto = Object.prototype;
var owns = objProto.hasOwnProperty;
var toStr = objProto.toString;
var NON_HOST_TYPES = {
'boolean' : 1,
'number' : 1,
'string' : 1,
'undefined' : 1
};
var hexRegex = /^[A-Fa-f0-9]+$/;
var is = module.exports = {};
is.a = is.an = is.type = function(value, type) {
return typeof value === type;
};
is.defined = function(value) {
return typeof value !== 'undefined';
};
is.empty = function(value) {
var type = toStr.call(value);
var key;
if ('[object Array]' === type || '[object Arguments]' === type
|| '[object String]' === type) {
return value.length === 0;
}
if ('[object Object]' === type) {
for (key in value) {
if (owns.call(value, key)) {
return false;
}
}
return true;
}
return !value;
};
is.equal = function(value, other) {
if (value === other) {
return true;
}
var type = toStr.call(value);
var key;
if (type !== toStr.call(other)) {
return false;
}
if ('[object Object]' === type) {
for (key in value) {
if (!is.equal(value[key], other[key]) || !(key in other)) {
return false;
}
}
for (key in other) {
if (!is.equal(value[key], other[key]) || !(key in value)) {
return false;
}
}
return true;
}
if ('[object Array]' === type) {
key = value.length;
if (key !== other.length) {
return false;
}
while (--key) {
if (!is.equal(value[key], other[key])) {
return false;
}
}
return true;
}
if ('[object Function]' === type) {
return value.prototype === other.prototype;
}
if ('[object Date]' === type) {
return value.getTime() === other.getTime();
}
return false;
};
is.instance = function(value, constructor) {
return value instanceof constructor;
};
is.nil = function(value) {
return value === null;
};
is.undef = function(value) {
return typeof value === 'undefined';
};
is.array = function(value) {
return '[object Array]' === toStr.call(value);
};
is.emptyarray = function(value) {
return is.array(value) && value.length === 0;
};
is.arraylike = function(value) {
return !!value && !is.boolean(value) && owns.call(value, 'length')
&& isFinite(value.length) && is.number(value.length) && value.length >= 0;
};
is.boolean = function(value) {
return '[object Boolean]' === toStr.call(value);
};
is.element = function(value) {
return value !== undefined && typeof HTMLElement !== 'undefined'
&& value instanceof HTMLElement && value.nodeType === 1;
};
is.fn = function(value) {
return '[object Function]' === toStr.call(value);
};
is.number = function(value) {
return '[object Number]' === toStr.call(value);
};
is.nan = function(value) {
return !is.number(value) || value !== value;
};
is.object = function(value) {
return '[object Object]' === toStr.call(value);
};
is.hash = function(value) {
return is.object(value) && value.constructor === Object && !value.nodeType
&& !value.setInterval;
};
is.regexp = function(value) {
return '[object RegExp]' === toStr.call(value);
};
is.string = function(value) {
return '[object String]' === toStr.call(value);
};
is.hex = function(value) {
return is.string(value) && (!value.length || hexRegex.test(value));
};
},{}],78:[function(require,module,exports){
var create = require('./create');
var native = Math;
module.exports = create(Math);
module.exports.random = function(min, max) {
if (typeof min === 'undefined') {
max = 1, min = 0;
} else if (typeof max === 'undefined') {
max = min, min = 0;
}
return min == max ? min : native.random() * (max - min) + min;
};
module.exports.rotate = function(num, min, max) {
if (typeof min === 'undefined') {
max = 1, min = 0;
} else if (typeof max === 'undefined') {
max = min, min = 0;
}
if (max > min) {
num = (num - min) % (max - min);
return num + (num < 0 ? max : min);
} else {
num = (num - max) % (min - max);
return num + (num <= 0 ? min : max);
}
};
module.exports.limit = function(num, min, max) {
if (num < min) {
return min;
} else if (num > max) {
return max;
} else {
return num;
}
};
module.exports.length = function(x, y) {
return native.sqrt(x * x + y * y);
};
},{"./create":74}],79:[function(require,module,exports){
module.exports = function(img, owidth, oheight, stretch, inner, insert) {
var width = img.width;
var height = img.height;
var left = img.left;
var right = img.right;
var top = img.top;
var bottom = img.bottom;
left = typeof left === 'number' && left === left ? left : 0;
right = typeof right === 'number' && right === right ? right : 0;
top = typeof top === 'number' && top === top ? top : 0;
bottom = typeof bottom === 'number' && bottom === bottom ? bottom : 0;
width = width - left - right;
height = height - top - bottom;
if (!inner) {
owidth = Math.max(owidth - left - right, 0);
oheight = Math.max(oheight - top - bottom, 0);
}
var i = 0;
if (top > 0 && left > 0)
insert(i++, 0, 0, left, top, 0, 0, left, top);
if (bottom > 0 && left > 0)
insert(i++, 0, height + top, left, bottom, 0, oheight + top, left, bottom);
if (top > 0 && right > 0)
insert(i++, width + left, 0, right, top, owidth + left, 0, right, top);
if (bottom > 0 && right > 0)
insert(i++, width + left, height + top, right, bottom, owidth + left,
oheight + top, right, bottom);
if (stretch) {
if (top > 0)
insert(i++, left, 0, width, top, left, 0, owidth, top);
if (bottom > 0)
insert(i++, left, height + top, width, bottom, left, oheight + top,
owidth, bottom);
if (left > 0)
insert(i++, 0, top, left, height, 0, top, left, oheight);
if (right > 0)
insert(i++, width + left, top, right, height, owidth + left, top, right,
oheight);
// center
insert(i++, left, top, width, height, left, top, owidth, oheight);
} else { // tile
var l = left, r = owidth, w;
while (r > 0) {
w = Math.min(width, r), r -= width;
var t = top, b = oheight, h;
while (b > 0) {
h = Math.min(height, b), b -= height;
insert(i++, left, top, w, h, l, t, w, h);
if (r <= 0) {
if (left)
insert(i++, 0, top, left, h, 0, t, left, h);
if (right)
insert(i++, width + left, top, right, h, l + w, t, right, h);
}
t += h;
}
if (top)
insert(i++, left, 0, w, top, l, 0, w, top);
if (bottom)
insert(i++, left, height + top, w, bottom, l, t, w, bottom);
l += w;
}
}
return i;
};
},{}],80:[function(require,module,exports){
module.exports = {};
},{}],81:[function(require,module,exports){
module.exports.startsWith = function(str, sub) {
return typeof str === 'string' && typeof sub === 'string'
&& str.substring(0, sub.length) == sub;
};
},{}],82:[function(require,module,exports){
module.exports = require('../lib/');
require('../lib/canvas');
require('../lib/image');
require('../lib/anim');
require('../lib/str');
require('../lib/layout');
require('../lib/addon/tween');
module.exports.Mouse = require('../lib/addon/mouse');
module.exports.Math = require('../lib/util/math');
module.exports._extend = require('../lib/util/extend');
module.exports._create = require('../lib/util/create');
require('../lib/loader/web');
},{"../lib/":63,"../lib/addon/mouse":55,"../lib/addon/tween":56,"../lib/anim":57,"../lib/canvas":59,"../lib/image":62,"../lib/layout":64,"../lib/loader/web":65,"../lib/str":70,"../lib/util/create":74,"../lib/util/extend":76,"../lib/util/math":78}]},{},[1])(1)
}); | PeterDaveHello/jsdelivr | files/planck/0.1.34/planck-with-testbed.js | JavaScript | mit | 464,606 |
module.exports = function isString (value) {
return Object.prototype.toString.call(value) === '[object String]'
}
| chrisdavidmills/express-local-library | node_modules/helmet-csp/lib/is-string.js | JavaScript | mit | 116 |
/*
* The MIT License
* Copyright (c) 2012 Microsoft Corporation
*
* 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.
*/
package microsoft.exchange.webservices.data.core.request;
import microsoft.exchange.webservices.data.core.EwsServiceXmlWriter;
import microsoft.exchange.webservices.data.core.EwsUtilities;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.XmlElementNames;
import microsoft.exchange.webservices.data.core.enumeration.service.error.ServiceErrorHandling;
import microsoft.exchange.webservices.data.core.response.ServiceResponse;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.enumeration.misc.XmlNamespace;
import microsoft.exchange.webservices.data.misc.ItemIdWrapperList;
/**
* Represents an abstract Move/Copy Item request.
*
* @param <TResponse> The type of the response.
*/
public abstract class MoveCopyItemRequest<TResponse extends ServiceResponse>
extends MoveCopyRequest<Item, TResponse> {
private ItemIdWrapperList itemIds = new ItemIdWrapperList();
private Boolean newItemIds;
/**
* Validates request.
*
* @throws Exception the exception
*/
@Override
public void validate() throws Exception {
super.validate();
EwsUtilities.validateParam(this.getItemIds(), "ItemIds");
}
/**
* Initializes a new instance of the class.
*
* @param service the service
* @param errorHandlingMode the error handling mode
* @throws Exception on error
*/
protected MoveCopyItemRequest(ExchangeService service,
ServiceErrorHandling errorHandlingMode)
throws Exception {
super(service, errorHandlingMode);
}
/**
* Writes the ids as XML.
*
* @param writer the writer
* @throws Exception the exception
*/
@Override
protected void writeIdsToXml(EwsServiceXmlWriter writer) throws Exception {
this.getItemIds().writeToXml(writer, XmlNamespace.Messages,
XmlElementNames.ItemIds);
if (this.getReturnNewItemIds() != null) {
writer.writeElementValue(
XmlNamespace.Messages,
XmlElementNames.ReturnNewItemIds,
this.getReturnNewItemIds());
}
}
/**
* Gets the expected response message count.
*
* @return Number of expected response messages.
*/
@Override
protected int getExpectedResponseMessageCount() {
return this.getItemIds().getCount();
}
/**
* Gets the item ids.
*
* @return the item ids
*/
public ItemIdWrapperList getItemIds() {
return this.itemIds;
}
protected Boolean getReturnNewItemIds() {
return this.newItemIds;
}
public void setReturnNewItemIds(Boolean value) {
this.newItemIds = value;
}
}
| KatharineYe/ews-java-api | src/main/java/microsoft/exchange/webservices/data/core/request/MoveCopyItemRequest.java | Java | mit | 3,795 |
import { Teammates } from "../../";
export = Teammates;
| georgemarshall/DefinitelyTyped | types/carbon__pictograms-react/lib/teammates/index.d.ts | TypeScript | mit | 57 |
self.description = "Install a package from a sync db with fnmatch'ed NoExtract"
sp = pmpkg("dummy")
sp.files = ["bin/dummy",
"usr/share/man/man8",
"usr/share/man/man1/dummy.1"]
self.addpkg2db("sync", sp)
self.option["NoExtract"] = ["usr/share/man/*"]
self.args = "-S %s" % sp.name
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_EXIST=dummy")
self.addrule("FILE_EXIST=bin/dummy")
self.addrule("!FILE_EXIST=usr/share/man/man8")
self.addrule("!FILE_EXIST=usr/share/man/man1/dummy.1")
| kylon/pacman-fakeroot | test/pacman/tests/sync502.py | Python | gpl-2.0 | 513 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/media/audio_sync_reader.h"
#include <algorithm>
#include "base/command_line.h"
#include "base/memory/shared_memory.h"
#include "base/metrics/histogram.h"
#include "content/public/common/content_switches.h"
#include "media/audio/audio_buffers_state.h"
#include "media/audio/audio_parameters.h"
using media::AudioBus;
namespace content {
AudioSyncReader::AudioSyncReader(base::SharedMemory* shared_memory,
const media::AudioParameters& params,
int input_channels)
: shared_memory_(shared_memory),
input_channels_(input_channels),
mute_audio_(CommandLine::ForCurrentProcess()->HasSwitch(
switches::kMuteAudio)),
packet_size_(shared_memory_->requested_size()),
renderer_callback_count_(0),
renderer_missed_callback_count_(0),
#if defined(OS_MACOSX)
maximum_wait_time_(params.GetBufferDuration() / 2),
#else
// TODO(dalecurtis): Investigate if we can reduce this on all platforms.
maximum_wait_time_(base::TimeDelta::FromMilliseconds(20)),
#endif
buffer_index_(0) {
int input_memory_size = 0;
int output_memory_size = AudioBus::CalculateMemorySize(params);
if (input_channels_ > 0) {
// The input storage is after the output storage.
int frames = params.frames_per_buffer();
input_memory_size = AudioBus::CalculateMemorySize(input_channels_, frames);
char* input_data =
static_cast<char*>(shared_memory_->memory()) + output_memory_size;
input_bus_ = AudioBus::WrapMemory(input_channels_, frames, input_data);
input_bus_->Zero();
}
DCHECK_EQ(packet_size_, output_memory_size + input_memory_size);
output_bus_ = AudioBus::WrapMemory(params, shared_memory->memory());
output_bus_->Zero();
}
AudioSyncReader::~AudioSyncReader() {
if (!renderer_callback_count_)
return;
// Recording the percentage of deadline misses gives us a rough overview of
// how many users might be running into audio glitches.
int percentage_missed =
100.0 * renderer_missed_callback_count_ / renderer_callback_count_;
UMA_HISTOGRAM_PERCENTAGE(
"Media.AudioRendererMissedDeadline", percentage_missed);
}
// media::AudioOutputController::SyncReader implementations.
void AudioSyncReader::UpdatePendingBytes(uint32 bytes) {
// Zero out the entire output buffer to avoid stuttering/repeating-buffers
// in the anomalous case if the renderer is unable to keep up with real-time.
output_bus_->Zero();
socket_->Send(&bytes, sizeof(bytes));
++buffer_index_;
}
void AudioSyncReader::Read(const AudioBus* source, AudioBus* dest) {
++renderer_callback_count_;
if (!WaitUntilDataIsReady()) {
++renderer_missed_callback_count_;
dest->Zero();
return;
}
// Copy optional synchronized live audio input for consumption by renderer
// process.
if (input_bus_) {
if (source)
source->CopyTo(input_bus_.get());
else
input_bus_->Zero();
}
if (mute_audio_)
dest->Zero();
else
output_bus_->CopyTo(dest);
}
void AudioSyncReader::Close() {
socket_->Close();
}
bool AudioSyncReader::Init() {
socket_.reset(new base::CancelableSyncSocket());
foreign_socket_.reset(new base::CancelableSyncSocket());
return base::CancelableSyncSocket::CreatePair(socket_.get(),
foreign_socket_.get());
}
#if defined(OS_WIN)
bool AudioSyncReader::PrepareForeignSocketHandle(
base::ProcessHandle process_handle,
base::SyncSocket::Handle* foreign_handle) {
::DuplicateHandle(GetCurrentProcess(), foreign_socket_->handle(),
process_handle, foreign_handle,
0, FALSE, DUPLICATE_SAME_ACCESS);
return (*foreign_handle != 0);
}
#else
bool AudioSyncReader::PrepareForeignSocketHandle(
base::ProcessHandle process_handle,
base::FileDescriptor* foreign_handle) {
foreign_handle->fd = foreign_socket_->handle();
foreign_handle->auto_close = false;
return (foreign_handle->fd != -1);
}
#endif
bool AudioSyncReader::WaitUntilDataIsReady() {
base::TimeDelta timeout = maximum_wait_time_;
const base::TimeTicks start_time = base::TimeTicks::Now();
const base::TimeTicks finish_time = start_time + timeout;
// Check if data is ready and if not, wait a reasonable amount of time for it.
//
// Data readiness is achieved via parallel counters, one on the renderer side
// and one here. Every time a buffer is requested via UpdatePendingBytes(),
// |buffer_index_| is incremented. Subsequently every time the renderer has a
// buffer ready it increments its counter and sends the counter value over the
// SyncSocket. Data is ready when |buffer_index_| matches the counter value
// received from the renderer.
//
// The counter values may temporarily become out of sync if the renderer is
// unable to deliver audio fast enough. It's assumed that the renderer will
// catch up at some point, which means discarding counter values read from the
// SyncSocket which don't match our current buffer index.
size_t bytes_received = 0;
uint32 renderer_buffer_index = 0;
while (timeout.InMicroseconds() > 0) {
bytes_received = socket_->ReceiveWithTimeout(
&renderer_buffer_index, sizeof(renderer_buffer_index), timeout);
if (!bytes_received)
break;
DCHECK_EQ(bytes_received, sizeof(renderer_buffer_index));
if (renderer_buffer_index == buffer_index_)
break;
// Reduce the timeout value as receives succeed, but aren't the right index.
timeout = finish_time - base::TimeTicks::Now();
}
// Receive timed out or another error occurred. Receive can timeout if the
// renderer is unable to deliver audio data within the allotted time.
if (!bytes_received || renderer_buffer_index != buffer_index_) {
DVLOG(2) << "AudioSyncReader::WaitUntilDataIsReady() timed out.";
base::TimeDelta time_since_start = base::TimeTicks::Now() - start_time;
UMA_HISTOGRAM_CUSTOM_TIMES("Media.AudioOutputControllerDataNotReady",
time_since_start,
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(1000),
50);
return false;
}
return true;
}
} // namespace content
| qtekfun/htcDesire820Kernel | external/chromium_org/content/browser/renderer_host/media/audio_sync_reader.cc | C++ | gpl-2.0 | 6,518 |
<?php
/**
* Discussion
*
* @package ThematicCoreLibrary
* @subpackage Discussion
*/
/**
* Custom callback function to list comments in the Thematic style.
*
* If you want to use your own comments callback for wp_list_comments, filter list_comments_arg
*
* @param object $comment
* @param array $args
* @param int $depth
*/
function thematic_comments($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
$GLOBALS['comment_depth'] = $depth;
?>
<li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>>
<?php
// action hook for inserting content above #comment
thematic_abovecomment();
?>
<div class="comment-author vcard"><?php thematic_commenter_link() ?></div>
<?php thematic_commentmeta(TRUE); ?>
<?php
if ( $comment->comment_approved == '0' ) {
echo "\t\t\t\t\t" . '<span class="unapproved">';
_e( 'Your comment is awaiting moderation', 'thematic' );
echo ".</span>\n";
}
?>
<div class="comment-content">
<?php comment_text() ?>
</div>
<?php // echo the comment reply link with help from Justin Tadlock http://justintadlock.com/ and Will Norris http://willnorris.com/
if( $args['type'] == 'all' || get_comment_type() == 'comment' ) :
comment_reply_link( array_merge( $args, array(
'reply_text' => __( 'Reply','thematic' ),
'login_text' => __( 'Log in to reply.','thematic' ),
'depth' => $depth,
'before' => '<div class="comment-reply-link">',
'after' => '</div>'
)));
endif;
?>
<?php
// action hook for inserting content above #comment
thematic_belowcomment()
?>
<?php }
/**
* Custom callback to list pings in the Thematic style
*
* @param object $comment
* @param array $args
* @param int $depth
*/
function thematic_pings($comment, $args, $depth) {
$GLOBALS['comment'] = $comment;
?>
<li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>>
<div class="comment-author"><?php printf(_x('By %1$s on %2$s at %3$s', 'By {$authorlink} on {$date} at {$time}', 'thematic'),
get_comment_author_link(),
get_comment_date(),
get_comment_time() );
edit_comment_link(__('Edit', 'thematic'), ' <span class="meta-sep">|</span>' . "\n\n\t\t\t\t\t\t" . '<span class="edit-link">', '</span>'); ?>
</div>
<?php
if ($comment->comment_approved == '0') {
echo "\t\t\t\t\t" . '<span class="unapproved">';
_e( 'Your trackback is awaiting moderation', 'thematic' );
echo ".</span>\n";
}
?>
<div class="comment-content">
<?php comment_text() ?>
</div>
<?php }
| bourroush/blog-17aout | wp-content/themes/thematic/library/extensions/discussion.php | PHP | gpl-2.0 | 2,891 |
// Generated by CoffeeScript 1.4.0
(function() {
var RoomIO;
RoomIO = require('./room').RoomIO;
exports.RequestIO = (function() {
function RequestIO(socket, request, io) {
this.socket = socket;
this.request = request;
this.manager = io;
}
RequestIO.prototype.broadcast = function(event, message) {
return this.socket.broadcast.emit(event, message);
};
RequestIO.prototype.emit = function(event, message) {
return this.socket.emit(event, message);
};
RequestIO.prototype.room = function(room) {
return new RoomIO(room, this.socket);
};
RequestIO.prototype.join = function(room) {
return this.socket.join(room);
};
RequestIO.prototype.route = function(route) {
return this.manager.route(route, this.request, {
trigger: true
});
};
RequestIO.prototype.leave = function(room) {
return this.socket.leave(room);
};
RequestIO.prototype.on = function() {
var args;
args = Array.prototype.slice.call(arguments, 0);
return this.sockets.on.apply(this.socket, args);
};
RequestIO.prototype.disconnect = function(callback) {
return this.socket.disconnect(callback);
};
return RequestIO;
})();
}).call(this);
| mekinney/transparica | webapp/node_modules/express.io/compiled/request.js | JavaScript | gpl-2.0 | 1,285 |
# -*- coding: utf-8 -*-
from . import project_sla
from . import analytic_account
from . import project_sla_control
from . import project_issue
from . import project_task
from . import report
| sergiocorato/project-service | project_sla/__init__.py | Python | agpl-3.0 | 191 |
from nose.tools import *
from framework.mongo import database as db
from scripts.remove_wiki_title_forward_slashes import main
from tests.base import OsfTestCase
from tests.factories import NodeWikiFactory, ProjectFactory
class TestRemoveWikiTitleForwardSlashes(OsfTestCase):
def test_forward_slash_is_removed_from_wiki_title(self):
project = ProjectFactory()
wiki = NodeWikiFactory(node=project)
invalid_name = 'invalid/name'
db.nodewikipage.update({'_id': wiki._id}, {'$set': {'page_name': invalid_name}})
project.wiki_pages_current['invalid/name'] = project.wiki_pages_current[wiki.page_name]
project.wiki_pages_versions['invalid/name'] = project.wiki_pages_versions[wiki.page_name]
project.save()
main()
wiki.reload()
assert_equal(wiki.page_name, 'invalidname')
assert_in('invalidname', project.wiki_pages_current)
assert_in('invalidname', project.wiki_pages_versions)
def test_valid_wiki_title(self):
project = ProjectFactory()
wiki = NodeWikiFactory(node=project)
page_name = wiki.page_name
main()
wiki.reload()
assert_equal(page_name, wiki.page_name)
assert_in(page_name, project.wiki_pages_current)
assert_in(page_name, project.wiki_pages_versions)
| rdhyee/osf.io | scripts/tests/test_remove_wiki_title_forward_slashes.py | Python | apache-2.0 | 1,335 |
name "runit_test"
maintainer "Opscode, Inc."
maintainer_email "cookbooks@opscode.com"
license "Apache 2.0"
description "This cookbook is used with test-kitchen to test the parent, runit cookbok"
version "1.0.0"
| dialoghq/runit | test/kitchen/cookbooks/runit_test/metadata.rb | Ruby | apache-2.0 | 258 |
package hclog
import (
"bufio"
"bytes"
"encoding"
"encoding/json"
"fmt"
"log"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
var (
_levelToBracket = map[Level]string{
Debug: "[DEBUG]",
Trace: "[TRACE]",
Info: "[INFO] ",
Warn: "[WARN] ",
Error: "[ERROR]",
}
)
// Given the options (nil for defaults), create a new Logger
func New(opts *LoggerOptions) Logger {
if opts == nil {
opts = &LoggerOptions{}
}
output := opts.Output
if output == nil {
output = os.Stderr
}
level := opts.Level
if level == NoLevel {
level = DefaultLevel
}
mtx := opts.Mutex
if mtx == nil {
mtx = new(sync.Mutex)
}
ret := &intLogger{
m: mtx,
json: opts.JSONFormat,
caller: opts.IncludeLocation,
name: opts.Name,
timeFormat: TimeFormat,
w: bufio.NewWriter(output),
level: new(int32),
}
if opts.TimeFormat != "" {
ret.timeFormat = opts.TimeFormat
}
atomic.StoreInt32(ret.level, int32(level))
return ret
}
// The internal logger implementation. Internal in that it is defined entirely
// by this package.
type intLogger struct {
json bool
caller bool
name string
timeFormat string
// this is a pointer so that it's shared by any derived loggers, since
// those derived loggers share the bufio.Writer as well.
m *sync.Mutex
w *bufio.Writer
level *int32
implied []interface{}
}
// Make sure that intLogger is a Logger
var _ Logger = &intLogger{}
// The time format to use for logging. This is a version of RFC3339 that
// contains millisecond precision
const TimeFormat = "2006-01-02T15:04:05.000Z0700"
// Log a message and a set of key/value pairs if the given level is at
// or more severe that the threshold configured in the Logger.
func (z *intLogger) Log(level Level, msg string, args ...interface{}) {
if level < Level(atomic.LoadInt32(z.level)) {
return
}
t := time.Now()
z.m.Lock()
defer z.m.Unlock()
if z.json {
z.logJson(t, level, msg, args...)
} else {
z.log(t, level, msg, args...)
}
z.w.Flush()
}
// Cleanup a path by returning the last 2 segments of the path only.
func trimCallerPath(path string) string {
// lovely borrowed from zap
// nb. To make sure we trim the path correctly on Windows too, we
// counter-intuitively need to use '/' and *not* os.PathSeparator here,
// because the path given originates from Go stdlib, specifically
// runtime.Caller() which (as of Mar/17) returns forward slashes even on
// Windows.
//
// See https://github.com/golang/go/issues/3335
// and https://github.com/golang/go/issues/18151
//
// for discussion on the issue on Go side.
//
// Find the last separator.
//
idx := strings.LastIndexByte(path, '/')
if idx == -1 {
return path
}
// Find the penultimate separator.
idx = strings.LastIndexByte(path[:idx], '/')
if idx == -1 {
return path
}
return path[idx+1:]
}
// Non-JSON logging format function
func (z *intLogger) log(t time.Time, level Level, msg string, args ...interface{}) {
z.w.WriteString(t.Format(z.timeFormat))
z.w.WriteByte(' ')
s, ok := _levelToBracket[level]
if ok {
z.w.WriteString(s)
} else {
z.w.WriteString("[?????]")
}
if z.caller {
if _, file, line, ok := runtime.Caller(3); ok {
z.w.WriteByte(' ')
z.w.WriteString(trimCallerPath(file))
z.w.WriteByte(':')
z.w.WriteString(strconv.Itoa(line))
z.w.WriteByte(':')
}
}
z.w.WriteByte(' ')
if z.name != "" {
z.w.WriteString(z.name)
z.w.WriteString(": ")
}
z.w.WriteString(msg)
args = append(z.implied, args...)
var stacktrace CapturedStacktrace
if args != nil && len(args) > 0 {
if len(args)%2 != 0 {
cs, ok := args[len(args)-1].(CapturedStacktrace)
if ok {
args = args[:len(args)-1]
stacktrace = cs
} else {
args = append(args, "<unknown>")
}
}
z.w.WriteByte(':')
FOR:
for i := 0; i < len(args); i = i + 2 {
var (
val string
raw bool
)
switch st := args[i+1].(type) {
case string:
val = st
case int:
val = strconv.FormatInt(int64(st), 10)
case int64:
val = strconv.FormatInt(int64(st), 10)
case int32:
val = strconv.FormatInt(int64(st), 10)
case int16:
val = strconv.FormatInt(int64(st), 10)
case int8:
val = strconv.FormatInt(int64(st), 10)
case uint:
val = strconv.FormatUint(uint64(st), 10)
case uint64:
val = strconv.FormatUint(uint64(st), 10)
case uint32:
val = strconv.FormatUint(uint64(st), 10)
case uint16:
val = strconv.FormatUint(uint64(st), 10)
case uint8:
val = strconv.FormatUint(uint64(st), 10)
case CapturedStacktrace:
stacktrace = st
continue FOR
case Format:
val = fmt.Sprintf(st[0].(string), st[1:]...)
default:
v := reflect.ValueOf(st)
if v.Kind() == reflect.Slice {
val = z.renderSlice(v)
raw = true
} else {
val = fmt.Sprintf("%v", st)
}
}
z.w.WriteByte(' ')
z.w.WriteString(args[i].(string))
z.w.WriteByte('=')
if !raw && strings.ContainsAny(val, " \t\n\r") {
z.w.WriteByte('"')
z.w.WriteString(val)
z.w.WriteByte('"')
} else {
z.w.WriteString(val)
}
}
}
z.w.WriteString("\n")
if stacktrace != "" {
z.w.WriteString(string(stacktrace))
}
}
func (z *intLogger) renderSlice(v reflect.Value) string {
var buf bytes.Buffer
buf.WriteRune('[')
for i := 0; i < v.Len(); i++ {
if i > 0 {
buf.WriteString(", ")
}
sv := v.Index(i)
var val string
switch sv.Kind() {
case reflect.String:
val = sv.String()
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
val = strconv.FormatInt(sv.Int(), 10)
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
val = strconv.FormatUint(sv.Uint(), 10)
default:
val = fmt.Sprintf("%v", sv.Interface())
}
if strings.ContainsAny(val, " \t\n\r") {
buf.WriteByte('"')
buf.WriteString(val)
buf.WriteByte('"')
} else {
buf.WriteString(val)
}
}
buf.WriteRune(']')
return buf.String()
}
// JSON logging function
func (z *intLogger) logJson(t time.Time, level Level, msg string, args ...interface{}) {
vals := map[string]interface{}{
"@message": msg,
"@timestamp": t.Format("2006-01-02T15:04:05.000000Z07:00"),
}
var levelStr string
switch level {
case Error:
levelStr = "error"
case Warn:
levelStr = "warn"
case Info:
levelStr = "info"
case Debug:
levelStr = "debug"
case Trace:
levelStr = "trace"
default:
levelStr = "all"
}
vals["@level"] = levelStr
if z.name != "" {
vals["@module"] = z.name
}
if z.caller {
if _, file, line, ok := runtime.Caller(3); ok {
vals["@caller"] = fmt.Sprintf("%s:%d", file, line)
}
}
args = append(z.implied, args...)
if args != nil && len(args) > 0 {
if len(args)%2 != 0 {
cs, ok := args[len(args)-1].(CapturedStacktrace)
if ok {
args = args[:len(args)-1]
vals["stacktrace"] = cs
} else {
args = append(args, "<unknown>")
}
}
for i := 0; i < len(args); i = i + 2 {
if _, ok := args[i].(string); !ok {
// As this is the logging function not much we can do here
// without injecting into logs...
continue
}
val := args[i+1]
switch sv := val.(type) {
case error:
// Check if val is of type error. If error type doesn't
// implement json.Marshaler or encoding.TextMarshaler
// then set val to err.Error() so that it gets marshaled
switch sv.(type) {
case json.Marshaler, encoding.TextMarshaler:
default:
val = sv.Error()
}
case Format:
val = fmt.Sprintf(sv[0].(string), sv[1:]...)
}
vals[args[i].(string)] = val
}
}
err := json.NewEncoder(z.w).Encode(vals)
if err != nil {
panic(err)
}
}
// Emit the message and args at DEBUG level
func (z *intLogger) Debug(msg string, args ...interface{}) {
z.Log(Debug, msg, args...)
}
// Emit the message and args at TRACE level
func (z *intLogger) Trace(msg string, args ...interface{}) {
z.Log(Trace, msg, args...)
}
// Emit the message and args at INFO level
func (z *intLogger) Info(msg string, args ...interface{}) {
z.Log(Info, msg, args...)
}
// Emit the message and args at WARN level
func (z *intLogger) Warn(msg string, args ...interface{}) {
z.Log(Warn, msg, args...)
}
// Emit the message and args at ERROR level
func (z *intLogger) Error(msg string, args ...interface{}) {
z.Log(Error, msg, args...)
}
// Indicate that the logger would emit TRACE level logs
func (z *intLogger) IsTrace() bool {
return Level(atomic.LoadInt32(z.level)) == Trace
}
// Indicate that the logger would emit DEBUG level logs
func (z *intLogger) IsDebug() bool {
return Level(atomic.LoadInt32(z.level)) <= Debug
}
// Indicate that the logger would emit INFO level logs
func (z *intLogger) IsInfo() bool {
return Level(atomic.LoadInt32(z.level)) <= Info
}
// Indicate that the logger would emit WARN level logs
func (z *intLogger) IsWarn() bool {
return Level(atomic.LoadInt32(z.level)) <= Warn
}
// Indicate that the logger would emit ERROR level logs
func (z *intLogger) IsError() bool {
return Level(atomic.LoadInt32(z.level)) <= Error
}
// Return a sub-Logger for which every emitted log message will contain
// the given key/value pairs. This is used to create a context specific
// Logger.
func (z *intLogger) With(args ...interface{}) Logger {
if len(args)%2 != 0 {
panic("With() call requires paired arguments")
}
var nz intLogger = *z
result := make(map[string]interface{}, len(z.implied)+len(args))
keys := make([]string, 0, len(z.implied)+len(args))
// Read existing args, store map and key for consistent sorting
for i := 0; i < len(z.implied); i += 2 {
key := z.implied[i].(string)
keys = append(keys, key)
result[key] = z.implied[i+1]
}
// Read new args, store map and key for consistent sorting
for i := 0; i < len(args); i += 2 {
key := args[i].(string)
_, exists := result[key]
if !exists {
keys = append(keys, key)
}
result[key] = args[i+1]
}
// Sort keys to be consistent
sort.Strings(keys)
nz.implied = make([]interface{}, 0, len(z.implied)+len(args))
for _, k := range keys {
nz.implied = append(nz.implied, k)
nz.implied = append(nz.implied, result[k])
}
return &nz
}
// Create a new sub-Logger that a name decending from the current name.
// This is used to create a subsystem specific Logger.
func (z *intLogger) Named(name string) Logger {
var nz intLogger = *z
if nz.name != "" {
nz.name = nz.name + "." + name
} else {
nz.name = name
}
return &nz
}
// Create a new sub-Logger with an explicit name. This ignores the current
// name. This is used to create a standalone logger that doesn't fall
// within the normal hierarchy.
func (z *intLogger) ResetNamed(name string) Logger {
var nz intLogger = *z
nz.name = name
return &nz
}
// Update the logging level on-the-fly. This will affect all subloggers as
// well.
func (z *intLogger) SetLevel(level Level) {
atomic.StoreInt32(z.level, int32(level))
}
// Create a *log.Logger that will send it's data through this Logger. This
// allows packages that expect to be using the standard library log to actually
// use this logger.
func (z *intLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
if opts == nil {
opts = &StandardLoggerOptions{}
}
return log.New(&stdlogAdapter{z, opts.InferLevels}, "", 0)
}
| xanzy/terraform-provider-cosmic | vendor/github.com/hashicorp/go-hclog/int.go | GO | apache-2.0 | 11,348 |
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package podautoscaler
import (
"fmt"
"math"
"time"
"github.com/golang/glog"
autoscalingv1 "k8s.io/api/autoscaling/v1"
autoscalingv2 "k8s.io/api/autoscaling/v2beta1"
"k8s.io/api/core/v1"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
autoscalinginformers "k8s.io/client-go/informers/autoscaling/v1"
"k8s.io/client-go/kubernetes/scheme"
autoscalingclient "k8s.io/client-go/kubernetes/typed/autoscaling/v1"
v1core "k8s.io/client-go/kubernetes/typed/core/v1"
autoscalinglisters "k8s.io/client-go/listers/autoscaling/v1"
scaleclient "k8s.io/client-go/scale"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/controller"
)
var (
scaleUpLimitFactor = 2.0
scaleUpLimitMinimum = 4.0
)
// HorizontalController is responsible for the synchronizing HPA objects stored
// in the system with the actual deployments/replication controllers they
// control.
type HorizontalController struct {
scaleNamespacer scaleclient.ScalesGetter
hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter
mapper apimeta.RESTMapper
replicaCalc *ReplicaCalculator
eventRecorder record.EventRecorder
upscaleForbiddenWindow time.Duration
downscaleForbiddenWindow time.Duration
// hpaLister is able to list/get HPAs from the shared cache from the informer passed in to
// NewHorizontalController.
hpaLister autoscalinglisters.HorizontalPodAutoscalerLister
hpaListerSynced cache.InformerSynced
// Controllers that need to be synced
queue workqueue.RateLimitingInterface
}
// NewHorizontalController creates a new HorizontalController.
func NewHorizontalController(
evtNamespacer v1core.EventsGetter,
scaleNamespacer scaleclient.ScalesGetter,
hpaNamespacer autoscalingclient.HorizontalPodAutoscalersGetter,
mapper apimeta.RESTMapper,
replicaCalc *ReplicaCalculator,
hpaInformer autoscalinginformers.HorizontalPodAutoscalerInformer,
resyncPeriod time.Duration,
upscaleForbiddenWindow time.Duration,
downscaleForbiddenWindow time.Duration,
) *HorizontalController {
broadcaster := record.NewBroadcaster()
broadcaster.StartLogging(glog.Infof)
broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: evtNamespacer.Events("")})
recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "horizontal-pod-autoscaler"})
hpaController := &HorizontalController{
replicaCalc: replicaCalc,
eventRecorder: recorder,
scaleNamespacer: scaleNamespacer,
hpaNamespacer: hpaNamespacer,
upscaleForbiddenWindow: upscaleForbiddenWindow,
downscaleForbiddenWindow: downscaleForbiddenWindow,
queue: workqueue.NewNamedRateLimitingQueue(NewDefaultHPARateLimiter(resyncPeriod), "horizontalpodautoscaler"),
mapper: mapper,
}
hpaInformer.Informer().AddEventHandlerWithResyncPeriod(
cache.ResourceEventHandlerFuncs{
AddFunc: hpaController.enqueueHPA,
UpdateFunc: hpaController.updateHPA,
DeleteFunc: hpaController.deleteHPA,
},
resyncPeriod,
)
hpaController.hpaLister = hpaInformer.Lister()
hpaController.hpaListerSynced = hpaInformer.Informer().HasSynced
return hpaController
}
// Run begins watching and syncing.
func (a *HorizontalController) Run(stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer a.queue.ShutDown()
glog.Infof("Starting HPA controller")
defer glog.Infof("Shutting down HPA controller")
if !controller.WaitForCacheSync("HPA", stopCh, a.hpaListerSynced) {
return
}
// start a single worker (we may wish to start more in the future)
go wait.Until(a.worker, time.Second, stopCh)
<-stopCh
}
// obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item.
func (a *HorizontalController) updateHPA(old, cur interface{}) {
a.enqueueHPA(cur)
}
// obj could be an *v1.HorizontalPodAutoscaler, or a DeletionFinalStateUnknown marker item.
func (a *HorizontalController) enqueueHPA(obj interface{}) {
key, err := controller.KeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
// always add rate-limitted so we don't fetch metrics more that once per resync interval
a.queue.AddRateLimited(key)
}
func (a *HorizontalController) deleteHPA(obj interface{}) {
key, err := controller.KeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
// TODO: could we leak if we fail to get the key?
a.queue.Forget(key)
}
func (a *HorizontalController) worker() {
for a.processNextWorkItem() {
}
glog.Infof("horizontal pod autoscaler controller worker shutting down")
}
func (a *HorizontalController) processNextWorkItem() bool {
key, quit := a.queue.Get()
if quit {
return false
}
defer a.queue.Done(key)
err := a.reconcileKey(key.(string))
if err == nil {
// don't "forget" here because we want to only process a given HPA once per resync interval
return true
}
a.queue.AddRateLimited(key)
utilruntime.HandleError(err)
return true
}
// Computes the desired number of replicas for the metric specifications listed in the HPA, returning the maximum
// of the computed replica counts, a description of the associated metric, and the statuses of all metrics
// computed.
func (a *HorizontalController) computeReplicasForMetrics(hpa *autoscalingv2.HorizontalPodAutoscaler, scale *autoscalingv1.Scale,
metricSpecs []autoscalingv2.MetricSpec) (replicas int32, metric string, statuses []autoscalingv2.MetricStatus, timestamp time.Time, err error) {
currentReplicas := scale.Status.Replicas
statuses = make([]autoscalingv2.MetricStatus, len(metricSpecs))
for i, metricSpec := range metricSpecs {
if scale.Status.Selector == "" {
errMsg := "selector is required"
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "SelectorRequired", errMsg)
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", "the HPA target's scale is missing a selector")
return 0, "", nil, time.Time{}, fmt.Errorf(errMsg)
}
selector, err := labels.Parse(scale.Status.Selector)
if err != nil {
errMsg := fmt.Sprintf("couldn't convert selector into a corresponding internal selector object: %v", err)
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidSelector", errMsg)
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidSelector", errMsg)
return 0, "", nil, time.Time{}, fmt.Errorf(errMsg)
}
var replicaCountProposal int32
var utilizationProposal int64
var timestampProposal time.Time
var metricNameProposal string
switch metricSpec.Type {
case autoscalingv2.ObjectMetricSourceType:
replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetObjectMetricReplicas(currentReplicas, metricSpec.Object.TargetValue.MilliValue(), metricSpec.Object.MetricName, hpa.Namespace, &metricSpec.Object.Target, selector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetObjectMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetObjectMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get object metric value: %v", err)
}
metricNameProposal = fmt.Sprintf("%s metric %s", metricSpec.Object.Target.Kind, metricSpec.Object.MetricName)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.ObjectMetricSourceType,
Object: &autoscalingv2.ObjectMetricStatus{
Target: metricSpec.Object.Target,
MetricName: metricSpec.Object.MetricName,
CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
},
}
case autoscalingv2.PodsMetricSourceType:
replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetMetricReplicas(currentReplicas, metricSpec.Pods.TargetAverageValue.MilliValue(), metricSpec.Pods.MetricName, hpa.Namespace, selector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetPodsMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetPodsMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get pods metric value: %v", err)
}
metricNameProposal = fmt.Sprintf("pods metric %s", metricSpec.Pods.MetricName)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.PodsMetricSourceType,
Pods: &autoscalingv2.PodsMetricStatus{
MetricName: metricSpec.Pods.MetricName,
CurrentAverageValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
},
}
case autoscalingv2.ResourceMetricSourceType:
if metricSpec.Resource.TargetAverageValue != nil {
var rawProposal int64
replicaCountProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetRawResourceReplicas(currentReplicas, metricSpec.Resource.TargetAverageValue.MilliValue(), metricSpec.Resource.Name, hpa.Namespace, selector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err)
}
metricNameProposal = fmt.Sprintf("%s resource", metricSpec.Resource.Name)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.ResourceMetricSourceType,
Resource: &autoscalingv2.ResourceMetricStatus{
Name: metricSpec.Resource.Name,
CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI),
},
}
} else {
// set a default utilization percentage if none is set
if metricSpec.Resource.TargetAverageUtilization == nil {
errMsg := "invalid resource metric source: neither a utilization target nor a value target was set"
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", errMsg)
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %s", errMsg)
return 0, "", nil, time.Time{}, fmt.Errorf(errMsg)
}
targetUtilization := *metricSpec.Resource.TargetAverageUtilization
var percentageProposal int32
var rawProposal int64
replicaCountProposal, percentageProposal, rawProposal, timestampProposal, err = a.replicaCalc.GetResourceReplicas(currentReplicas, targetUtilization, metricSpec.Resource.Name, hpa.Namespace, selector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetResourceMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetResourceMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s utilization: %v", metricSpec.Resource.Name, err)
}
metricNameProposal = fmt.Sprintf("%s resource utilization (percentage of request)", metricSpec.Resource.Name)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.ResourceMetricSourceType,
Resource: &autoscalingv2.ResourceMetricStatus{
Name: metricSpec.Resource.Name,
CurrentAverageUtilization: &percentageProposal,
CurrentAverageValue: *resource.NewMilliQuantity(rawProposal, resource.DecimalSI),
},
}
}
case autoscalingv2.ExternalMetricSourceType:
if metricSpec.External.TargetAverageValue != nil {
replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalPerPodMetricReplicas(currentReplicas, metricSpec.External.TargetAverageValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get %s external metric: %v", metricSpec.External.MetricName, err)
}
metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.ExternalMetricSourceType,
External: &autoscalingv2.ExternalMetricStatus{
MetricSelector: metricSpec.External.MetricSelector,
MetricName: metricSpec.External.MetricName,
CurrentAverageValue: resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
},
}
} else if metricSpec.External.TargetValue != nil {
replicaCountProposal, utilizationProposal, timestampProposal, err = a.replicaCalc.GetExternalMetricReplicas(currentReplicas, metricSpec.External.TargetValue.MilliValue(), metricSpec.External.MetricName, hpa.Namespace, metricSpec.External.MetricSelector, selector)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", err.Error())
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf("failed to get external metric %s: %v", metricSpec.External.MetricName, err)
}
metricNameProposal = fmt.Sprintf("external metric %s(%+v)", metricSpec.External.MetricName, metricSpec.External.MetricSelector)
statuses[i] = autoscalingv2.MetricStatus{
Type: autoscalingv2.ExternalMetricSourceType,
External: &autoscalingv2.ExternalMetricStatus{
MetricSelector: metricSpec.External.MetricSelector,
MetricName: metricSpec.External.MetricName,
CurrentValue: *resource.NewMilliQuantity(utilizationProposal, resource.DecimalSI),
},
}
} else {
errMsg := "invalid external metric source: neither a value target nor an average value target was set"
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetExternalMetric", errMsg)
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "FailedGetExternalMetric", "the HPA was unable to compute the replica count: %v", err)
return 0, "", nil, time.Time{}, fmt.Errorf(errMsg)
}
default:
errMsg := fmt.Sprintf("unknown metric source type %q", string(metricSpec.Type))
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "InvalidMetricSourceType", errMsg)
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "InvalidMetricSourceType", "the HPA was unable to compute the replica count: %s", errMsg)
return 0, "", nil, time.Time{}, fmt.Errorf(errMsg)
}
if replicas == 0 || replicaCountProposal > replicas {
timestamp = timestampProposal
replicas = replicaCountProposal
metric = metricNameProposal
}
}
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionTrue, "ValidMetricFound", "the HPA was able to successfully calculate a replica count from %s", metric)
return replicas, metric, statuses, timestamp, nil
}
func (a *HorizontalController) reconcileKey(key string) error {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
hpa, err := a.hpaLister.HorizontalPodAutoscalers(namespace).Get(name)
if errors.IsNotFound(err) {
glog.Infof("Horizontal Pod Autoscaler has been deleted %v", key)
return nil
}
return a.reconcileAutoscaler(hpa)
}
func (a *HorizontalController) reconcileAutoscaler(hpav1Shared *autoscalingv1.HorizontalPodAutoscaler) error {
// make a copy so that we never mutate the shared informer cache (conversion can mutate the object)
hpav1 := hpav1Shared.DeepCopy()
// then, convert to autoscaling/v2, which makes our lives easier when calculating metrics
hpaRaw, err := unsafeConvertToVersionVia(hpav1, autoscalingv2.SchemeGroupVersion)
if err != nil {
a.eventRecorder.Event(hpav1, v1.EventTypeWarning, "FailedConvertHPA", err.Error())
return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err)
}
hpa := hpaRaw.(*autoscalingv2.HorizontalPodAutoscaler)
hpaStatusOriginal := hpa.Status.DeepCopy()
reference := fmt.Sprintf("%s/%s/%s", hpa.Spec.ScaleTargetRef.Kind, hpa.Namespace, hpa.Spec.ScaleTargetRef.Name)
targetGV, err := schema.ParseGroupVersion(hpa.Spec.ScaleTargetRef.APIVersion)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error())
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err)
a.updateStatusIfNeeded(hpaStatusOriginal, hpa)
return fmt.Errorf("invalid API version in scale target reference: %v", err)
}
targetGK := schema.GroupKind{
Group: targetGV.Group,
Kind: hpa.Spec.ScaleTargetRef.Kind,
}
mappings, err := a.mapper.RESTMappings(targetGK)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error())
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err)
a.updateStatusIfNeeded(hpaStatusOriginal, hpa)
return fmt.Errorf("unable to determine resource for scale target reference: %v", err)
}
scale, targetGR, err := a.scaleForResourceMappings(hpa.Namespace, hpa.Spec.ScaleTargetRef.Name, mappings)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedGetScale", err.Error())
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedGetScale", "the HPA controller was unable to get the target's current scale: %v", err)
a.updateStatusIfNeeded(hpaStatusOriginal, hpa)
return fmt.Errorf("failed to query scale subresource for %s: %v", reference, err)
}
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededGetScale", "the HPA controller was able to get the target's current scale")
currentReplicas := scale.Status.Replicas
var metricStatuses []autoscalingv2.MetricStatus
metricDesiredReplicas := int32(0)
metricName := ""
metricTimestamp := time.Time{}
desiredReplicas := int32(0)
rescaleReason := ""
timestamp := time.Now()
rescale := true
if scale.Spec.Replicas == 0 {
// Autoscaling is disabled for this resource
desiredReplicas = 0
rescale = false
setCondition(hpa, autoscalingv2.ScalingActive, v1.ConditionFalse, "ScalingDisabled", "scaling is disabled since the replica count of the target is zero")
} else if currentReplicas > hpa.Spec.MaxReplicas {
rescaleReason = "Current number of replicas above Spec.MaxReplicas"
desiredReplicas = hpa.Spec.MaxReplicas
} else if hpa.Spec.MinReplicas != nil && currentReplicas < *hpa.Spec.MinReplicas {
rescaleReason = "Current number of replicas below Spec.MinReplicas"
desiredReplicas = *hpa.Spec.MinReplicas
} else if currentReplicas == 0 {
rescaleReason = "Current number of replicas must be greater than 0"
desiredReplicas = 1
} else {
metricDesiredReplicas, metricName, metricStatuses, metricTimestamp, err = a.computeReplicasForMetrics(hpa, scale, hpa.Spec.Metrics)
if err != nil {
a.setCurrentReplicasInStatus(hpa, currentReplicas)
if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil {
utilruntime.HandleError(err)
}
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedComputeMetricsReplicas", err.Error())
return fmt.Errorf("failed to compute desired number of replicas based on listed metrics for %s: %v", reference, err)
}
glog.V(4).Infof("proposing %v desired replicas (based on %s from %s) for %s", metricDesiredReplicas, metricName, timestamp, reference)
rescaleMetric := ""
if metricDesiredReplicas > desiredReplicas {
desiredReplicas = metricDesiredReplicas
timestamp = metricTimestamp
rescaleMetric = metricName
}
if desiredReplicas > currentReplicas {
rescaleReason = fmt.Sprintf("%s above target", rescaleMetric)
}
if desiredReplicas < currentReplicas {
rescaleReason = "All metrics below target"
}
desiredReplicas = a.normalizeDesiredReplicas(hpa, currentReplicas, desiredReplicas)
rescale = a.shouldScale(hpa, currentReplicas, desiredReplicas, timestamp)
backoffDown := false
backoffUp := false
if hpa.Status.LastScaleTime != nil {
if !hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) {
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffDownscale", "the time since the previous scale is still within the downscale forbidden window")
backoffDown = true
}
if !hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) {
backoffUp = true
if backoffDown {
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffBoth", "the time since the previous scale is still within both the downscale and upscale forbidden windows")
} else {
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "BackoffUpscale", "the time since the previous scale is still within the upscale forbidden window")
}
}
}
if !backoffDown && !backoffUp {
// mark that we're not backing off
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "ReadyForNewScale", "the last scale time was sufficiently old as to warrant a new scale")
}
}
if rescale {
scale.Spec.Replicas = desiredReplicas
_, err = a.scaleNamespacer.Scales(hpa.Namespace).Update(targetGR, scale)
if err != nil {
a.eventRecorder.Eventf(hpa, v1.EventTypeWarning, "FailedRescale", "New size: %d; reason: %s; error: %v", desiredReplicas, rescaleReason, err.Error())
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionFalse, "FailedUpdateScale", "the HPA controller was unable to update the target scale: %v", err)
a.setCurrentReplicasInStatus(hpa, currentReplicas)
if err := a.updateStatusIfNeeded(hpaStatusOriginal, hpa); err != nil {
utilruntime.HandleError(err)
}
return fmt.Errorf("failed to rescale %s: %v", reference, err)
}
setCondition(hpa, autoscalingv2.AbleToScale, v1.ConditionTrue, "SucceededRescale", "the HPA controller was able to update the target scale to %d", desiredReplicas)
a.eventRecorder.Eventf(hpa, v1.EventTypeNormal, "SuccessfulRescale", "New size: %d; reason: %s", desiredReplicas, rescaleReason)
glog.Infof("Successful rescale of %s, old size: %d, new size: %d, reason: %s",
hpa.Name, currentReplicas, desiredReplicas, rescaleReason)
} else {
glog.V(4).Infof("decided not to scale %s to %v (last scale time was %s)", reference, desiredReplicas, hpa.Status.LastScaleTime)
desiredReplicas = currentReplicas
}
a.setStatus(hpa, currentReplicas, desiredReplicas, metricStatuses, rescale)
return a.updateStatusIfNeeded(hpaStatusOriginal, hpa)
}
// normalizeDesiredReplicas takes the metrics desired replicas value and normalizes it based on the appropriate conditions (i.e. < maxReplicas, >
// minReplicas, etc...)
func (a *HorizontalController) normalizeDesiredReplicas(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32, prenormalizedDesiredReplicas int32) int32 {
var minReplicas int32
if hpa.Spec.MinReplicas != nil {
minReplicas = *hpa.Spec.MinReplicas
} else {
minReplicas = 0
}
desiredReplicas, condition, reason := convertDesiredReplicasWithRules(currentReplicas, prenormalizedDesiredReplicas, minReplicas, hpa.Spec.MaxReplicas)
if desiredReplicas == prenormalizedDesiredReplicas {
setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionFalse, condition, reason)
} else {
setCondition(hpa, autoscalingv2.ScalingLimited, v1.ConditionTrue, condition, reason)
}
return desiredReplicas
}
// convertDesiredReplicas performs the actual normalization, without depending on `HorizontalController` or `HorizontalPodAutoscaler`
func convertDesiredReplicasWithRules(currentReplicas, desiredReplicas, hpaMinReplicas, hpaMaxReplicas int32) (int32, string, string) {
var minimumAllowedReplicas int32
var maximumAllowedReplicas int32
var possibleLimitingCondition string
var possibleLimitingReason string
if hpaMinReplicas == 0 {
minimumAllowedReplicas = 1
possibleLimitingReason = "the desired replica count is zero"
} else {
minimumAllowedReplicas = hpaMinReplicas
possibleLimitingReason = "the desired replica count is less than the minimum replica count"
}
// Do not upscale too much to prevent incorrect rapid increase of the number of master replicas caused by
// bogus CPU usage report from heapster/kubelet (like in issue #32304).
scaleUpLimit := calculateScaleUpLimit(currentReplicas)
if hpaMaxReplicas > scaleUpLimit {
maximumAllowedReplicas = scaleUpLimit
possibleLimitingCondition = "ScaleUpLimit"
possibleLimitingReason = "the desired replica count is increasing faster than the maximum scale rate"
} else {
maximumAllowedReplicas = hpaMaxReplicas
possibleLimitingCondition = "TooManyReplicas"
possibleLimitingReason = "the desired replica count is more than the maximum replica count"
}
if desiredReplicas < minimumAllowedReplicas {
possibleLimitingCondition = "TooFewReplicas"
return minimumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason
} else if desiredReplicas > maximumAllowedReplicas {
return maximumAllowedReplicas, possibleLimitingCondition, possibleLimitingReason
}
return desiredReplicas, "DesiredWithinRange", "the desired count is within the acceptable range"
}
func calculateScaleUpLimit(currentReplicas int32) int32 {
return int32(math.Max(scaleUpLimitFactor*float64(currentReplicas), scaleUpLimitMinimum))
}
func (a *HorizontalController) shouldScale(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, timestamp time.Time) bool {
if desiredReplicas == currentReplicas {
return false
}
if hpa.Status.LastScaleTime == nil {
return true
}
// Going down only if the usageRatio dropped significantly below the target
// and there was no rescaling in the last downscaleForbiddenWindow.
if desiredReplicas < currentReplicas && hpa.Status.LastScaleTime.Add(a.downscaleForbiddenWindow).Before(timestamp) {
return true
}
// Going up only if the usage ratio increased significantly above the target
// and there was no rescaling in the last upscaleForbiddenWindow.
if desiredReplicas > currentReplicas && hpa.Status.LastScaleTime.Add(a.upscaleForbiddenWindow).Before(timestamp) {
return true
}
return false
}
// scaleForResourceMappings attempts to fetch the scale for the
// resource with the given name and namespace, trying each RESTMapping
// in turn until a working one is found. If none work, the first error
// is returned. It returns both the scale, as well as the group-resource from
// the working mapping.
func (a *HorizontalController) scaleForResourceMappings(namespace, name string, mappings []*apimeta.RESTMapping) (*autoscalingv1.Scale, schema.GroupResource, error) {
var firstErr error
for i, mapping := range mappings {
targetGR := mapping.Resource.GroupResource()
scale, err := a.scaleNamespacer.Scales(namespace).Get(targetGR, name)
if err == nil {
return scale, targetGR, nil
}
// if this is the first error, remember it,
// then go on and try other mappings until we find a good one
if i == 0 {
firstErr = err
}
}
// make sure we handle an empty set of mappings
if firstErr == nil {
firstErr = fmt.Errorf("unrecognized resource")
}
return nil, schema.GroupResource{}, firstErr
}
// setCurrentReplicasInStatus sets the current replica count in the status of the HPA.
func (a *HorizontalController) setCurrentReplicasInStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas int32) {
a.setStatus(hpa, currentReplicas, hpa.Status.DesiredReplicas, hpa.Status.CurrentMetrics, false)
}
// setStatus recreates the status of the given HPA, updating the current and
// desired replicas, as well as the metric statuses
func (a *HorizontalController) setStatus(hpa *autoscalingv2.HorizontalPodAutoscaler, currentReplicas, desiredReplicas int32, metricStatuses []autoscalingv2.MetricStatus, rescale bool) {
hpa.Status = autoscalingv2.HorizontalPodAutoscalerStatus{
CurrentReplicas: currentReplicas,
DesiredReplicas: desiredReplicas,
LastScaleTime: hpa.Status.LastScaleTime,
CurrentMetrics: metricStatuses,
Conditions: hpa.Status.Conditions,
}
if rescale {
now := metav1.NewTime(time.Now())
hpa.Status.LastScaleTime = &now
}
}
// updateStatusIfNeeded calls updateStatus only if the status of the new HPA is not the same as the old status
func (a *HorizontalController) updateStatusIfNeeded(oldStatus *autoscalingv2.HorizontalPodAutoscalerStatus, newHPA *autoscalingv2.HorizontalPodAutoscaler) error {
// skip a write if we wouldn't need to update
if apiequality.Semantic.DeepEqual(oldStatus, &newHPA.Status) {
return nil
}
return a.updateStatus(newHPA)
}
// updateStatus actually does the update request for the status of the given HPA
func (a *HorizontalController) updateStatus(hpa *autoscalingv2.HorizontalPodAutoscaler) error {
// convert back to autoscalingv1
hpaRaw, err := unsafeConvertToVersionVia(hpa, autoscalingv1.SchemeGroupVersion)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedConvertHPA", err.Error())
return fmt.Errorf("failed to convert the given HPA to %s: %v", autoscalingv2.SchemeGroupVersion.String(), err)
}
hpav1 := hpaRaw.(*autoscalingv1.HorizontalPodAutoscaler)
_, err = a.hpaNamespacer.HorizontalPodAutoscalers(hpav1.Namespace).UpdateStatus(hpav1)
if err != nil {
a.eventRecorder.Event(hpa, v1.EventTypeWarning, "FailedUpdateStatus", err.Error())
return fmt.Errorf("failed to update status for %s: %v", hpa.Name, err)
}
glog.V(2).Infof("Successfully updated status for %s", hpa.Name)
return nil
}
// unsafeConvertToVersionVia is like Scheme.UnsafeConvertToVersion, but it does so via an internal version first.
// We use it since working with v2alpha1 is convenient here, but we want to use the v1 client (and
// can't just use the internal version). Note that conversion mutates the object, so you need to deepcopy
// *before* you call this if the input object came out of a shared cache.
func unsafeConvertToVersionVia(obj runtime.Object, externalVersion schema.GroupVersion) (runtime.Object, error) {
objInt, err := legacyscheme.Scheme.UnsafeConvertToVersion(obj, schema.GroupVersion{Group: externalVersion.Group, Version: runtime.APIVersionInternal})
if err != nil {
return nil, fmt.Errorf("failed to convert the given object to the internal version: %v", err)
}
objExt, err := legacyscheme.Scheme.UnsafeConvertToVersion(objInt, externalVersion)
if err != nil {
return nil, fmt.Errorf("failed to convert the given object back to the external version: %v", err)
}
return objExt, err
}
// setCondition sets the specific condition type on the given HPA to the specified value with the given reason
// and message. The message and args are treated like a format string. The condition will be added if it is
// not present.
func setCondition(hpa *autoscalingv2.HorizontalPodAutoscaler, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) {
hpa.Status.Conditions = setConditionInList(hpa.Status.Conditions, conditionType, status, reason, message, args...)
}
// setConditionInList sets the specific condition type on the given HPA to the specified value with the given
// reason and message. The message and args are treated like a format string. The condition will be added if
// it is not present. The new list will be returned.
func setConditionInList(inputList []autoscalingv2.HorizontalPodAutoscalerCondition, conditionType autoscalingv2.HorizontalPodAutoscalerConditionType, status v1.ConditionStatus, reason, message string, args ...interface{}) []autoscalingv2.HorizontalPodAutoscalerCondition {
resList := inputList
var existingCond *autoscalingv2.HorizontalPodAutoscalerCondition
for i, condition := range resList {
if condition.Type == conditionType {
// can't take a pointer to an iteration variable
existingCond = &resList[i]
break
}
}
if existingCond == nil {
resList = append(resList, autoscalingv2.HorizontalPodAutoscalerCondition{
Type: conditionType,
})
existingCond = &resList[len(resList)-1]
}
if existingCond.Status != status {
existingCond.LastTransitionTime = metav1.Now()
}
existingCond.Status = status
existingCond.Reason = reason
existingCond.Message = fmt.Sprintf(message, args...)
return resList
}
| victorgp/kubernetes | pkg/controller/podautoscaler/horizontal.go | GO | apache-2.0 | 33,818 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/global_error/global_error_service.h"
#include <algorithm>
#include "base/stl_util.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_bubble_view_base.h"
#include "content/public/browser/notification_service.h"
GlobalErrorService::GlobalErrorService(Profile* profile) : profile_(profile) {
}
GlobalErrorService::~GlobalErrorService() {
STLDeleteElements(&errors_);
}
void GlobalErrorService::AddGlobalError(GlobalError* error) {
errors_.push_back(error);
NotifyErrorsChanged(error);
}
void GlobalErrorService::RemoveGlobalError(GlobalError* error) {
errors_.erase(std::find(errors_.begin(), errors_.end(), error));
GlobalErrorBubbleViewBase* bubble = error->GetBubbleView();
if (bubble)
bubble->CloseBubbleView();
NotifyErrorsChanged(error);
}
GlobalError* GlobalErrorService::GetGlobalErrorByMenuItemCommandID(
int command_id) const {
for (GlobalErrorList::const_iterator
it = errors_.begin(); it != errors_.end(); ++it) {
GlobalError* error = *it;
if (error->HasMenuItem() && command_id == error->MenuItemCommandID())
return error;
}
return NULL;
}
GlobalError*
GlobalErrorService::GetHighestSeverityGlobalErrorWithWrenchMenuItem() const {
GlobalError::Severity highest_severity = GlobalError::SEVERITY_LOW;
GlobalError* highest_severity_error = NULL;
for (GlobalErrorList::const_iterator
it = errors_.begin(); it != errors_.end(); ++it) {
GlobalError* error = *it;
if (error->HasMenuItem()) {
if (!highest_severity_error || error->GetSeverity() > highest_severity) {
highest_severity = error->GetSeverity();
highest_severity_error = error;
}
}
}
return highest_severity_error;
}
GlobalError* GlobalErrorService::GetFirstGlobalErrorWithBubbleView() const {
for (GlobalErrorList::const_iterator
it = errors_.begin(); it != errors_.end(); ++it) {
GlobalError* error = *it;
if (error->HasBubbleView() && !error->HasShownBubbleView())
return error;
}
return NULL;
}
void GlobalErrorService::NotifyErrorsChanged(GlobalError* error) {
// GlobalErrorService is bound only to original profile so we need to send
// notifications to both it and its off-the-record profile to update
// incognito windows as well.
std::vector<Profile*> profiles_to_notify;
if (profile_ != NULL) {
profiles_to_notify.push_back(profile_);
if (profile_->IsOffTheRecord())
profiles_to_notify.push_back(profile_->GetOriginalProfile());
else if (profile_->HasOffTheRecordProfile())
profiles_to_notify.push_back(profile_->GetOffTheRecordProfile());
for (size_t i = 0; i < profiles_to_notify.size(); ++i) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_GLOBAL_ERRORS_CHANGED,
content::Source<Profile>(profiles_to_notify[i]),
content::Details<GlobalError>(error));
}
}
}
| aospx-kitkat/platform_external_chromium_org | chrome/browser/ui/global_error/global_error_service.cc | C++ | bsd-3-clause | 3,238 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "google_apis/gaia/gaia_oauth_client.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "google_apis/gaia/gaia_urls.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_fetcher_delegate.h"
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"
namespace {
const char kAccessTokenValue[] = "access_token";
const char kRefreshTokenValue[] = "refresh_token";
const char kExpiresInValue[] = "expires_in";
}
namespace gaia {
// Use a non-zero number, so unit tests can differentiate the URLFetcher used by
// this class from other fetchers (most other code just hardcodes the ID to 0).
const int GaiaOAuthClient::kUrlFetcherId = 17109006;
class GaiaOAuthClient::Core
: public base::RefCountedThreadSafe<GaiaOAuthClient::Core>,
public net::URLFetcherDelegate {
public:
Core(net::URLRequestContextGetter* request_context_getter)
: num_retries_(0),
request_context_getter_(request_context_getter),
delegate_(NULL),
request_type_(NO_PENDING_REQUEST) {
}
void GetTokensFromAuthCode(const OAuthClientInfo& oauth_client_info,
const std::string& auth_code,
int max_retries,
GaiaOAuthClient::Delegate* delegate);
void RefreshToken(const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
const std::vector<std::string>& scopes,
int max_retries,
GaiaOAuthClient::Delegate* delegate);
void GetUserEmail(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate);
void GetUserId(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate);
void GetTokenInfo(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate);
// net::URLFetcherDelegate implementation.
virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
private:
friend class base::RefCountedThreadSafe<Core>;
enum RequestType {
NO_PENDING_REQUEST,
TOKENS_FROM_AUTH_CODE,
REFRESH_TOKEN,
TOKEN_INFO,
USER_EMAIL,
USER_ID,
};
virtual ~Core() {}
void GetUserInfo(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate);
void MakeGaiaRequest(const GURL& url,
const std::string& post_body,
int max_retries,
GaiaOAuthClient::Delegate* delegate);
void HandleResponse(const net::URLFetcher* source,
bool* should_retry_request);
int num_retries_;
scoped_refptr<net::URLRequestContextGetter> request_context_getter_;
GaiaOAuthClient::Delegate* delegate_;
scoped_ptr<net::URLFetcher> request_;
RequestType request_type_;
};
void GaiaOAuthClient::Core::GetTokensFromAuthCode(
const OAuthClientInfo& oauth_client_info,
const std::string& auth_code,
int max_retries,
GaiaOAuthClient::Delegate* delegate) {
DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
request_type_ = TOKENS_FROM_AUTH_CODE;
std::string post_body =
"code=" + net::EscapeUrlEncodedData(auth_code, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&redirect_uri=" +
net::EscapeUrlEncodedData(oauth_client_info.redirect_uri, true) +
"&grant_type=authorization_code";
MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
post_body, max_retries, delegate);
}
void GaiaOAuthClient::Core::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
const std::vector<std::string>& scopes,
int max_retries,
GaiaOAuthClient::Delegate* delegate) {
DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
request_type_ = REFRESH_TOKEN;
std::string post_body =
"refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) +
"&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id,
true) +
"&client_secret=" +
net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) +
"&grant_type=refresh_token";
if (!scopes.empty()) {
std::string scopes_string = JoinString(scopes, ' ');
post_body += "&scope=" + net::EscapeUrlEncodedData(scopes_string, true);
}
MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_url()),
post_body, max_retries, delegate);
}
void GaiaOAuthClient::Core::GetUserEmail(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate) {
DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
DCHECK(!request_.get());
request_type_ = USER_EMAIL;
GetUserInfo(oauth_access_token, max_retries, delegate);
}
void GaiaOAuthClient::Core::GetUserId(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate) {
DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
DCHECK(!request_.get());
request_type_ = USER_ID;
GetUserInfo(oauth_access_token, max_retries, delegate);
}
void GaiaOAuthClient::Core::GetUserInfo(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate) {
delegate_ = delegate;
num_retries_ = 0;
request_.reset(net::URLFetcher::Create(
kUrlFetcherId, GURL(GaiaUrls::GetInstance()->oauth_user_info_url()),
net::URLFetcher::GET, this));
request_->SetRequestContext(request_context_getter_.get());
request_->AddExtraRequestHeader("Authorization: OAuth " + oauth_access_token);
request_->SetMaxRetriesOn5xx(max_retries);
request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
// Fetchers are sometimes cancelled because a network change was detected,
// especially at startup and after sign-in on ChromeOS. Retrying once should
// be enough in those cases; let the fetcher retry up to 3 times just in case.
// http://crbug.com/163710
request_->SetAutomaticallyRetryOnNetworkChanges(3);
request_->Start();
}
void GaiaOAuthClient::Core::GetTokenInfo(const std::string& oauth_access_token,
int max_retries,
Delegate* delegate) {
DCHECK_EQ(request_type_, NO_PENDING_REQUEST);
DCHECK(!request_.get());
request_type_ = TOKEN_INFO;
std::string post_body =
"access_token=" + net::EscapeUrlEncodedData(oauth_access_token, true);
MakeGaiaRequest(GURL(GaiaUrls::GetInstance()->oauth2_token_info_url()),
post_body,
max_retries,
delegate);
}
void GaiaOAuthClient::Core::MakeGaiaRequest(
const GURL& url,
const std::string& post_body,
int max_retries,
GaiaOAuthClient::Delegate* delegate) {
DCHECK(!request_.get()) << "Tried to fetch two things at once!";
delegate_ = delegate;
num_retries_ = 0;
request_.reset(net::URLFetcher::Create(
kUrlFetcherId, url, net::URLFetcher::POST, this));
request_->SetRequestContext(request_context_getter_.get());
request_->SetUploadData("application/x-www-form-urlencoded", post_body);
request_->SetMaxRetriesOn5xx(max_retries);
request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
// See comment on SetAutomaticallyRetryOnNetworkChanges() above.
request_->SetAutomaticallyRetryOnNetworkChanges(3);
request_->Start();
}
// URLFetcher::Delegate implementation.
void GaiaOAuthClient::Core::OnURLFetchComplete(
const net::URLFetcher* source) {
bool should_retry = false;
HandleResponse(source, &should_retry);
if (should_retry) {
// Explicitly call ReceivedContentWasMalformed() to ensure the current
// request gets counted as a failure for calculation of the back-off
// period. If it was already a failure by status code, this call will
// be ignored.
request_->ReceivedContentWasMalformed();
num_retries_++;
// We must set our request_context_getter_ again because
// URLFetcher::Core::RetryOrCompleteUrlFetch resets it to NULL...
request_->SetRequestContext(request_context_getter_.get());
request_->Start();
}
}
void GaiaOAuthClient::Core::HandleResponse(
const net::URLFetcher* source,
bool* should_retry_request) {
// Move ownership of the request fetcher into a local scoped_ptr which
// will be nuked when we're done handling the request, unless we need
// to retry, in which case ownership will be returned to request_.
scoped_ptr<net::URLFetcher> old_request = request_.Pass();
DCHECK_EQ(source, old_request.get());
// RC_BAD_REQUEST means the arguments are invalid. No point retrying. We are
// done here.
if (source->GetResponseCode() == net::HTTP_BAD_REQUEST) {
delegate_->OnOAuthError();
return;
}
scoped_ptr<base::DictionaryValue> response_dict;
if (source->GetResponseCode() == net::HTTP_OK) {
std::string data;
source->GetResponseAsString(&data);
scoped_ptr<base::Value> message_value(base::JSONReader::Read(data));
if (message_value.get() &&
message_value->IsType(base::Value::TYPE_DICTIONARY)) {
response_dict.reset(
static_cast<base::DictionaryValue*>(message_value.release()));
}
}
if (!response_dict.get()) {
// If we don't have an access token yet and the the error was not
// RC_BAD_REQUEST, we may need to retry.
if ((source->GetMaxRetriesOn5xx() != -1) &&
(num_retries_ >= source->GetMaxRetriesOn5xx())) {
// Retry limit reached. Give up.
delegate_->OnNetworkError(source->GetResponseCode());
} else {
request_ = old_request.Pass();
*should_retry_request = true;
}
return;
}
RequestType type = request_type_;
request_type_ = NO_PENDING_REQUEST;
switch (type) {
case USER_EMAIL: {
std::string email;
response_dict->GetString("email", &email);
delegate_->OnGetUserEmailResponse(email);
break;
}
case USER_ID: {
std::string id;
response_dict->GetString("id", &id);
delegate_->OnGetUserIdResponse(id);
break;
}
case TOKEN_INFO: {
delegate_->OnGetTokenInfoResponse(response_dict.Pass());
break;
}
case TOKENS_FROM_AUTH_CODE:
case REFRESH_TOKEN: {
std::string access_token;
std::string refresh_token;
int expires_in_seconds = 0;
response_dict->GetString(kAccessTokenValue, &access_token);
response_dict->GetString(kRefreshTokenValue, &refresh_token);
response_dict->GetInteger(kExpiresInValue, &expires_in_seconds);
if (access_token.empty()) {
delegate_->OnOAuthError();
return;
}
if (type == REFRESH_TOKEN) {
delegate_->OnRefreshTokenResponse(access_token, expires_in_seconds);
} else {
delegate_->OnGetTokensResponse(refresh_token,
access_token,
expires_in_seconds);
}
break;
}
default:
NOTREACHED();
}
}
GaiaOAuthClient::GaiaOAuthClient(net::URLRequestContextGetter* context_getter) {
core_ = new Core(context_getter);
}
GaiaOAuthClient::~GaiaOAuthClient() {
}
void GaiaOAuthClient::GetTokensFromAuthCode(
const OAuthClientInfo& oauth_client_info,
const std::string& auth_code,
int max_retries,
Delegate* delegate) {
return core_->GetTokensFromAuthCode(oauth_client_info,
auth_code,
max_retries,
delegate);
}
void GaiaOAuthClient::RefreshToken(
const OAuthClientInfo& oauth_client_info,
const std::string& refresh_token,
const std::vector<std::string>& scopes,
int max_retries,
Delegate* delegate) {
return core_->RefreshToken(oauth_client_info,
refresh_token,
scopes,
max_retries,
delegate);
}
void GaiaOAuthClient::GetUserEmail(const std::string& access_token,
int max_retries,
Delegate* delegate) {
return core_->GetUserEmail(access_token, max_retries, delegate);
}
void GaiaOAuthClient::GetUserId(const std::string& access_token,
int max_retries,
Delegate* delegate) {
return core_->GetUserId(access_token, max_retries, delegate);
}
void GaiaOAuthClient::GetTokenInfo(const std::string& access_token,
int max_retries,
Delegate* delegate) {
return core_->GetTokenInfo(access_token, max_retries, delegate);
}
} // namespace gaia
| Gateworks/platform-external-chromium_org | google_apis/gaia/gaia_oauth_client.cc | C++ | bsd-3-clause | 13,657 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/usb/usb_chooser_context_factory.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/profiles/incognito_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/usb/usb_chooser_context.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
UsbChooserContextFactory::UsbChooserContextFactory()
: BrowserContextKeyedServiceFactory(
"UsbChooserContext",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(HostContentSettingsMapFactory::GetInstance());
}
UsbChooserContextFactory::~UsbChooserContextFactory() {}
KeyedService* UsbChooserContextFactory::BuildServiceInstanceFor(
content::BrowserContext* context) const {
return new UsbChooserContext(Profile::FromBrowserContext(context));
}
// static
UsbChooserContextFactory* UsbChooserContextFactory::GetInstance() {
return base::Singleton<UsbChooserContextFactory>::get();
}
// static
UsbChooserContext* UsbChooserContextFactory::GetForProfile(Profile* profile) {
return static_cast<UsbChooserContext*>(
GetInstance()->GetServiceForBrowserContext(profile, true));
}
content::BrowserContext* UsbChooserContextFactory::GetBrowserContextToUse(
content::BrowserContext* context) const {
return chrome::GetBrowserContextOwnInstanceInIncognito(context);
}
| endlessm/chromium-browser | chrome/browser/usb/usb_chooser_context_factory.cc | C++ | bsd-3-clause | 1,559 |
// Code generated by protoc-gen-gogo.
// source: combos/both/one.proto
// DO NOT EDIT!
/*
Package one is a generated protocol buffer package.
It is generated from these files:
combos/both/one.proto
It has these top-level messages:
Subby
SampleOneOf
*/
package one
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import compress_gzip "compress/gzip"
import bytes "bytes"
import io_ioutil "io/ioutil"
import strings "strings"
import reflect "reflect"
import io "io"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type Subby struct {
Sub string `protobuf:"bytes,1,opt,name=sub,proto3" json:"sub,omitempty"`
}
func (m *Subby) Reset() { *m = Subby{} }
func (*Subby) ProtoMessage() {}
func (*Subby) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{0} }
type SampleOneOf struct {
// Types that are valid to be assigned to TestOneof:
// *SampleOneOf_Field1
// *SampleOneOf_Field2
// *SampleOneOf_Field3
// *SampleOneOf_Field4
// *SampleOneOf_Field5
// *SampleOneOf_Field6
// *SampleOneOf_Field7
// *SampleOneOf_Field8
// *SampleOneOf_Field9
// *SampleOneOf_Field10
// *SampleOneOf_Field11
// *SampleOneOf_Field12
// *SampleOneOf_Field13
// *SampleOneOf_Field14
// *SampleOneOf_Field15
// *SampleOneOf_SubMessage
TestOneof isSampleOneOf_TestOneof `protobuf_oneof:"test_oneof"`
}
func (m *SampleOneOf) Reset() { *m = SampleOneOf{} }
func (*SampleOneOf) ProtoMessage() {}
func (*SampleOneOf) Descriptor() ([]byte, []int) { return fileDescriptorOne, []int{1} }
type isSampleOneOf_TestOneof interface {
isSampleOneOf_TestOneof()
Equal(interface{}) bool
VerboseEqual(interface{}) error
MarshalTo([]byte) (int, error)
Size() int
}
type SampleOneOf_Field1 struct {
Field1 float64 `protobuf:"fixed64,1,opt,name=Field1,proto3,oneof"`
}
type SampleOneOf_Field2 struct {
Field2 float32 `protobuf:"fixed32,2,opt,name=Field2,proto3,oneof"`
}
type SampleOneOf_Field3 struct {
Field3 int32 `protobuf:"varint,3,opt,name=Field3,proto3,oneof"`
}
type SampleOneOf_Field4 struct {
Field4 int64 `protobuf:"varint,4,opt,name=Field4,proto3,oneof"`
}
type SampleOneOf_Field5 struct {
Field5 uint32 `protobuf:"varint,5,opt,name=Field5,proto3,oneof"`
}
type SampleOneOf_Field6 struct {
Field6 uint64 `protobuf:"varint,6,opt,name=Field6,proto3,oneof"`
}
type SampleOneOf_Field7 struct {
Field7 int32 `protobuf:"zigzag32,7,opt,name=Field7,proto3,oneof"`
}
type SampleOneOf_Field8 struct {
Field8 int64 `protobuf:"zigzag64,8,opt,name=Field8,proto3,oneof"`
}
type SampleOneOf_Field9 struct {
Field9 uint32 `protobuf:"fixed32,9,opt,name=Field9,proto3,oneof"`
}
type SampleOneOf_Field10 struct {
Field10 int32 `protobuf:"fixed32,10,opt,name=Field10,proto3,oneof"`
}
type SampleOneOf_Field11 struct {
Field11 uint64 `protobuf:"fixed64,11,opt,name=Field11,proto3,oneof"`
}
type SampleOneOf_Field12 struct {
Field12 int64 `protobuf:"fixed64,12,opt,name=Field12,proto3,oneof"`
}
type SampleOneOf_Field13 struct {
Field13 bool `protobuf:"varint,13,opt,name=Field13,proto3,oneof"`
}
type SampleOneOf_Field14 struct {
Field14 string `protobuf:"bytes,14,opt,name=Field14,proto3,oneof"`
}
type SampleOneOf_Field15 struct {
Field15 []byte `protobuf:"bytes,15,opt,name=Field15,proto3,oneof"`
}
type SampleOneOf_SubMessage struct {
SubMessage *Subby `protobuf:"bytes,16,opt,name=sub_message,json=subMessage,oneof"`
}
func (*SampleOneOf_Field1) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field2) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field3) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field4) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field5) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field6) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field7) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field8) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field9) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field10) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field11) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field12) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field13) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field14) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_Field15) isSampleOneOf_TestOneof() {}
func (*SampleOneOf_SubMessage) isSampleOneOf_TestOneof() {}
func (m *SampleOneOf) GetTestOneof() isSampleOneOf_TestOneof {
if m != nil {
return m.TestOneof
}
return nil
}
func (m *SampleOneOf) GetField1() float64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field1); ok {
return x.Field1
}
return 0
}
func (m *SampleOneOf) GetField2() float32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field2); ok {
return x.Field2
}
return 0
}
func (m *SampleOneOf) GetField3() int32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field3); ok {
return x.Field3
}
return 0
}
func (m *SampleOneOf) GetField4() int64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field4); ok {
return x.Field4
}
return 0
}
func (m *SampleOneOf) GetField5() uint32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field5); ok {
return x.Field5
}
return 0
}
func (m *SampleOneOf) GetField6() uint64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field6); ok {
return x.Field6
}
return 0
}
func (m *SampleOneOf) GetField7() int32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field7); ok {
return x.Field7
}
return 0
}
func (m *SampleOneOf) GetField8() int64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field8); ok {
return x.Field8
}
return 0
}
func (m *SampleOneOf) GetField9() uint32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field9); ok {
return x.Field9
}
return 0
}
func (m *SampleOneOf) GetField10() int32 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field10); ok {
return x.Field10
}
return 0
}
func (m *SampleOneOf) GetField11() uint64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field11); ok {
return x.Field11
}
return 0
}
func (m *SampleOneOf) GetField12() int64 {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field12); ok {
return x.Field12
}
return 0
}
func (m *SampleOneOf) GetField13() bool {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field13); ok {
return x.Field13
}
return false
}
func (m *SampleOneOf) GetField14() string {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field14); ok {
return x.Field14
}
return ""
}
func (m *SampleOneOf) GetField15() []byte {
if x, ok := m.GetTestOneof().(*SampleOneOf_Field15); ok {
return x.Field15
}
return nil
}
func (m *SampleOneOf) GetSubMessage() *Subby {
if x, ok := m.GetTestOneof().(*SampleOneOf_SubMessage); ok {
return x.SubMessage
}
return nil
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*SampleOneOf) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
return _SampleOneOf_OneofMarshaler, _SampleOneOf_OneofUnmarshaler, _SampleOneOf_OneofSizer, []interface{}{
(*SampleOneOf_Field1)(nil),
(*SampleOneOf_Field2)(nil),
(*SampleOneOf_Field3)(nil),
(*SampleOneOf_Field4)(nil),
(*SampleOneOf_Field5)(nil),
(*SampleOneOf_Field6)(nil),
(*SampleOneOf_Field7)(nil),
(*SampleOneOf_Field8)(nil),
(*SampleOneOf_Field9)(nil),
(*SampleOneOf_Field10)(nil),
(*SampleOneOf_Field11)(nil),
(*SampleOneOf_Field12)(nil),
(*SampleOneOf_Field13)(nil),
(*SampleOneOf_Field14)(nil),
(*SampleOneOf_Field15)(nil),
(*SampleOneOf_SubMessage)(nil),
}
}
func _SampleOneOf_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
m := msg.(*SampleOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *SampleOneOf_Field1:
_ = b.EncodeVarint(1<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(math.Float64bits(x.Field1))
case *SampleOneOf_Field2:
_ = b.EncodeVarint(2<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(math.Float32bits(x.Field2)))
case *SampleOneOf_Field3:
_ = b.EncodeVarint(3<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field3))
case *SampleOneOf_Field4:
_ = b.EncodeVarint(4<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field4))
case *SampleOneOf_Field5:
_ = b.EncodeVarint(5<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field5))
case *SampleOneOf_Field6:
_ = b.EncodeVarint(6<<3 | proto.WireVarint)
_ = b.EncodeVarint(uint64(x.Field6))
case *SampleOneOf_Field7:
_ = b.EncodeVarint(7<<3 | proto.WireVarint)
_ = b.EncodeZigzag32(uint64(x.Field7))
case *SampleOneOf_Field8:
_ = b.EncodeVarint(8<<3 | proto.WireVarint)
_ = b.EncodeZigzag64(uint64(x.Field8))
case *SampleOneOf_Field9:
_ = b.EncodeVarint(9<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field9))
case *SampleOneOf_Field10:
_ = b.EncodeVarint(10<<3 | proto.WireFixed32)
_ = b.EncodeFixed32(uint64(x.Field10))
case *SampleOneOf_Field11:
_ = b.EncodeVarint(11<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field11))
case *SampleOneOf_Field12:
_ = b.EncodeVarint(12<<3 | proto.WireFixed64)
_ = b.EncodeFixed64(uint64(x.Field12))
case *SampleOneOf_Field13:
t := uint64(0)
if x.Field13 {
t = 1
}
_ = b.EncodeVarint(13<<3 | proto.WireVarint)
_ = b.EncodeVarint(t)
case *SampleOneOf_Field14:
_ = b.EncodeVarint(14<<3 | proto.WireBytes)
_ = b.EncodeStringBytes(x.Field14)
case *SampleOneOf_Field15:
_ = b.EncodeVarint(15<<3 | proto.WireBytes)
_ = b.EncodeRawBytes(x.Field15)
case *SampleOneOf_SubMessage:
_ = b.EncodeVarint(16<<3 | proto.WireBytes)
if err := b.EncodeMessage(x.SubMessage); err != nil {
return err
}
case nil:
default:
return fmt.Errorf("SampleOneOf.TestOneof has unexpected type %T", x)
}
return nil
}
func _SampleOneOf_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
m := msg.(*SampleOneOf)
switch tag {
case 1: // test_oneof.Field1
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &SampleOneOf_Field1{math.Float64frombits(x)}
return true, err
case 2: // test_oneof.Field2
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &SampleOneOf_Field2{math.Float32frombits(uint32(x))}
return true, err
case 3: // test_oneof.Field3
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &SampleOneOf_Field3{int32(x)}
return true, err
case 4: // test_oneof.Field4
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &SampleOneOf_Field4{int64(x)}
return true, err
case 5: // test_oneof.Field5
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &SampleOneOf_Field5{uint32(x)}
return true, err
case 6: // test_oneof.Field6
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &SampleOneOf_Field6{x}
return true, err
case 7: // test_oneof.Field7
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag32()
m.TestOneof = &SampleOneOf_Field7{int32(x)}
return true, err
case 8: // test_oneof.Field8
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeZigzag64()
m.TestOneof = &SampleOneOf_Field8{int64(x)}
return true, err
case 9: // test_oneof.Field9
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &SampleOneOf_Field9{uint32(x)}
return true, err
case 10: // test_oneof.Field10
if wire != proto.WireFixed32 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed32()
m.TestOneof = &SampleOneOf_Field10{int32(x)}
return true, err
case 11: // test_oneof.Field11
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &SampleOneOf_Field11{x}
return true, err
case 12: // test_oneof.Field12
if wire != proto.WireFixed64 {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeFixed64()
m.TestOneof = &SampleOneOf_Field12{int64(x)}
return true, err
case 13: // test_oneof.Field13
if wire != proto.WireVarint {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeVarint()
m.TestOneof = &SampleOneOf_Field13{x != 0}
return true, err
case 14: // test_oneof.Field14
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeStringBytes()
m.TestOneof = &SampleOneOf_Field14{x}
return true, err
case 15: // test_oneof.Field15
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
x, err := b.DecodeRawBytes(true)
m.TestOneof = &SampleOneOf_Field15{x}
return true, err
case 16: // test_oneof.sub_message
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(Subby)
err := b.DecodeMessage(msg)
m.TestOneof = &SampleOneOf_SubMessage{msg}
return true, err
default:
return false, nil
}
}
func _SampleOneOf_OneofSizer(msg proto.Message) (n int) {
m := msg.(*SampleOneOf)
// test_oneof
switch x := m.TestOneof.(type) {
case *SampleOneOf_Field1:
n += proto.SizeVarint(1<<3 | proto.WireFixed64)
n += 8
case *SampleOneOf_Field2:
n += proto.SizeVarint(2<<3 | proto.WireFixed32)
n += 4
case *SampleOneOf_Field3:
n += proto.SizeVarint(3<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field3))
case *SampleOneOf_Field4:
n += proto.SizeVarint(4<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field4))
case *SampleOneOf_Field5:
n += proto.SizeVarint(5<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field5))
case *SampleOneOf_Field6:
n += proto.SizeVarint(6<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(x.Field6))
case *SampleOneOf_Field7:
n += proto.SizeVarint(7<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64((uint32(x.Field7) << 1) ^ uint32((int32(x.Field7) >> 31))))
case *SampleOneOf_Field8:
n += proto.SizeVarint(8<<3 | proto.WireVarint)
n += proto.SizeVarint(uint64(uint64(x.Field8<<1) ^ uint64((int64(x.Field8) >> 63))))
case *SampleOneOf_Field9:
n += proto.SizeVarint(9<<3 | proto.WireFixed32)
n += 4
case *SampleOneOf_Field10:
n += proto.SizeVarint(10<<3 | proto.WireFixed32)
n += 4
case *SampleOneOf_Field11:
n += proto.SizeVarint(11<<3 | proto.WireFixed64)
n += 8
case *SampleOneOf_Field12:
n += proto.SizeVarint(12<<3 | proto.WireFixed64)
n += 8
case *SampleOneOf_Field13:
n += proto.SizeVarint(13<<3 | proto.WireVarint)
n += 1
case *SampleOneOf_Field14:
n += proto.SizeVarint(14<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field14)))
n += len(x.Field14)
case *SampleOneOf_Field15:
n += proto.SizeVarint(15<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(len(x.Field15)))
n += len(x.Field15)
case *SampleOneOf_SubMessage:
s := proto.Size(x.SubMessage)
n += proto.SizeVarint(16<<3 | proto.WireBytes)
n += proto.SizeVarint(uint64(s))
n += s
case nil:
default:
panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
}
return n
}
func init() {
proto.RegisterType((*Subby)(nil), "one.Subby")
proto.RegisterType((*SampleOneOf)(nil), "one.SampleOneOf")
}
func (this *Subby) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func (this *SampleOneOf) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return OneDescription()
}
func OneDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{}
var gzipped = []byte{
// 3749 bytes of a gzipped FileDescriptorSet
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x5a, 0x5b, 0x6c, 0xe4, 0xe6,
0x75, 0x16, 0xe7, 0xa6, 0x99, 0x33, 0xa3, 0x11, 0xf5, 0x4b, 0x5e, 0x73, 0xe5, 0x78, 0x56, 0xab,
0xd8, 0xb1, 0x6c, 0xd7, 0x5a, 0x5b, 0x97, 0xbd, 0xcc, 0x36, 0x31, 0x46, 0xd2, 0x58, 0xab, 0x85,
0x6e, 0xe1, 0x48, 0x89, 0x9d, 0x3c, 0x10, 0x1c, 0xce, 0x3f, 0x23, 0xee, 0x72, 0xc8, 0x29, 0xc9,
0x59, 0x5b, 0x7e, 0xda, 0xc0, 0xbd, 0x20, 0x08, 0x7a, 0x4d, 0x81, 0x26, 0x8e, 0xe3, 0xa6, 0x01,
0x5a, 0xa7, 0xe9, 0x2d, 0xe9, 0x25, 0x0d, 0xfa, 0xd4, 0x97, 0xb4, 0x7e, 0x2a, 0x92, 0xb7, 0x3e,
0xe4, 0x21, 0xab, 0x1a, 0x68, 0xda, 0xba, 0xad, 0xdb, 0x18, 0x68, 0x80, 0x7d, 0x29, 0xfe, 0x1b,
0xc9, 0xb9, 0x68, 0x39, 0x0a, 0x90, 0x38, 0x4f, 0x12, 0xcf, 0x39, 0xdf, 0xc7, 0xc3, 0xf3, 0x9f,
0xff, 0x9c, 0xc3, 0x7f, 0x08, 0x9f, 0x59, 0x81, 0xb9, 0x96, 0xe3, 0xb4, 0x2c, 0x7c, 0xa9, 0xe3,
0x3a, 0xbe, 0x53, 0xef, 0x36, 0x2f, 0x35, 0xb0, 0x67, 0xb8, 0x66, 0xc7, 0x77, 0xdc, 0x45, 0x2a,
0x43, 0x93, 0xcc, 0x62, 0x51, 0x58, 0xcc, 0xef, 0xc0, 0xd4, 0x0b, 0xa6, 0x85, 0x37, 0x02, 0xc3,
0x1a, 0xf6, 0xd1, 0x55, 0x48, 0x35, 0x4d, 0x0b, 0x2b, 0xd2, 0x5c, 0x72, 0x21, 0xbf, 0xf4, 0xd8,
0x62, 0x1f, 0x68, 0xb1, 0x17, 0xb1, 0x4f, 0xc4, 0x2a, 0x45, 0xcc, 0xbf, 0x93, 0x82, 0xe9, 0x21,
0x5a, 0x84, 0x20, 0x65, 0xeb, 0x6d, 0xc2, 0x28, 0x2d, 0xe4, 0x54, 0xfa, 0x3f, 0x52, 0x60, 0xbc,
0xa3, 0x1b, 0xb7, 0xf5, 0x16, 0x56, 0x12, 0x54, 0x2c, 0x2e, 0x51, 0x09, 0xa0, 0x81, 0x3b, 0xd8,
0x6e, 0x60, 0xdb, 0x38, 0x56, 0x92, 0x73, 0xc9, 0x85, 0x9c, 0x1a, 0x91, 0xa0, 0xa7, 0x61, 0xaa,
0xd3, 0xad, 0x5b, 0xa6, 0xa1, 0x45, 0xcc, 0x60, 0x2e, 0xb9, 0x90, 0x56, 0x65, 0xa6, 0xd8, 0x08,
0x8d, 0x9f, 0x80, 0xc9, 0x97, 0xb1, 0x7e, 0x3b, 0x6a, 0x9a, 0xa7, 0xa6, 0x45, 0x22, 0x8e, 0x18,
0xae, 0x43, 0xa1, 0x8d, 0x3d, 0x4f, 0x6f, 0x61, 0xcd, 0x3f, 0xee, 0x60, 0x25, 0x45, 0x9f, 0x7e,
0x6e, 0xe0, 0xe9, 0xfb, 0x9f, 0x3c, 0xcf, 0x51, 0x07, 0xc7, 0x1d, 0x8c, 0x2a, 0x90, 0xc3, 0x76,
0xb7, 0xcd, 0x18, 0xd2, 0xa7, 0xc4, 0xaf, 0x6a, 0x77, 0xdb, 0xfd, 0x2c, 0x59, 0x02, 0xe3, 0x14,
0xe3, 0x1e, 0x76, 0xef, 0x98, 0x06, 0x56, 0x32, 0x94, 0xe0, 0x89, 0x01, 0x82, 0x1a, 0xd3, 0xf7,
0x73, 0x08, 0x1c, 0x5a, 0x87, 0x1c, 0x7e, 0xc5, 0xc7, 0xb6, 0x67, 0x3a, 0xb6, 0x32, 0x4e, 0x49,
0x1e, 0x1f, 0xb2, 0x8a, 0xd8, 0x6a, 0xf4, 0x53, 0x84, 0x38, 0x74, 0x19, 0xc6, 0x9d, 0x8e, 0x6f,
0x3a, 0xb6, 0xa7, 0x64, 0xe7, 0xa4, 0x85, 0xfc, 0xd2, 0x87, 0x86, 0x26, 0xc2, 0x1e, 0xb3, 0x51,
0x85, 0x31, 0xda, 0x02, 0xd9, 0x73, 0xba, 0xae, 0x81, 0x35, 0xc3, 0x69, 0x60, 0xcd, 0xb4, 0x9b,
0x8e, 0x92, 0xa3, 0x04, 0x17, 0x06, 0x1f, 0x84, 0x1a, 0xae, 0x3b, 0x0d, 0xbc, 0x65, 0x37, 0x1d,
0xb5, 0xe8, 0xf5, 0x5c, 0xa3, 0x73, 0x90, 0xf1, 0x8e, 0x6d, 0x5f, 0x7f, 0x45, 0x29, 0xd0, 0x0c,
0xe1, 0x57, 0xf3, 0xff, 0x97, 0x86, 0xc9, 0x51, 0x52, 0xec, 0x3a, 0xa4, 0x9b, 0xe4, 0x29, 0x95,
0xc4, 0x59, 0x62, 0xc0, 0x30, 0xbd, 0x41, 0xcc, 0xfc, 0x84, 0x41, 0xac, 0x40, 0xde, 0xc6, 0x9e,
0x8f, 0x1b, 0x2c, 0x23, 0x92, 0x23, 0xe6, 0x14, 0x30, 0xd0, 0x60, 0x4a, 0xa5, 0x7e, 0xa2, 0x94,
0x7a, 0x11, 0x26, 0x03, 0x97, 0x34, 0x57, 0xb7, 0x5b, 0x22, 0x37, 0x2f, 0xc5, 0x79, 0xb2, 0x58,
0x15, 0x38, 0x95, 0xc0, 0xd4, 0x22, 0xee, 0xb9, 0x46, 0x1b, 0x00, 0x8e, 0x8d, 0x9d, 0xa6, 0xd6,
0xc0, 0x86, 0xa5, 0x64, 0x4f, 0x89, 0xd2, 0x1e, 0x31, 0x19, 0x88, 0x92, 0xc3, 0xa4, 0x86, 0x85,
0xae, 0x85, 0xa9, 0x36, 0x7e, 0x4a, 0xa6, 0xec, 0xb0, 0x4d, 0x36, 0x90, 0x6d, 0x87, 0x50, 0x74,
0x31, 0xc9, 0x7b, 0xdc, 0xe0, 0x4f, 0x96, 0xa3, 0x4e, 0x2c, 0xc6, 0x3e, 0x99, 0xca, 0x61, 0xec,
0xc1, 0x26, 0xdc, 0xe8, 0x25, 0xfa, 0x30, 0x04, 0x02, 0x8d, 0xa6, 0x15, 0xd0, 0x2a, 0x54, 0x10,
0xc2, 0x5d, 0xbd, 0x8d, 0x67, 0xaf, 0x42, 0xb1, 0x37, 0x3c, 0x68, 0x06, 0xd2, 0x9e, 0xaf, 0xbb,
0x3e, 0xcd, 0xc2, 0xb4, 0xca, 0x2e, 0x90, 0x0c, 0x49, 0x6c, 0x37, 0x68, 0x95, 0x4b, 0xab, 0xe4,
0xdf, 0xd9, 0x2b, 0x30, 0xd1, 0x73, 0xfb, 0x51, 0x81, 0xf3, 0x5f, 0xc8, 0xc0, 0xcc, 0xb0, 0x9c,
0x1b, 0x9a, 0xfe, 0xe7, 0x20, 0x63, 0x77, 0xdb, 0x75, 0xec, 0x2a, 0x49, 0xca, 0xc0, 0xaf, 0x50,
0x05, 0xd2, 0x96, 0x5e, 0xc7, 0x96, 0x92, 0x9a, 0x93, 0x16, 0x8a, 0x4b, 0x4f, 0x8f, 0x94, 0xd5,
0x8b, 0xdb, 0x04, 0xa2, 0x32, 0x24, 0xfa, 0x18, 0xa4, 0x78, 0x89, 0x23, 0x0c, 0x4f, 0x8d, 0xc6,
0x40, 0x72, 0x51, 0xa5, 0x38, 0xf4, 0x08, 0xe4, 0xc8, 0x5f, 0x16, 0xdb, 0x0c, 0xf5, 0x39, 0x4b,
0x04, 0x24, 0xae, 0x68, 0x16, 0xb2, 0x34, 0xcd, 0x1a, 0x58, 0xb4, 0x86, 0xe0, 0x9a, 0x2c, 0x4c,
0x03, 0x37, 0xf5, 0xae, 0xe5, 0x6b, 0x77, 0x74, 0xab, 0x8b, 0x69, 0xc2, 0xe4, 0xd4, 0x02, 0x17,
0x7e, 0x82, 0xc8, 0xd0, 0x05, 0xc8, 0xb3, 0xac, 0x34, 0xed, 0x06, 0x7e, 0x85, 0x56, 0x9f, 0xb4,
0xca, 0x12, 0x75, 0x8b, 0x48, 0xc8, 0xed, 0x6f, 0x79, 0x8e, 0x2d, 0x96, 0x96, 0xde, 0x82, 0x08,
0xe8, 0xed, 0xaf, 0xf4, 0x17, 0xbe, 0x47, 0x87, 0x3f, 0x5e, 0x7f, 0x2e, 0xce, 0x7f, 0x2b, 0x01,
0x29, 0xba, 0xdf, 0x26, 0x21, 0x7f, 0xf0, 0xd2, 0x7e, 0x55, 0xdb, 0xd8, 0x3b, 0x5c, 0xdb, 0xae,
0xca, 0x12, 0x2a, 0x02, 0x50, 0xc1, 0x0b, 0xdb, 0x7b, 0x95, 0x03, 0x39, 0x11, 0x5c, 0x6f, 0xed,
0x1e, 0x5c, 0x5e, 0x91, 0x93, 0x01, 0xe0, 0x90, 0x09, 0x52, 0x51, 0x83, 0xe5, 0x25, 0x39, 0x8d,
0x64, 0x28, 0x30, 0x82, 0xad, 0x17, 0xab, 0x1b, 0x97, 0x57, 0xe4, 0x4c, 0xaf, 0x64, 0x79, 0x49,
0x1e, 0x47, 0x13, 0x90, 0xa3, 0x92, 0xb5, 0xbd, 0xbd, 0x6d, 0x39, 0x1b, 0x70, 0xd6, 0x0e, 0xd4,
0xad, 0xdd, 0x4d, 0x39, 0x17, 0x70, 0x6e, 0xaa, 0x7b, 0x87, 0xfb, 0x32, 0x04, 0x0c, 0x3b, 0xd5,
0x5a, 0xad, 0xb2, 0x59, 0x95, 0xf3, 0x81, 0xc5, 0xda, 0x4b, 0x07, 0xd5, 0x9a, 0x5c, 0xe8, 0x71,
0x6b, 0x79, 0x49, 0x9e, 0x08, 0x6e, 0x51, 0xdd, 0x3d, 0xdc, 0x91, 0x8b, 0x68, 0x0a, 0x26, 0xd8,
0x2d, 0x84, 0x13, 0x93, 0x7d, 0xa2, 0xcb, 0x2b, 0xb2, 0x1c, 0x3a, 0xc2, 0x58, 0xa6, 0x7a, 0x04,
0x97, 0x57, 0x64, 0x34, 0xbf, 0x0e, 0x69, 0x9a, 0x5d, 0x08, 0x41, 0x71, 0xbb, 0xb2, 0x56, 0xdd,
0xd6, 0xf6, 0xf6, 0x0f, 0xb6, 0xf6, 0x76, 0x2b, 0xdb, 0xb2, 0x14, 0xca, 0xd4, 0xea, 0xc7, 0x0f,
0xb7, 0xd4, 0xea, 0x86, 0x9c, 0x88, 0xca, 0xf6, 0xab, 0x95, 0x83, 0xea, 0x86, 0x9c, 0x9c, 0x37,
0x60, 0x66, 0x58, 0x9d, 0x19, 0xba, 0x33, 0x22, 0x4b, 0x9c, 0x38, 0x65, 0x89, 0x29, 0xd7, 0xc0,
0x12, 0x7f, 0x55, 0x82, 0xe9, 0x21, 0xb5, 0x76, 0xe8, 0x4d, 0x9e, 0x87, 0x34, 0x4b, 0x51, 0xd6,
0x7d, 0x9e, 0x1c, 0x5a, 0xb4, 0x69, 0xc2, 0x0e, 0x74, 0x20, 0x8a, 0x8b, 0x76, 0xe0, 0xe4, 0x29,
0x1d, 0x98, 0x50, 0x0c, 0x38, 0xf9, 0x9a, 0x04, 0xca, 0x69, 0xdc, 0x31, 0x85, 0x22, 0xd1, 0x53,
0x28, 0xae, 0xf7, 0x3b, 0x70, 0xf1, 0xf4, 0x67, 0x18, 0xf0, 0xe2, 0x2d, 0x09, 0xce, 0x0d, 0x1f,
0x54, 0x86, 0xfa, 0xf0, 0x31, 0xc8, 0xb4, 0xb1, 0x7f, 0xe4, 0x88, 0x66, 0xfd, 0x91, 0x21, 0x2d,
0x80, 0xa8, 0xfb, 0x63, 0xc5, 0x51, 0xd1, 0x1e, 0x92, 0x3c, 0x6d, 0xda, 0x60, 0xde, 0x0c, 0x78,
0xfa, 0xd9, 0x04, 0x3c, 0x34, 0x94, 0x7c, 0xa8, 0xa3, 0x8f, 0x02, 0x98, 0x76, 0xa7, 0xeb, 0xb3,
0x86, 0xcc, 0xea, 0x53, 0x8e, 0x4a, 0xe8, 0xde, 0x27, 0xb5, 0xa7, 0xeb, 0x07, 0xfa, 0x24, 0xd5,
0x03, 0x13, 0x51, 0x83, 0xab, 0xa1, 0xa3, 0x29, 0xea, 0x68, 0xe9, 0x94, 0x27, 0x1d, 0xe8, 0x75,
0xcf, 0x82, 0x6c, 0x58, 0x26, 0xb6, 0x7d, 0xcd, 0xf3, 0x5d, 0xac, 0xb7, 0x4d, 0xbb, 0x45, 0x0b,
0x70, 0xb6, 0x9c, 0x6e, 0xea, 0x96, 0x87, 0xd5, 0x49, 0xa6, 0xae, 0x09, 0x2d, 0x41, 0xd0, 0x2e,
0xe3, 0x46, 0x10, 0x99, 0x1e, 0x04, 0x53, 0x07, 0x88, 0xf9, 0xcf, 0x8d, 0x43, 0x3e, 0x32, 0xd6,
0xa1, 0x8b, 0x50, 0xb8, 0xa5, 0xdf, 0xd1, 0x35, 0x31, 0xaa, 0xb3, 0x48, 0xe4, 0x89, 0x6c, 0x9f,
0x8f, 0xeb, 0xcf, 0xc2, 0x0c, 0x35, 0x71, 0xba, 0x3e, 0x76, 0x35, 0xc3, 0xd2, 0x3d, 0x8f, 0x06,
0x2d, 0x4b, 0x4d, 0x11, 0xd1, 0xed, 0x11, 0xd5, 0xba, 0xd0, 0xa0, 0x55, 0x98, 0xa6, 0x88, 0x76,
0xd7, 0xf2, 0xcd, 0x8e, 0x85, 0x35, 0xf2, 0xf2, 0xe0, 0xd1, 0x42, 0x1c, 0x78, 0x36, 0x45, 0x2c,
0x76, 0xb8, 0x01, 0xf1, 0xc8, 0x43, 0x9b, 0xf0, 0x28, 0x85, 0xb5, 0xb0, 0x8d, 0x5d, 0xdd, 0xc7,
0x1a, 0xfe, 0xa5, 0xae, 0x6e, 0x79, 0x9a, 0x6e, 0x37, 0xb4, 0x23, 0xdd, 0x3b, 0x52, 0x66, 0xa2,
0x04, 0xe7, 0x89, 0xed, 0x26, 0x37, 0xad, 0x52, 0xcb, 0x8a, 0xdd, 0xb8, 0xa1, 0x7b, 0x47, 0xa8,
0x0c, 0xe7, 0x28, 0x91, 0xe7, 0xbb, 0xa6, 0xdd, 0xd2, 0x8c, 0x23, 0x6c, 0xdc, 0xd6, 0xba, 0x7e,
0xf3, 0xaa, 0xf2, 0x48, 0x94, 0x81, 0x3a, 0x59, 0xa3, 0x36, 0xeb, 0xc4, 0xe4, 0xd0, 0x6f, 0x5e,
0x45, 0x35, 0x28, 0x90, 0xf5, 0x68, 0x9b, 0xaf, 0x62, 0xad, 0xe9, 0xb8, 0xb4, 0xb9, 0x14, 0x87,
0x6c, 0xee, 0x48, 0x10, 0x17, 0xf7, 0x38, 0x60, 0xc7, 0x69, 0xe0, 0x72, 0xba, 0xb6, 0x5f, 0xad,
0x6e, 0xa8, 0x79, 0xc1, 0xf2, 0x82, 0xe3, 0x92, 0x9c, 0x6a, 0x39, 0x41, 0x8c, 0xf3, 0x2c, 0xa7,
0x5a, 0x8e, 0x88, 0xf0, 0x2a, 0x4c, 0x1b, 0x06, 0x7b, 0x6c, 0xd3, 0xd0, 0xf8, 0x94, 0xef, 0x29,
0x72, 0x4f, 0xbc, 0x0c, 0x63, 0x93, 0x19, 0xf0, 0x34, 0xf7, 0xd0, 0x35, 0x78, 0x28, 0x8c, 0x57,
0x14, 0x38, 0x35, 0xf0, 0x94, 0xfd, 0xd0, 0x55, 0x98, 0xee, 0x1c, 0x0f, 0x02, 0x51, 0xcf, 0x1d,
0x3b, 0xc7, 0xfd, 0xb0, 0xc7, 0xe9, 0x9b, 0x9b, 0x8b, 0x0d, 0xdd, 0xc7, 0x0d, 0xe5, 0xe1, 0xa8,
0x75, 0x44, 0x81, 0x2e, 0x81, 0x6c, 0x18, 0x1a, 0xb6, 0xf5, 0xba, 0x85, 0x35, 0xdd, 0xc5, 0xb6,
0xee, 0x29, 0x17, 0xa2, 0xc6, 0x45, 0xc3, 0xa8, 0x52, 0x6d, 0x85, 0x2a, 0xd1, 0x53, 0x30, 0xe5,
0xd4, 0x6f, 0x19, 0x2c, 0xb9, 0xb4, 0x8e, 0x8b, 0x9b, 0xe6, 0x2b, 0xca, 0x63, 0x34, 0x4c, 0x93,
0x44, 0x41, 0x53, 0x6b, 0x9f, 0x8a, 0xd1, 0x93, 0x20, 0x1b, 0xde, 0x91, 0xee, 0x76, 0x68, 0x77,
0xf7, 0x3a, 0xba, 0x81, 0x95, 0xc7, 0x99, 0x29, 0x93, 0xef, 0x0a, 0x31, 0x7a, 0x11, 0x66, 0xba,
0xb6, 0x69, 0xfb, 0xd8, 0xed, 0xb8, 0x98, 0x0c, 0xe9, 0x6c, 0xa7, 0x29, 0xff, 0x3a, 0x7e, 0xca,
0x98, 0x7d, 0x18, 0xb5, 0x66, 0xab, 0xab, 0x4e, 0x77, 0x07, 0x85, 0xf3, 0x65, 0x28, 0x44, 0x17,
0x1d, 0xe5, 0x80, 0x2d, 0xbb, 0x2c, 0x91, 0x1e, 0xba, 0xbe, 0xb7, 0x41, 0xba, 0xdf, 0xa7, 0xaa,
0x72, 0x82, 0x74, 0xe1, 0xed, 0xad, 0x83, 0xaa, 0xa6, 0x1e, 0xee, 0x1e, 0x6c, 0xed, 0x54, 0xe5,
0xe4, 0x53, 0xb9, 0xec, 0x0f, 0xc7, 0xe5, 0xbb, 0x77, 0xef, 0xde, 0x4d, 0xcc, 0x7f, 0x27, 0x01,
0xc5, 0xde, 0xc9, 0x17, 0xfd, 0x22, 0x3c, 0x2c, 0x5e, 0x53, 0x3d, 0xec, 0x6b, 0x2f, 0x9b, 0x2e,
0xcd, 0xc3, 0xb6, 0xce, 0x66, 0xc7, 0x20, 0x84, 0x33, 0xdc, 0xaa, 0x86, 0xfd, 0x4f, 0x9a, 0x2e,
0xc9, 0xb2, 0xb6, 0xee, 0xa3, 0x6d, 0xb8, 0x60, 0x3b, 0x9a, 0xe7, 0xeb, 0x76, 0x43, 0x77, 0x1b,
0x5a, 0x78, 0x40, 0xa0, 0xe9, 0x86, 0x81, 0x3d, 0xcf, 0x61, 0x2d, 0x20, 0x60, 0xf9, 0x90, 0xed,
0xd4, 0xb8, 0x71, 0x58, 0x1b, 0x2b, 0xdc, 0xb4, 0x6f, 0xb9, 0x93, 0xa7, 0x2d, 0xf7, 0x23, 0x90,
0x6b, 0xeb, 0x1d, 0x0d, 0xdb, 0xbe, 0x7b, 0x4c, 0xe7, 0xb5, 0xac, 0x9a, 0x6d, 0xeb, 0x9d, 0x2a,
0xb9, 0xfe, 0xe9, 0xad, 0x41, 0x34, 0x8e, 0xdf, 0x4f, 0x42, 0x21, 0x3a, 0xb3, 0x91, 0x11, 0xd8,
0xa0, 0xf5, 0x59, 0xa2, 0xdb, 0xf7, 0xc3, 0x0f, 0x9c, 0xf0, 0x16, 0xd7, 0x49, 0xe1, 0x2e, 0x67,
0xd8, 0x24, 0xa5, 0x32, 0x24, 0x69, 0x9a, 0x64, 0xc3, 0x62, 0x36, 0x9f, 0x67, 0x55, 0x7e, 0x85,
0x36, 0x21, 0x73, 0xcb, 0xa3, 0xdc, 0x19, 0xca, 0xfd, 0xd8, 0x83, 0xb9, 0x6f, 0xd6, 0x28, 0x79,
0xee, 0x66, 0x4d, 0xdb, 0xdd, 0x53, 0x77, 0x2a, 0xdb, 0x2a, 0x87, 0xa3, 0xf3, 0x90, 0xb2, 0xf4,
0x57, 0x8f, 0x7b, 0x4b, 0x3c, 0x15, 0x8d, 0x1a, 0xf8, 0xf3, 0x90, 0x7a, 0x19, 0xeb, 0xb7, 0x7b,
0x0b, 0x2b, 0x15, 0xfd, 0x14, 0x53, 0xff, 0x12, 0xa4, 0x69, 0xbc, 0x10, 0x00, 0x8f, 0x98, 0x3c,
0x86, 0xb2, 0x90, 0x5a, 0xdf, 0x53, 0x49, 0xfa, 0xcb, 0x50, 0x60, 0x52, 0x6d, 0x7f, 0xab, 0xba,
0x5e, 0x95, 0x13, 0xf3, 0xab, 0x90, 0x61, 0x41, 0x20, 0x5b, 0x23, 0x08, 0x83, 0x3c, 0xc6, 0x2f,
0x39, 0x87, 0x24, 0xb4, 0x87, 0x3b, 0x6b, 0x55, 0x55, 0x4e, 0x44, 0x97, 0xd7, 0x83, 0x42, 0x74,
0x5c, 0xfb, 0xd9, 0xe4, 0xd4, 0xdf, 0x49, 0x90, 0x8f, 0x8c, 0x5f, 0xa4, 0xf1, 0xeb, 0x96, 0xe5,
0xbc, 0xac, 0xe9, 0x96, 0xa9, 0x7b, 0x3c, 0x29, 0x80, 0x8a, 0x2a, 0x44, 0x32, 0xea, 0xa2, 0xfd,
0x4c, 0x9c, 0x7f, 0x53, 0x02, 0xb9, 0x7f, 0x74, 0xeb, 0x73, 0x50, 0xfa, 0x40, 0x1d, 0x7c, 0x43,
0x82, 0x62, 0xef, 0xbc, 0xd6, 0xe7, 0xde, 0xc5, 0x0f, 0xd4, 0xbd, 0x2f, 0x49, 0x30, 0xd1, 0x33,
0xa5, 0xfd, 0x5c, 0x79, 0xf7, 0x7a, 0x12, 0xa6, 0x87, 0xe0, 0x50, 0x85, 0x8f, 0xb3, 0x6c, 0xc2,
0x7e, 0x66, 0x94, 0x7b, 0x2d, 0x92, 0x6e, 0xb9, 0xaf, 0xbb, 0x3e, 0x9f, 0x7e, 0x9f, 0x04, 0xd9,
0x6c, 0x60, 0xdb, 0x37, 0x9b, 0x26, 0x76, 0xf9, 0x2b, 0x38, 0x9b, 0x71, 0x27, 0x43, 0x39, 0x7b,
0x0b, 0xff, 0x05, 0x40, 0x1d, 0xc7, 0x33, 0x7d, 0xf3, 0x0e, 0xd6, 0x4c, 0x5b, 0xbc, 0xaf, 0x93,
0x99, 0x37, 0xa5, 0xca, 0x42, 0xb3, 0x65, 0xfb, 0x81, 0xb5, 0x8d, 0x5b, 0x7a, 0x9f, 0x35, 0xa9,
0x7d, 0x49, 0x55, 0x16, 0x9a, 0xc0, 0xfa, 0x22, 0x14, 0x1a, 0x4e, 0x97, 0x8c, 0x0f, 0xcc, 0x8e,
0x94, 0x5a, 0x49, 0xcd, 0x33, 0x59, 0x60, 0xc2, 0xe7, 0xbb, 0xf0, 0xa0, 0xa0, 0xa0, 0xe6, 0x99,
0x8c, 0x99, 0x3c, 0x01, 0x93, 0x7a, 0xab, 0xe5, 0x12, 0x72, 0x41, 0xc4, 0x86, 0xd6, 0x62, 0x20,
0xa6, 0x86, 0xb3, 0x37, 0x21, 0x2b, 0xe2, 0x40, 0xba, 0x19, 0x89, 0x84, 0xd6, 0x61, 0xc7, 0x35,
0x89, 0x85, 0x9c, 0x9a, 0xb5, 0x85, 0xf2, 0x22, 0x14, 0x4c, 0x4f, 0x0b, 0xcf, 0x0d, 0x13, 0x73,
0x89, 0x85, 0xac, 0x9a, 0x37, 0xbd, 0xe0, 0xa0, 0x68, 0xfe, 0xad, 0x04, 0x14, 0x7b, 0xcf, 0x3d,
0xd1, 0x06, 0x64, 0x2d, 0xc7, 0xd0, 0x69, 0x22, 0xb0, 0x43, 0xf7, 0x85, 0x98, 0xa3, 0xd2, 0xc5,
0x6d, 0x6e, 0xaf, 0x06, 0xc8, 0xd9, 0x7f, 0x92, 0x20, 0x2b, 0xc4, 0xe8, 0x1c, 0xa4, 0x3a, 0xba,
0x7f, 0x44, 0xe9, 0xd2, 0x6b, 0x09, 0x59, 0x52, 0xe9, 0x35, 0x91, 0x7b, 0x1d, 0xdd, 0xa6, 0x29,
0xc0, 0xe5, 0xe4, 0x9a, 0xac, 0xab, 0x85, 0xf5, 0x06, 0x1d, 0x87, 0x9d, 0x76, 0x1b, 0xdb, 0xbe,
0x27, 0xd6, 0x95, 0xcb, 0xd7, 0xb9, 0x18, 0x3d, 0x0d, 0x53, 0xbe, 0xab, 0x9b, 0x56, 0x8f, 0x6d,
0x8a, 0xda, 0xca, 0x42, 0x11, 0x18, 0x97, 0xe1, 0xbc, 0xe0, 0x6d, 0x60, 0x5f, 0x37, 0x8e, 0x70,
0x23, 0x04, 0x65, 0xe8, 0xa1, 0xda, 0xc3, 0xdc, 0x60, 0x83, 0xeb, 0x05, 0x76, 0xfe, 0x7b, 0x12,
0x4c, 0x89, 0x01, 0xbe, 0x11, 0x04, 0x6b, 0x07, 0x40, 0xb7, 0x6d, 0xc7, 0x8f, 0x86, 0x6b, 0x30,
0x95, 0x07, 0x70, 0x8b, 0x95, 0x00, 0xa4, 0x46, 0x08, 0x66, 0xdb, 0x00, 0xa1, 0xe6, 0xd4, 0xb0,
0x5d, 0x80, 0x3c, 0x3f, 0xd4, 0xa6, 0xbf, 0x8c, 0xb0, 0xb7, 0x3e, 0x60, 0x22, 0x32, 0xe9, 0xa3,
0x19, 0x48, 0xd7, 0x71, 0xcb, 0xb4, 0xf9, 0x51, 0x1b, 0xbb, 0x10, 0x07, 0x78, 0xa9, 0xe0, 0x00,
0x6f, 0xed, 0xd3, 0x30, 0x6d, 0x38, 0xed, 0x7e, 0x77, 0xd7, 0xe4, 0xbe, 0x37, 0x4f, 0xef, 0x86,
0xf4, 0x29, 0x08, 0xa7, 0xb3, 0xaf, 0x48, 0xd2, 0x57, 0x13, 0xc9, 0xcd, 0xfd, 0xb5, 0xaf, 0x27,
0x66, 0x37, 0x19, 0x74, 0x5f, 0x3c, 0xa9, 0x8a, 0x9b, 0x16, 0x36, 0x88, 0xf7, 0xf0, 0xa3, 0x8f,
0xc0, 0x33, 0x2d, 0xd3, 0x3f, 0xea, 0xd6, 0x17, 0x0d, 0xa7, 0x7d, 0xa9, 0xe5, 0xb4, 0x9c, 0xf0,
0xc7, 0x20, 0x72, 0x45, 0x2f, 0xe8, 0x7f, 0xfc, 0x07, 0xa1, 0x5c, 0x20, 0x9d, 0x8d, 0xfd, 0xf5,
0xa8, 0xbc, 0x0b, 0xd3, 0xdc, 0x58, 0xa3, 0x27, 0xd2, 0x6c, 0x0e, 0x47, 0x0f, 0x3c, 0x95, 0x50,
0xbe, 0xf9, 0x0e, 0xed, 0x74, 0xea, 0x14, 0x87, 0x12, 0x1d, 0x9b, 0xd4, 0xcb, 0x2a, 0x3c, 0xd4,
0xc3, 0xc7, 0xb6, 0x26, 0x76, 0x63, 0x18, 0xbf, 0xc3, 0x19, 0xa7, 0x23, 0x8c, 0x35, 0x0e, 0x2d,
0xaf, 0xc3, 0xc4, 0x59, 0xb8, 0xfe, 0x81, 0x73, 0x15, 0x70, 0x94, 0x64, 0x13, 0x26, 0x29, 0x89,
0xd1, 0xf5, 0x7c, 0xa7, 0x4d, 0xeb, 0xde, 0x83, 0x69, 0xfe, 0xf1, 0x1d, 0xb6, 0x57, 0x8a, 0x04,
0xb6, 0x1e, 0xa0, 0xca, 0x65, 0xa0, 0x87, 0xf0, 0x0d, 0x6c, 0x58, 0x31, 0x0c, 0x6f, 0x73, 0x47,
0x02, 0xfb, 0xf2, 0x27, 0x60, 0x86, 0xfc, 0x4f, 0xcb, 0x52, 0xd4, 0x93, 0xf8, 0x33, 0x18, 0xe5,
0x7b, 0xaf, 0xb1, 0xed, 0x38, 0x1d, 0x10, 0x44, 0x7c, 0x8a, 0xac, 0x62, 0x0b, 0xfb, 0x3e, 0x76,
0x3d, 0x4d, 0xb7, 0x86, 0xb9, 0x17, 0x79, 0x83, 0x55, 0xbe, 0xf8, 0x6e, 0xef, 0x2a, 0x6e, 0x32,
0x64, 0xc5, 0xb2, 0xca, 0x87, 0xf0, 0xf0, 0x90, 0xac, 0x18, 0x81, 0xf3, 0x75, 0xce, 0x39, 0x33,
0x90, 0x19, 0x84, 0x76, 0x1f, 0x84, 0x3c, 0x58, 0xcb, 0x11, 0x38, 0xbf, 0xc4, 0x39, 0x11, 0xc7,
0x8a, 0x25, 0x25, 0x8c, 0x37, 0x61, 0xea, 0x0e, 0x76, 0xeb, 0x8e, 0xc7, 0x0f, 0x0e, 0x46, 0xa0,
0x7b, 0x83, 0xd3, 0x4d, 0x72, 0x20, 0x3d, 0x46, 0x20, 0x5c, 0xd7, 0x20, 0xdb, 0xd4, 0x0d, 0x3c,
0x02, 0xc5, 0x97, 0x39, 0xc5, 0x38, 0xb1, 0x27, 0xd0, 0x0a, 0x14, 0x5a, 0x0e, 0xef, 0x4c, 0xf1,
0xf0, 0x37, 0x39, 0x3c, 0x2f, 0x30, 0x9c, 0xa2, 0xe3, 0x74, 0xba, 0x16, 0x69, 0x5b, 0xf1, 0x14,
0xbf, 0x2f, 0x28, 0x04, 0x86, 0x53, 0x9c, 0x21, 0xac, 0x5f, 0x11, 0x14, 0x5e, 0x24, 0x9e, 0xcf,
0x43, 0xde, 0xb1, 0xad, 0x63, 0xc7, 0x1e, 0xc5, 0x89, 0x3f, 0xe0, 0x0c, 0xc0, 0x21, 0x84, 0xe0,
0x3a, 0xe4, 0x46, 0x5d, 0x88, 0x3f, 0x7c, 0x57, 0x6c, 0x0f, 0xb1, 0x02, 0x9b, 0x30, 0x29, 0x0a,
0x94, 0xe9, 0xd8, 0x23, 0x50, 0xfc, 0x11, 0xa7, 0x28, 0x46, 0x60, 0xfc, 0x31, 0x7c, 0xec, 0xf9,
0x2d, 0x3c, 0x0a, 0xc9, 0x5b, 0xe2, 0x31, 0x38, 0x84, 0x87, 0xb2, 0x8e, 0x6d, 0xe3, 0x68, 0x34,
0x86, 0xaf, 0x89, 0x50, 0x0a, 0x0c, 0xa1, 0x58, 0x87, 0x89, 0xb6, 0xee, 0x7a, 0x47, 0xba, 0x35,
0xd2, 0x72, 0xfc, 0x31, 0xe7, 0x28, 0x04, 0x20, 0x1e, 0x91, 0xae, 0x7d, 0x16, 0x9a, 0xaf, 0x8b,
0x88, 0x44, 0x60, 0x7c, 0xeb, 0x79, 0x3e, 0x3d, 0x9b, 0x39, 0x0b, 0xdb, 0x9f, 0x88, 0xad, 0xc7,
0xb0, 0x3b, 0x51, 0xc6, 0xeb, 0x90, 0xf3, 0xcc, 0x57, 0x47, 0xa2, 0xf9, 0x53, 0xb1, 0xd2, 0x14,
0x40, 0xc0, 0x2f, 0xc1, 0xf9, 0xa1, 0x6d, 0x62, 0x04, 0xb2, 0x3f, 0xe3, 0x64, 0xe7, 0x86, 0xb4,
0x0a, 0x5e, 0x12, 0xce, 0x4a, 0xf9, 0xe7, 0xa2, 0x24, 0xe0, 0x3e, 0xae, 0x7d, 0x32, 0xd9, 0x7b,
0x7a, 0xf3, 0x6c, 0x51, 0xfb, 0x0b, 0x11, 0x35, 0x86, 0xed, 0x89, 0xda, 0x01, 0x9c, 0xe3, 0x8c,
0x67, 0x5b, 0xd7, 0x6f, 0x88, 0xc2, 0xca, 0xd0, 0x87, 0xbd, 0xab, 0xfb, 0x69, 0x98, 0x0d, 0xc2,
0x29, 0x86, 0x52, 0x4f, 0x6b, 0xeb, 0x9d, 0x11, 0x98, 0xbf, 0xc9, 0x99, 0x45, 0xc5, 0x0f, 0xa6,
0x5a, 0x6f, 0x47, 0xef, 0x10, 0xf2, 0x17, 0x41, 0x11, 0xe4, 0x5d, 0xdb, 0xc5, 0x86, 0xd3, 0xb2,
0xcd, 0x57, 0x71, 0x63, 0x04, 0xea, 0xbf, 0xec, 0x5b, 0xaa, 0xc3, 0x08, 0x9c, 0x30, 0x6f, 0x81,
0x1c, 0xcc, 0x2a, 0x9a, 0xd9, 0xee, 0x38, 0xae, 0x1f, 0xc3, 0xf8, 0x57, 0x62, 0xa5, 0x02, 0xdc,
0x16, 0x85, 0x95, 0xab, 0x50, 0xa4, 0x97, 0xa3, 0xa6, 0xe4, 0x5f, 0x73, 0xa2, 0x89, 0x10, 0xc5,
0x0b, 0x87, 0xe1, 0xb4, 0x3b, 0xba, 0x3b, 0x4a, 0xfd, 0xfb, 0x1b, 0x51, 0x38, 0x38, 0x84, 0x17,
0x0e, 0xff, 0xb8, 0x83, 0x49, 0xb7, 0x1f, 0x81, 0xe1, 0x5b, 0xa2, 0x70, 0x08, 0x0c, 0xa7, 0x10,
0x03, 0xc3, 0x08, 0x14, 0x7f, 0x2b, 0x28, 0x04, 0x86, 0x50, 0x7c, 0x3c, 0x6c, 0xb4, 0x2e, 0x6e,
0x99, 0x9e, 0xef, 0xb2, 0x51, 0xf8, 0xc1, 0x54, 0xdf, 0x7e, 0xb7, 0x77, 0x08, 0x53, 0x23, 0xd0,
0xf2, 0x4d, 0x98, 0xec, 0x1b, 0x31, 0x50, 0xdc, 0x2f, 0xfa, 0xca, 0x67, 0xde, 0xe7, 0xc5, 0xa8,
0x77, 0xc2, 0x28, 0x6f, 0x93, 0x75, 0xef, 0x9d, 0x03, 0xe2, 0xc9, 0x5e, 0x7b, 0x3f, 0x58, 0xfa,
0x9e, 0x31, 0xa0, 0xfc, 0x02, 0x4c, 0xf4, 0xcc, 0x00, 0xf1, 0x54, 0xbf, 0xcc, 0xa9, 0x0a, 0xd1,
0x11, 0xa0, 0xbc, 0x0a, 0x29, 0xd2, 0xcf, 0xe3, 0xe1, 0xbf, 0xc2, 0xe1, 0xd4, 0xbc, 0xfc, 0x51,
0xc8, 0x8a, 0x3e, 0x1e, 0x0f, 0xfd, 0x55, 0x0e, 0x0d, 0x20, 0x04, 0x2e, 0x7a, 0x78, 0x3c, 0xfc,
0xd7, 0x04, 0x5c, 0x40, 0x08, 0x7c, 0xf4, 0x10, 0xfe, 0xfd, 0xe7, 0x52, 0xbc, 0x0e, 0x8b, 0xd8,
0x5d, 0x87, 0x71, 0xde, 0xbc, 0xe3, 0xd1, 0x9f, 0xe5, 0x37, 0x17, 0x88, 0xf2, 0x15, 0x48, 0x8f,
0x18, 0xf0, 0x5f, 0xe7, 0x50, 0x66, 0x5f, 0x5e, 0x87, 0x7c, 0xa4, 0x61, 0xc7, 0xc3, 0x7f, 0x83,
0xc3, 0xa3, 0x28, 0xe2, 0x3a, 0x6f, 0xd8, 0xf1, 0x04, 0xbf, 0x29, 0x5c, 0xe7, 0x08, 0x12, 0x36,
0xd1, 0xab, 0xe3, 0xd1, 0xbf, 0x25, 0xa2, 0x2e, 0x20, 0xe5, 0xe7, 0x21, 0x17, 0xd4, 0xdf, 0x78,
0xfc, 0x6f, 0x73, 0x7c, 0x88, 0x21, 0x11, 0x88, 0xd4, 0xff, 0x78, 0x8a, 0xdf, 0x11, 0x11, 0x88,
0xa0, 0xc8, 0x36, 0xea, 0xef, 0xe9, 0xf1, 0x4c, 0x9f, 0x17, 0xdb, 0xa8, 0xaf, 0xa5, 0x93, 0xd5,
0xa4, 0x65, 0x30, 0x9e, 0xe2, 0x77, 0xc5, 0x6a, 0x52, 0x7b, 0xe2, 0x46, 0x7f, 0x93, 0x8c, 0xe7,
0xf8, 0x3d, 0xe1, 0x46, 0x5f, 0x8f, 0x2c, 0xef, 0x03, 0x1a, 0x6c, 0x90, 0xf1, 0x7c, 0x5f, 0xe0,
0x7c, 0x53, 0x03, 0xfd, 0xb1, 0xfc, 0x49, 0x38, 0x37, 0xbc, 0x39, 0xc6, 0xb3, 0x7e, 0xf1, 0xfd,
0xbe, 0xd7, 0x99, 0x68, 0x6f, 0x2c, 0x1f, 0x84, 0x55, 0x36, 0xda, 0x18, 0xe3, 0x69, 0x5f, 0x7f,
0xbf, 0xb7, 0xd0, 0x46, 0xfb, 0x62, 0xb9, 0x02, 0x10, 0xf6, 0xa4, 0x78, 0xae, 0x37, 0x38, 0x57,
0x04, 0x44, 0xb6, 0x06, 0x6f, 0x49, 0xf1, 0xf8, 0x2f, 0x8b, 0xad, 0xc1, 0x11, 0x64, 0x6b, 0x88,
0x6e, 0x14, 0x8f, 0x7e, 0x53, 0x6c, 0x0d, 0x01, 0x29, 0x5f, 0x87, 0xac, 0xdd, 0xb5, 0x2c, 0x92,
0x5b, 0xe8, 0xc1, 0x1f, 0xd9, 0x28, 0xff, 0x76, 0x9f, 0x83, 0x05, 0xa0, 0xbc, 0x0a, 0x69, 0xdc,
0xae, 0xe3, 0x46, 0x1c, 0xf2, 0xdf, 0xef, 0x8b, 0x7a, 0x42, 0xac, 0xcb, 0xcf, 0x03, 0xb0, 0x97,
0x69, 0xfa, 0x1b, 0x4b, 0x0c, 0xf6, 0x3f, 0xee, 0xf3, 0xdf, 0xef, 0x43, 0x48, 0x48, 0xc0, 0xbe,
0x06, 0x78, 0x30, 0xc1, 0xbb, 0xbd, 0x04, 0xf4, 0x05, 0xfc, 0x1a, 0x8c, 0xdf, 0xf2, 0x1c, 0xdb,
0xd7, 0x5b, 0x71, 0xe8, 0xff, 0xe4, 0x68, 0x61, 0x4f, 0x02, 0xd6, 0x76, 0x5c, 0xec, 0xeb, 0x2d,
0x2f, 0x0e, 0xfb, 0x5f, 0x1c, 0x1b, 0x00, 0x08, 0xd8, 0xd0, 0x3d, 0x7f, 0x94, 0xe7, 0xfe, 0x6f,
0x01, 0x16, 0x00, 0xe2, 0x34, 0xf9, 0xff, 0x36, 0x3e, 0x8e, 0xc3, 0xbe, 0x27, 0x9c, 0xe6, 0xf6,
0xe5, 0x8f, 0x42, 0x8e, 0xfc, 0xcb, 0xbe, 0x69, 0x89, 0x01, 0xff, 0x0f, 0x07, 0x87, 0x08, 0x72,
0x67, 0xcf, 0x6f, 0xf8, 0x66, 0x7c, 0xb0, 0xff, 0x97, 0xaf, 0xb4, 0xb0, 0x2f, 0x57, 0x20, 0xef,
0xf9, 0x8d, 0x46, 0x97, 0x4f, 0x34, 0x31, 0xf0, 0x1f, 0xdd, 0x0f, 0x5e, 0x72, 0x03, 0xcc, 0xda,
0xc5, 0xe1, 0xe7, 0x75, 0xb0, 0xe9, 0x6c, 0x3a, 0xec, 0xa4, 0x0e, 0x3e, 0x9f, 0x86, 0x87, 0x0c,
0xa7, 0x5d, 0x77, 0xbc, 0x4b, 0x75, 0xc7, 0x3f, 0xba, 0xe4, 0xd8, 0xdc, 0x10, 0x25, 0x1d, 0x1b,
0xcf, 0x9e, 0xed, 0x44, 0x6e, 0xfe, 0x3c, 0xa4, 0x6b, 0xdd, 0x7a, 0xfd, 0x18, 0xc9, 0x90, 0xf4,
0xba, 0x75, 0xfe, 0xc1, 0x05, 0xf9, 0x77, 0xfe, 0xfb, 0x49, 0xc8, 0xd7, 0xf4, 0x76, 0xc7, 0xc2,
0x7b, 0x36, 0xde, 0x6b, 0x22, 0x05, 0x32, 0xf4, 0x01, 0x9e, 0xa3, 0x46, 0xd2, 0x8d, 0x31, 0x95,
0x5f, 0x07, 0x9a, 0x25, 0x7a, 0x52, 0x99, 0x08, 0x34, 0x4b, 0x81, 0x66, 0x99, 0x1d, 0x54, 0x06,
0x9a, 0xe5, 0x40, 0xb3, 0x42, 0x8f, 0x2b, 0x93, 0x81, 0x66, 0x25, 0xd0, 0xac, 0xd2, 0xe3, 0xf8,
0x89, 0x40, 0xb3, 0x1a, 0x68, 0x2e, 0xd3, 0x03, 0xf8, 0x54, 0xa0, 0xb9, 0x1c, 0x68, 0xae, 0xd0,
0x73, 0xf7, 0xa9, 0x40, 0x73, 0x25, 0xd0, 0x5c, 0xa5, 0x67, 0xed, 0x28, 0xd0, 0x5c, 0x0d, 0x34,
0xd7, 0xe8, 0x47, 0x15, 0xe3, 0x81, 0xe6, 0x1a, 0x9a, 0x85, 0x71, 0xf6, 0x64, 0xcf, 0xd2, 0xdf,
0x32, 0x27, 0x6f, 0x8c, 0xa9, 0x42, 0x10, 0xea, 0x9e, 0xa3, 0x1f, 0x4e, 0x64, 0x42, 0xdd, 0x73,
0xa1, 0x6e, 0x89, 0x7e, 0x41, 0x2c, 0x87, 0xba, 0xa5, 0x50, 0xb7, 0xac, 0x4c, 0x90, 0x75, 0x0f,
0x75, 0xcb, 0xa1, 0x6e, 0x45, 0x29, 0x92, 0xf8, 0x87, 0xba, 0x95, 0x50, 0xb7, 0xaa, 0x4c, 0xce,
0x49, 0x0b, 0x85, 0x50, 0xb7, 0x8a, 0x9e, 0x81, 0xbc, 0xd7, 0xad, 0x6b, 0xfc, 0xa7, 0x77, 0xfa,
0x81, 0x46, 0x7e, 0x09, 0x16, 0x49, 0x46, 0xd0, 0x45, 0xbd, 0x31, 0xa6, 0x82, 0xd7, 0xad, 0xf3,
0xc2, 0xb8, 0x56, 0x00, 0x7a, 0x8e, 0xa0, 0xd1, 0x2f, 0x13, 0xd7, 0x36, 0xde, 0xbe, 0x57, 0x1a,
0xfb, 0xee, 0xbd, 0xd2, 0xd8, 0x3f, 0xdf, 0x2b, 0x8d, 0xfd, 0xe0, 0x5e, 0x49, 0x7a, 0xef, 0x5e,
0x49, 0xfa, 0xf1, 0xbd, 0x92, 0x74, 0xf7, 0xa4, 0x24, 0x7d, 0xed, 0xa4, 0x24, 0x7d, 0xe3, 0xa4,
0x24, 0x7d, 0xfb, 0xa4, 0x24, 0xbd, 0x7d, 0x52, 0x92, 0xbe, 0x7b, 0x52, 0x92, 0x7e, 0x70, 0x52,
0x92, 0x7e, 0x78, 0x52, 0x1a, 0x7b, 0xef, 0xa4, 0x24, 0xfd, 0xf8, 0xa4, 0x34, 0x76, 0xf7, 0x5f,
0x4a, 0x63, 0xf5, 0x0c, 0x4d, 0xa3, 0xe5, 0xff, 0x0f, 0x00, 0x00, 0xff, 0xff, 0x34, 0x19, 0xac,
0x3a, 0x10, 0x30, 0x00, 0x00,
}
r := bytes.NewReader(gzipped)
gzipr, err := compress_gzip.NewReader(r)
if err != nil {
panic(err)
}
ungzipped, err := io_ioutil.ReadAll(gzipr)
if err != nil {
panic(err)
}
if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil {
panic(err)
}
return d
}
func (this *Subby) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *Subby")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *Subby but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *Subby but is not nil && this == nil")
}
if this.Sub != that1.Sub {
return fmt.Errorf("Sub this(%v) Not Equal that(%v)", this.Sub, that1.Sub)
}
return nil
}
func (this *Subby) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*Subby)
if !ok {
that2, ok := that.(Subby)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Sub != that1.Sub {
return false
}
return true
}
func (this *SampleOneOf) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf)
if !ok {
that2, ok := that.(SampleOneOf)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf but is not nil && this == nil")
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return fmt.Errorf("this.TestOneof != nil && that1.TestOneof == nil")
}
} else if this.TestOneof == nil {
return fmt.Errorf("this.TestOneof == nil && that1.TestOneof != nil")
} else if err := this.TestOneof.VerboseEqual(that1.TestOneof); err != nil {
return err
}
return nil
}
func (this *SampleOneOf_Field1) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field1)
if !ok {
that2, ok := that.(SampleOneOf_Field1)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field1")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field1 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field1 but is not nil && this == nil")
}
if this.Field1 != that1.Field1 {
return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", this.Field1, that1.Field1)
}
return nil
}
func (this *SampleOneOf_Field2) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field2)
if !ok {
that2, ok := that.(SampleOneOf_Field2)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field2")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field2 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field2 but is not nil && this == nil")
}
if this.Field2 != that1.Field2 {
return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", this.Field2, that1.Field2)
}
return nil
}
func (this *SampleOneOf_Field3) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field3)
if !ok {
that2, ok := that.(SampleOneOf_Field3)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field3")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field3 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field3 but is not nil && this == nil")
}
if this.Field3 != that1.Field3 {
return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", this.Field3, that1.Field3)
}
return nil
}
func (this *SampleOneOf_Field4) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field4)
if !ok {
that2, ok := that.(SampleOneOf_Field4)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field4")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field4 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field4 but is not nil && this == nil")
}
if this.Field4 != that1.Field4 {
return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", this.Field4, that1.Field4)
}
return nil
}
func (this *SampleOneOf_Field5) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field5)
if !ok {
that2, ok := that.(SampleOneOf_Field5)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field5")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field5 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field5 but is not nil && this == nil")
}
if this.Field5 != that1.Field5 {
return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", this.Field5, that1.Field5)
}
return nil
}
func (this *SampleOneOf_Field6) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field6)
if !ok {
that2, ok := that.(SampleOneOf_Field6)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field6")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field6 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field6 but is not nil && this == nil")
}
if this.Field6 != that1.Field6 {
return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", this.Field6, that1.Field6)
}
return nil
}
func (this *SampleOneOf_Field7) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field7)
if !ok {
that2, ok := that.(SampleOneOf_Field7)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field7")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field7 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field7 but is not nil && this == nil")
}
if this.Field7 != that1.Field7 {
return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", this.Field7, that1.Field7)
}
return nil
}
func (this *SampleOneOf_Field8) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field8)
if !ok {
that2, ok := that.(SampleOneOf_Field8)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field8")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field8 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field8 but is not nil && this == nil")
}
if this.Field8 != that1.Field8 {
return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", this.Field8, that1.Field8)
}
return nil
}
func (this *SampleOneOf_Field9) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field9)
if !ok {
that2, ok := that.(SampleOneOf_Field9)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field9")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field9 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field9 but is not nil && this == nil")
}
if this.Field9 != that1.Field9 {
return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", this.Field9, that1.Field9)
}
return nil
}
func (this *SampleOneOf_Field10) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field10)
if !ok {
that2, ok := that.(SampleOneOf_Field10)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field10")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field10 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field10 but is not nil && this == nil")
}
if this.Field10 != that1.Field10 {
return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", this.Field10, that1.Field10)
}
return nil
}
func (this *SampleOneOf_Field11) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field11)
if !ok {
that2, ok := that.(SampleOneOf_Field11)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field11")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field11 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field11 but is not nil && this == nil")
}
if this.Field11 != that1.Field11 {
return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", this.Field11, that1.Field11)
}
return nil
}
func (this *SampleOneOf_Field12) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field12)
if !ok {
that2, ok := that.(SampleOneOf_Field12)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field12")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field12 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field12 but is not nil && this == nil")
}
if this.Field12 != that1.Field12 {
return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", this.Field12, that1.Field12)
}
return nil
}
func (this *SampleOneOf_Field13) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field13)
if !ok {
that2, ok := that.(SampleOneOf_Field13)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field13")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field13 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field13 but is not nil && this == nil")
}
if this.Field13 != that1.Field13 {
return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", this.Field13, that1.Field13)
}
return nil
}
func (this *SampleOneOf_Field14) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field14)
if !ok {
that2, ok := that.(SampleOneOf_Field14)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field14")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field14 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field14 but is not nil && this == nil")
}
if this.Field14 != that1.Field14 {
return fmt.Errorf("Field14 this(%v) Not Equal that(%v)", this.Field14, that1.Field14)
}
return nil
}
func (this *SampleOneOf_Field15) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_Field15)
if !ok {
that2, ok := that.(SampleOneOf_Field15)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_Field15")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_Field15 but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_Field15 but is not nil && this == nil")
}
if !bytes.Equal(this.Field15, that1.Field15) {
return fmt.Errorf("Field15 this(%v) Not Equal that(%v)", this.Field15, that1.Field15)
}
return nil
}
func (this *SampleOneOf_SubMessage) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*SampleOneOf_SubMessage)
if !ok {
that2, ok := that.(SampleOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *SampleOneOf_SubMessage")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *SampleOneOf_SubMessage but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *SampleOneOf_SubMessage but is not nil && this == nil")
}
if !this.SubMessage.Equal(that1.SubMessage) {
return fmt.Errorf("SubMessage this(%v) Not Equal that(%v)", this.SubMessage, that1.SubMessage)
}
return nil
}
func (this *SampleOneOf) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf)
if !ok {
that2, ok := that.(SampleOneOf)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if that1.TestOneof == nil {
if this.TestOneof != nil {
return false
}
} else if this.TestOneof == nil {
return false
} else if !this.TestOneof.Equal(that1.TestOneof) {
return false
}
return true
}
func (this *SampleOneOf_Field1) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field1)
if !ok {
that2, ok := that.(SampleOneOf_Field1)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field1 != that1.Field1 {
return false
}
return true
}
func (this *SampleOneOf_Field2) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field2)
if !ok {
that2, ok := that.(SampleOneOf_Field2)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field2 != that1.Field2 {
return false
}
return true
}
func (this *SampleOneOf_Field3) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field3)
if !ok {
that2, ok := that.(SampleOneOf_Field3)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field3 != that1.Field3 {
return false
}
return true
}
func (this *SampleOneOf_Field4) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field4)
if !ok {
that2, ok := that.(SampleOneOf_Field4)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field4 != that1.Field4 {
return false
}
return true
}
func (this *SampleOneOf_Field5) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field5)
if !ok {
that2, ok := that.(SampleOneOf_Field5)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field5 != that1.Field5 {
return false
}
return true
}
func (this *SampleOneOf_Field6) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field6)
if !ok {
that2, ok := that.(SampleOneOf_Field6)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field6 != that1.Field6 {
return false
}
return true
}
func (this *SampleOneOf_Field7) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field7)
if !ok {
that2, ok := that.(SampleOneOf_Field7)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field7 != that1.Field7 {
return false
}
return true
}
func (this *SampleOneOf_Field8) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field8)
if !ok {
that2, ok := that.(SampleOneOf_Field8)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field8 != that1.Field8 {
return false
}
return true
}
func (this *SampleOneOf_Field9) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field9)
if !ok {
that2, ok := that.(SampleOneOf_Field9)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field9 != that1.Field9 {
return false
}
return true
}
func (this *SampleOneOf_Field10) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field10)
if !ok {
that2, ok := that.(SampleOneOf_Field10)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field10 != that1.Field10 {
return false
}
return true
}
func (this *SampleOneOf_Field11) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field11)
if !ok {
that2, ok := that.(SampleOneOf_Field11)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field11 != that1.Field11 {
return false
}
return true
}
func (this *SampleOneOf_Field12) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field12)
if !ok {
that2, ok := that.(SampleOneOf_Field12)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field12 != that1.Field12 {
return false
}
return true
}
func (this *SampleOneOf_Field13) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field13)
if !ok {
that2, ok := that.(SampleOneOf_Field13)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field13 != that1.Field13 {
return false
}
return true
}
func (this *SampleOneOf_Field14) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field14)
if !ok {
that2, ok := that.(SampleOneOf_Field14)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.Field14 != that1.Field14 {
return false
}
return true
}
func (this *SampleOneOf_Field15) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_Field15)
if !ok {
that2, ok := that.(SampleOneOf_Field15)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !bytes.Equal(this.Field15, that1.Field15) {
return false
}
return true
}
func (this *SampleOneOf_SubMessage) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*SampleOneOf_SubMessage)
if !ok {
that2, ok := that.(SampleOneOf_SubMessage)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if !this.SubMessage.Equal(that1.SubMessage) {
return false
}
return true
}
func (this *Subby) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&one.Subby{")
s = append(s, "Sub: "+fmt.Sprintf("%#v", this.Sub)+",\n")
s = append(s, "}")
return strings.Join(s, "")
}
func (this *SampleOneOf) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 20)
s = append(s, "&one.SampleOneOf{")
if this.TestOneof != nil {
s = append(s, "TestOneof: "+fmt.Sprintf("%#v", this.TestOneof)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func (this *SampleOneOf_Field1) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field1{` +
`Field1:` + fmt.Sprintf("%#v", this.Field1) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field2) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field2{` +
`Field2:` + fmt.Sprintf("%#v", this.Field2) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field3) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field3{` +
`Field3:` + fmt.Sprintf("%#v", this.Field3) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field4) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field4{` +
`Field4:` + fmt.Sprintf("%#v", this.Field4) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field5) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field5{` +
`Field5:` + fmt.Sprintf("%#v", this.Field5) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field6) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field6{` +
`Field6:` + fmt.Sprintf("%#v", this.Field6) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field7) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field7{` +
`Field7:` + fmt.Sprintf("%#v", this.Field7) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field8) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field8{` +
`Field8:` + fmt.Sprintf("%#v", this.Field8) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field9) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field9{` +
`Field9:` + fmt.Sprintf("%#v", this.Field9) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field10) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field10{` +
`Field10:` + fmt.Sprintf("%#v", this.Field10) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field11) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field11{` +
`Field11:` + fmt.Sprintf("%#v", this.Field11) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field12) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field12{` +
`Field12:` + fmt.Sprintf("%#v", this.Field12) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field13) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field13{` +
`Field13:` + fmt.Sprintf("%#v", this.Field13) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field14) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field14{` +
`Field14:` + fmt.Sprintf("%#v", this.Field14) + `}`}, ", ")
return s
}
func (this *SampleOneOf_Field15) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_Field15{` +
`Field15:` + fmt.Sprintf("%#v", this.Field15) + `}`}, ", ")
return s
}
func (this *SampleOneOf_SubMessage) GoString() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&one.SampleOneOf_SubMessage{` +
`SubMessage:` + fmt.Sprintf("%#v", this.SubMessage) + `}`}, ", ")
return s
}
func valueToGoStringOne(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func (m *Subby) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *Subby) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.Sub) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Sub)))
i += copy(dAtA[i:], m.Sub)
}
return i, nil
}
func (m *SampleOneOf) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *SampleOneOf) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.TestOneof != nil {
nn1, err := m.TestOneof.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += nn1
}
return i, nil
}
func (m *SampleOneOf_Field1) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x9
i++
i = encodeFixed64One(dAtA, i, uint64(math.Float64bits(float64(m.Field1))))
return i, nil
}
func (m *SampleOneOf_Field2) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x15
i++
i = encodeFixed32One(dAtA, i, uint32(math.Float32bits(float32(m.Field2))))
return i, nil
}
func (m *SampleOneOf_Field3) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x18
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field3))
return i, nil
}
func (m *SampleOneOf_Field4) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x20
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field4))
return i, nil
}
func (m *SampleOneOf_Field5) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x28
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field5))
return i, nil
}
func (m *SampleOneOf_Field6) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x30
i++
i = encodeVarintOne(dAtA, i, uint64(m.Field6))
return i, nil
}
func (m *SampleOneOf_Field7) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x38
i++
i = encodeVarintOne(dAtA, i, uint64((uint32(m.Field7)<<1)^uint32((m.Field7>>31))))
return i, nil
}
func (m *SampleOneOf_Field8) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x40
i++
i = encodeVarintOne(dAtA, i, uint64((uint64(m.Field8)<<1)^uint64((m.Field8>>63))))
return i, nil
}
func (m *SampleOneOf_Field9) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x4d
i++
i = encodeFixed32One(dAtA, i, uint32(m.Field9))
return i, nil
}
func (m *SampleOneOf_Field10) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x55
i++
i = encodeFixed32One(dAtA, i, uint32(m.Field10))
return i, nil
}
func (m *SampleOneOf_Field11) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x59
i++
i = encodeFixed64One(dAtA, i, uint64(m.Field11))
return i, nil
}
func (m *SampleOneOf_Field12) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x61
i++
i = encodeFixed64One(dAtA, i, uint64(m.Field12))
return i, nil
}
func (m *SampleOneOf_Field13) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x68
i++
if m.Field13 {
dAtA[i] = 1
} else {
dAtA[i] = 0
}
i++
return i, nil
}
func (m *SampleOneOf_Field14) MarshalTo(dAtA []byte) (int, error) {
i := 0
dAtA[i] = 0x72
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field14)))
i += copy(dAtA[i:], m.Field14)
return i, nil
}
func (m *SampleOneOf_Field15) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.Field15 != nil {
dAtA[i] = 0x7a
i++
i = encodeVarintOne(dAtA, i, uint64(len(m.Field15)))
i += copy(dAtA[i:], m.Field15)
}
return i, nil
}
func (m *SampleOneOf_SubMessage) MarshalTo(dAtA []byte) (int, error) {
i := 0
if m.SubMessage != nil {
dAtA[i] = 0x82
i++
dAtA[i] = 0x1
i++
i = encodeVarintOne(dAtA, i, uint64(m.SubMessage.Size()))
n2, err := m.SubMessage.MarshalTo(dAtA[i:])
if err != nil {
return 0, err
}
i += n2
}
return i, nil
}
func encodeFixed64One(dAtA []byte, offset int, v uint64) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
dAtA[offset+4] = uint8(v >> 32)
dAtA[offset+5] = uint8(v >> 40)
dAtA[offset+6] = uint8(v >> 48)
dAtA[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32One(dAtA []byte, offset int, v uint32) int {
dAtA[offset] = uint8(v)
dAtA[offset+1] = uint8(v >> 8)
dAtA[offset+2] = uint8(v >> 16)
dAtA[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintOne(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func NewPopulatedSubby(r randyOne, easy bool) *Subby {
this := &Subby{}
this.Sub = string(randStringOne(r))
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedSampleOneOf(r randyOne, easy bool) *SampleOneOf {
this := &SampleOneOf{}
oneofNumber_TestOneof := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}[r.Intn(16)]
switch oneofNumber_TestOneof {
case 1:
this.TestOneof = NewPopulatedSampleOneOf_Field1(r, easy)
case 2:
this.TestOneof = NewPopulatedSampleOneOf_Field2(r, easy)
case 3:
this.TestOneof = NewPopulatedSampleOneOf_Field3(r, easy)
case 4:
this.TestOneof = NewPopulatedSampleOneOf_Field4(r, easy)
case 5:
this.TestOneof = NewPopulatedSampleOneOf_Field5(r, easy)
case 6:
this.TestOneof = NewPopulatedSampleOneOf_Field6(r, easy)
case 7:
this.TestOneof = NewPopulatedSampleOneOf_Field7(r, easy)
case 8:
this.TestOneof = NewPopulatedSampleOneOf_Field8(r, easy)
case 9:
this.TestOneof = NewPopulatedSampleOneOf_Field9(r, easy)
case 10:
this.TestOneof = NewPopulatedSampleOneOf_Field10(r, easy)
case 11:
this.TestOneof = NewPopulatedSampleOneOf_Field11(r, easy)
case 12:
this.TestOneof = NewPopulatedSampleOneOf_Field12(r, easy)
case 13:
this.TestOneof = NewPopulatedSampleOneOf_Field13(r, easy)
case 14:
this.TestOneof = NewPopulatedSampleOneOf_Field14(r, easy)
case 15:
this.TestOneof = NewPopulatedSampleOneOf_Field15(r, easy)
case 16:
this.TestOneof = NewPopulatedSampleOneOf_SubMessage(r, easy)
}
if !easy && r.Intn(10) != 0 {
}
return this
}
func NewPopulatedSampleOneOf_Field1(r randyOne, easy bool) *SampleOneOf_Field1 {
this := &SampleOneOf_Field1{}
this.Field1 = float64(r.Float64())
if r.Intn(2) == 0 {
this.Field1 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field2(r randyOne, easy bool) *SampleOneOf_Field2 {
this := &SampleOneOf_Field2{}
this.Field2 = float32(r.Float32())
if r.Intn(2) == 0 {
this.Field2 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field3(r randyOne, easy bool) *SampleOneOf_Field3 {
this := &SampleOneOf_Field3{}
this.Field3 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field3 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field4(r randyOne, easy bool) *SampleOneOf_Field4 {
this := &SampleOneOf_Field4{}
this.Field4 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field4 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field5(r randyOne, easy bool) *SampleOneOf_Field5 {
this := &SampleOneOf_Field5{}
this.Field5 = uint32(r.Uint32())
return this
}
func NewPopulatedSampleOneOf_Field6(r randyOne, easy bool) *SampleOneOf_Field6 {
this := &SampleOneOf_Field6{}
this.Field6 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedSampleOneOf_Field7(r randyOne, easy bool) *SampleOneOf_Field7 {
this := &SampleOneOf_Field7{}
this.Field7 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field7 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field8(r randyOne, easy bool) *SampleOneOf_Field8 {
this := &SampleOneOf_Field8{}
this.Field8 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field8 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field9(r randyOne, easy bool) *SampleOneOf_Field9 {
this := &SampleOneOf_Field9{}
this.Field9 = uint32(r.Uint32())
return this
}
func NewPopulatedSampleOneOf_Field10(r randyOne, easy bool) *SampleOneOf_Field10 {
this := &SampleOneOf_Field10{}
this.Field10 = int32(r.Int31())
if r.Intn(2) == 0 {
this.Field10 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field11(r randyOne, easy bool) *SampleOneOf_Field11 {
this := &SampleOneOf_Field11{}
this.Field11 = uint64(uint64(r.Uint32()))
return this
}
func NewPopulatedSampleOneOf_Field12(r randyOne, easy bool) *SampleOneOf_Field12 {
this := &SampleOneOf_Field12{}
this.Field12 = int64(r.Int63())
if r.Intn(2) == 0 {
this.Field12 *= -1
}
return this
}
func NewPopulatedSampleOneOf_Field13(r randyOne, easy bool) *SampleOneOf_Field13 {
this := &SampleOneOf_Field13{}
this.Field13 = bool(bool(r.Intn(2) == 0))
return this
}
func NewPopulatedSampleOneOf_Field14(r randyOne, easy bool) *SampleOneOf_Field14 {
this := &SampleOneOf_Field14{}
this.Field14 = string(randStringOne(r))
return this
}
func NewPopulatedSampleOneOf_Field15(r randyOne, easy bool) *SampleOneOf_Field15 {
this := &SampleOneOf_Field15{}
v1 := r.Intn(100)
this.Field15 = make([]byte, v1)
for i := 0; i < v1; i++ {
this.Field15[i] = byte(r.Intn(256))
}
return this
}
func NewPopulatedSampleOneOf_SubMessage(r randyOne, easy bool) *SampleOneOf_SubMessage {
this := &SampleOneOf_SubMessage{}
this.SubMessage = NewPopulatedSubby(r, easy)
return this
}
type randyOne interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneOne(r randyOne) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringOne(r randyOne) string {
v2 := r.Intn(100)
tmps := make([]rune, v2)
for i := 0; i < v2; i++ {
tmps[i] = randUTF8RuneOne(r)
}
return string(tmps)
}
func randUnrecognizedOne(r randyOne, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldOne(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldOne(dAtA []byte, r randyOne, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
v3 := r.Int63()
if r.Intn(2) == 0 {
v3 *= -1
}
dAtA = encodeVarintPopulateOne(dAtA, uint64(v3))
case 1:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateOne(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateOne(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateOne(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *Subby) Size() (n int) {
var l int
_ = l
l = len(m.Sub)
if l > 0 {
n += 1 + l + sovOne(uint64(l))
}
return n
}
func (m *SampleOneOf) Size() (n int) {
var l int
_ = l
if m.TestOneof != nil {
n += m.TestOneof.Size()
}
return n
}
func (m *SampleOneOf_Field1) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *SampleOneOf_Field2) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *SampleOneOf_Field3) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field3))
return n
}
func (m *SampleOneOf_Field4) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field4))
return n
}
func (m *SampleOneOf_Field5) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field5))
return n
}
func (m *SampleOneOf_Field6) Size() (n int) {
var l int
_ = l
n += 1 + sovOne(uint64(m.Field6))
return n
}
func (m *SampleOneOf_Field7) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field7))
return n
}
func (m *SampleOneOf_Field8) Size() (n int) {
var l int
_ = l
n += 1 + sozOne(uint64(m.Field8))
return n
}
func (m *SampleOneOf_Field9) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *SampleOneOf_Field10) Size() (n int) {
var l int
_ = l
n += 5
return n
}
func (m *SampleOneOf_Field11) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *SampleOneOf_Field12) Size() (n int) {
var l int
_ = l
n += 9
return n
}
func (m *SampleOneOf_Field13) Size() (n int) {
var l int
_ = l
n += 2
return n
}
func (m *SampleOneOf_Field14) Size() (n int) {
var l int
_ = l
l = len(m.Field14)
n += 1 + l + sovOne(uint64(l))
return n
}
func (m *SampleOneOf_Field15) Size() (n int) {
var l int
_ = l
if m.Field15 != nil {
l = len(m.Field15)
n += 1 + l + sovOne(uint64(l))
}
return n
}
func (m *SampleOneOf_SubMessage) Size() (n int) {
var l int
_ = l
if m.SubMessage != nil {
l = m.SubMessage.Size()
n += 2 + l + sovOne(uint64(l))
}
return n
}
func sovOne(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozOne(x uint64) (n int) {
return sovOne(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *Subby) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&Subby{`,
`Sub:` + fmt.Sprintf("%v", this.Sub) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf{`,
`TestOneof:` + fmt.Sprintf("%v", this.TestOneof) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field1) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field1{`,
`Field1:` + fmt.Sprintf("%v", this.Field1) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field2) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field2{`,
`Field2:` + fmt.Sprintf("%v", this.Field2) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field3) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field3{`,
`Field3:` + fmt.Sprintf("%v", this.Field3) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field4) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field4{`,
`Field4:` + fmt.Sprintf("%v", this.Field4) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field5) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field5{`,
`Field5:` + fmt.Sprintf("%v", this.Field5) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field6) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field6{`,
`Field6:` + fmt.Sprintf("%v", this.Field6) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field7) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field7{`,
`Field7:` + fmt.Sprintf("%v", this.Field7) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field8) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field8{`,
`Field8:` + fmt.Sprintf("%v", this.Field8) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field9) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field9{`,
`Field9:` + fmt.Sprintf("%v", this.Field9) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field10) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field10{`,
`Field10:` + fmt.Sprintf("%v", this.Field10) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field11) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field11{`,
`Field11:` + fmt.Sprintf("%v", this.Field11) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field12) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field12{`,
`Field12:` + fmt.Sprintf("%v", this.Field12) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field13) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field13{`,
`Field13:` + fmt.Sprintf("%v", this.Field13) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field14) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field14{`,
`Field14:` + fmt.Sprintf("%v", this.Field14) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_Field15) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_Field15{`,
`Field15:` + fmt.Sprintf("%v", this.Field15) + `,`,
`}`,
}, "")
return s
}
func (this *SampleOneOf_SubMessage) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&SampleOneOf_SubMessage{`,
`SubMessage:` + strings.Replace(fmt.Sprintf("%v", this.SubMessage), "Subby", "Subby", 1) + `,`,
`}`,
}, "")
return s
}
func valueToStringOne(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func (m *Subby) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: Subby: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: Subby: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Sub", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOne
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Sub = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOne(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOne
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *SampleOneOf) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: SampleOneOf: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: SampleOneOf: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field1", wireType)
}
var v uint64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 8
v = uint64(dAtA[iNdEx-8])
v |= uint64(dAtA[iNdEx-7]) << 8
v |= uint64(dAtA[iNdEx-6]) << 16
v |= uint64(dAtA[iNdEx-5]) << 24
v |= uint64(dAtA[iNdEx-4]) << 32
v |= uint64(dAtA[iNdEx-3]) << 40
v |= uint64(dAtA[iNdEx-2]) << 48
v |= uint64(dAtA[iNdEx-1]) << 56
m.TestOneof = &SampleOneOf_Field1{float64(math.Float64frombits(v))}
case 2:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field2", wireType)
}
var v uint32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 4
v = uint32(dAtA[iNdEx-4])
v |= uint32(dAtA[iNdEx-3]) << 8
v |= uint32(dAtA[iNdEx-2]) << 16
v |= uint32(dAtA[iNdEx-1]) << 24
m.TestOneof = &SampleOneOf_Field2{float32(math.Float32frombits(v))}
case 3:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field3", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &SampleOneOf_Field3{v}
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field4", wireType)
}
var v int64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &SampleOneOf_Field4{v}
case 5:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field5", wireType)
}
var v uint32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &SampleOneOf_Field5{v}
case 6:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field6", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.TestOneof = &SampleOneOf_Field6{v}
case 7:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field7", wireType)
}
var v int32
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int32(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
v = int32((uint32(v) >> 1) ^ uint32(((v&1)<<31)>>31))
m.TestOneof = &SampleOneOf_Field7{v}
case 8:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field8", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
v = (v >> 1) ^ uint64((int64(v&1)<<63)>>63)
m.TestOneof = &SampleOneOf_Field8{int64(v)}
case 9:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field9", wireType)
}
var v uint32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 4
v = uint32(dAtA[iNdEx-4])
v |= uint32(dAtA[iNdEx-3]) << 8
v |= uint32(dAtA[iNdEx-2]) << 16
v |= uint32(dAtA[iNdEx-1]) << 24
m.TestOneof = &SampleOneOf_Field9{v}
case 10:
if wireType != 5 {
return fmt.Errorf("proto: wrong wireType = %d for field Field10", wireType)
}
var v int32
if (iNdEx + 4) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 4
v = int32(dAtA[iNdEx-4])
v |= int32(dAtA[iNdEx-3]) << 8
v |= int32(dAtA[iNdEx-2]) << 16
v |= int32(dAtA[iNdEx-1]) << 24
m.TestOneof = &SampleOneOf_Field10{v}
case 11:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field11", wireType)
}
var v uint64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 8
v = uint64(dAtA[iNdEx-8])
v |= uint64(dAtA[iNdEx-7]) << 8
v |= uint64(dAtA[iNdEx-6]) << 16
v |= uint64(dAtA[iNdEx-5]) << 24
v |= uint64(dAtA[iNdEx-4]) << 32
v |= uint64(dAtA[iNdEx-3]) << 40
v |= uint64(dAtA[iNdEx-2]) << 48
v |= uint64(dAtA[iNdEx-1]) << 56
m.TestOneof = &SampleOneOf_Field11{v}
case 12:
if wireType != 1 {
return fmt.Errorf("proto: wrong wireType = %d for field Field12", wireType)
}
var v int64
if (iNdEx + 8) > l {
return io.ErrUnexpectedEOF
}
iNdEx += 8
v = int64(dAtA[iNdEx-8])
v |= int64(dAtA[iNdEx-7]) << 8
v |= int64(dAtA[iNdEx-6]) << 16
v |= int64(dAtA[iNdEx-5]) << 24
v |= int64(dAtA[iNdEx-4]) << 32
v |= int64(dAtA[iNdEx-3]) << 40
v |= int64(dAtA[iNdEx-2]) << 48
v |= int64(dAtA[iNdEx-1]) << 56
m.TestOneof = &SampleOneOf_Field12{v}
case 13:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Field13", wireType)
}
var v int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
v |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
b := bool(v != 0)
m.TestOneof = &SampleOneOf_Field13{b}
case 14:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field14", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthOne
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.TestOneof = &SampleOneOf_Field14{string(dAtA[iNdEx:postIndex])}
iNdEx = postIndex
case 15:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Field15", wireType)
}
var byteLen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
byteLen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if byteLen < 0 {
return ErrInvalidLengthOne
}
postIndex := iNdEx + byteLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := make([]byte, postIndex-iNdEx)
copy(v, dAtA[iNdEx:postIndex])
m.TestOneof = &SampleOneOf_Field15{v}
iNdEx = postIndex
case 16:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field SubMessage", wireType)
}
var msglen int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowOne
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
msglen |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
if msglen < 0 {
return ErrInvalidLengthOne
}
postIndex := iNdEx + msglen
if postIndex > l {
return io.ErrUnexpectedEOF
}
v := &Subby{}
if err := v.Unmarshal(dAtA[iNdEx:postIndex]); err != nil {
return err
}
m.TestOneof = &SampleOneOf_SubMessage{v}
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipOne(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthOne
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipOne(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOne
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOne
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOne
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
if length < 0 {
return 0, ErrInvalidLengthOne
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowOne
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipOne(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthOne = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowOne = fmt.Errorf("proto: integer overflow")
)
func init() { proto.RegisterFile("combos/both/one.proto", fileDescriptorOne) }
var fileDescriptorOne = []byte{
// 404 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0xd2, 0xbf, 0x4f, 0x1b, 0x31,
0x14, 0x07, 0x70, 0x3f, 0x8e, 0x24, 0xe0, 0x84, 0x92, 0x9e, 0x54, 0xe9, 0x95, 0xe1, 0xc9, 0x62,
0xf2, 0x42, 0xd2, 0xdc, 0x25, 0xfc, 0x58, 0x51, 0x55, 0x65, 0xa9, 0x90, 0xc2, 0x1f, 0x80, 0x30,
0x75, 0x0e, 0x24, 0xee, 0x8c, 0x7a, 0x77, 0x43, 0x37, 0xfe, 0x9c, 0x8e, 0x1d, 0xfb, 0x27, 0x30,
0x32, 0x76, 0xe8, 0xc0, 0xb9, 0x4b, 0x47, 0x46, 0xc6, 0x2a, 0x97, 0xf2, 0xbc, 0xbd, 0xaf, 0x3f,
0xf6, 0x60, 0xfb, 0x2b, 0xdf, 0x5d, 0xb9, 0xdc, 0xb8, 0x72, 0x6c, 0x5c, 0x75, 0x3d, 0x76, 0x85,
0x1d, 0xdd, 0x7d, 0x75, 0x95, 0x8b, 0x23, 0x57, 0xd8, 0xbd, 0x83, 0xec, 0xa6, 0xba, 0xae, 0xcd,
0xe8, 0xca, 0xe5, 0xe3, 0xcc, 0x65, 0x6e, 0xdc, 0x9a, 0xa9, 0x97, 0x6d, 0x6a, 0x43, 0x3b, 0xad,
0xcf, 0xec, 0xbf, 0x97, 0x9d, 0xf3, 0xda, 0x98, 0x6f, 0xf1, 0x50, 0x46, 0x65, 0x6d, 0x10, 0x14,
0xe8, 0xed, 0xc5, 0x6a, 0xdc, 0xff, 0x1d, 0xc9, 0xfe, 0xf9, 0x65, 0x7e, 0x77, 0x6b, 0xcf, 0x0a,
0x7b, 0xb6, 0x8c, 0x51, 0x76, 0x3f, 0xdd, 0xd8, 0xdb, 0x2f, 0x93, 0x76, 0x13, 0xcc, 0xc5, 0xe2,
0x7f, 0x66, 0x49, 0x70, 0x43, 0x81, 0xde, 0x60, 0x49, 0x58, 0x52, 0x8c, 0x14, 0xe8, 0x0e, 0x4b,
0xca, 0x32, 0xc5, 0x4d, 0x05, 0x3a, 0x62, 0x99, 0xb2, 0xcc, 0xb0, 0xa3, 0x40, 0xef, 0xb0, 0xcc,
0x58, 0x0e, 0xb1, 0xab, 0x40, 0x6f, 0xb2, 0x1c, 0xb2, 0x1c, 0x61, 0x4f, 0x81, 0x7e, 0xcb, 0x72,
0xc4, 0x72, 0x8c, 0x5b, 0x0a, 0x74, 0xcc, 0x72, 0xcc, 0x72, 0x82, 0xdb, 0x0a, 0x74, 0x8f, 0xe5,
0x24, 0xde, 0x93, 0xbd, 0xf5, 0xcd, 0x3e, 0xa0, 0x54, 0xa0, 0x77, 0xe7, 0x62, 0xf1, 0xba, 0x10,
0x6c, 0x82, 0x7d, 0x05, 0xba, 0x1b, 0x6c, 0x12, 0x2c, 0xc1, 0x81, 0x02, 0x3d, 0x0c, 0x96, 0x04,
0x4b, 0x71, 0x47, 0x81, 0xde, 0x0a, 0x96, 0x06, 0x9b, 0xe2, 0x9b, 0xd5, 0xfb, 0x07, 0x9b, 0x06,
0x9b, 0xe1, 0xae, 0x02, 0x3d, 0x08, 0x36, 0x8b, 0x0f, 0x64, 0xbf, 0xac, 0xcd, 0x45, 0x6e, 0xcb,
0xf2, 0x32, 0xb3, 0x38, 0x54, 0xa0, 0xfb, 0x89, 0x1c, 0xad, 0x1a, 0xd1, 0x7e, 0xea, 0x5c, 0x2c,
0x64, 0x59, 0x9b, 0xcf, 0x6b, 0x3f, 0x1d, 0x48, 0x59, 0xd9, 0xb2, 0xba, 0x70, 0x85, 0x75, 0xcb,
0xd3, 0x8f, 0x0f, 0x0d, 0x89, 0xc7, 0x86, 0xc4, 0xaf, 0x86, 0xc4, 0x53, 0x43, 0xf0, 0xdc, 0x10,
0xbc, 0x34, 0x04, 0xf7, 0x9e, 0xe0, 0xbb, 0x27, 0xf8, 0xe1, 0x09, 0x7e, 0x7a, 0x82, 0x07, 0x4f,
0xf0, 0xe8, 0x09, 0x9e, 0x3c, 0xc1, 0x5f, 0x4f, 0xe2, 0xd9, 0x13, 0xbc, 0x78, 0x12, 0xf7, 0x7f,
0x48, 0x98, 0x6e, 0x5b, 0xa3, 0xf4, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x1e, 0x42, 0xd6, 0x88,
0x93, 0x02, 0x00, 0x00,
}
| ae6rt/decap | web/vendor/github.com/gogo/protobuf/test/oneof3/combos/both/one.pb.go | GO | mit | 99,707 |
/*
* Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6350057 7025809
* @summary Test that parameters on implicit enum methods have the right kind
* @author Joseph D. Darcy
* @library /tools/javac/lib
* @modules java.compiler
* jdk.compiler
* @build JavacTestingAbstractProcessor T6350057
* @compile -processor T6350057 -proc:only TestEnum.java
*/
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.*;
import javax.lang.model.util.*;
import static javax.tools.Diagnostic.Kind.*;
public class T6350057 extends JavacTestingAbstractProcessor {
static class LocalVarAllergy extends ElementKindVisitor<Boolean, Void> {
@Override
public Boolean visitTypeAsEnum(TypeElement e, Void v) {
System.out.println("visitTypeAsEnum: " + e.getSimpleName().toString());
for(Element el: e.getEnclosedElements() )
this.visit(el);
return true;
}
@Override
public Boolean visitVariableAsLocalVariable(VariableElement e, Void v){
throw new IllegalStateException("Should not see any local variables!");
}
@Override
public Boolean visitVariableAsParameter(VariableElement e, Void v){
String senclm=e.getEnclosingElement().getEnclosingElement().getSimpleName().toString();
String sEncl = senclm+"."+e.getEnclosingElement().getSimpleName().toString();
String stype = e.asType().toString();
String name = e.getSimpleName().toString();
System.out.println("visitVariableAsParameter: " +sEncl+"." + stype + " " + name);
return true;
}
@Override
public Boolean visitExecutableAsMethod(ExecutableElement e, Void v){
String name=e.getEnclosingElement().getSimpleName().toString();
name = name + "."+e.getSimpleName().toString();
System.out.println("visitExecutableAsMethod: " + name);
for (VariableElement ve: e.getParameters())
this.visit(ve);
return true;
}
}
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnvironment) {
if (!roundEnvironment.processingOver())
for(Element element : roundEnvironment.getRootElements())
element.accept(new LocalVarAllergy(), null);
return true;
}
}
| FauxFaux/jdk9-langtools | test/tools/javac/enum/6350057/T6350057.java | Java | gpl-2.0 | 3,605 |
<?php
/**
* @package Joomla.UnitTest
* @subpackage Linkedin
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
/**
* Test class for JLinkedinPeople.
*
* @package Joomla.UnitTest
* @subpackage Linkedin
* @since 3.2.0
*/
class JLinkedinPeopleTest extends TestCase
{
/**
* @var JRegistry Options for the Linkedin object.
* @since 3.2.0
*/
protected $options;
/**
* @var JHttp Mock http object.
* @since 3.2.0
*/
protected $client;
/**
* @var JInput The input object to use in retrieving GET/POST data.
* @since 3.2.0
*/
protected $input;
/**
* @var JLinkedinPeople Object under test.
* @since 3.2.0
*/
protected $object;
/**
* @var JLinkedinOAuth Authentication object for the Twitter object.
* @since 3.2.0
*/
protected $oauth;
/**
* @var string Sample JSON string.
* @since 3.2.0
*/
protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
/**
* @var string Sample JSON string used to access out of network profiles.
* @since 3.2.0
*/
protected $outString = '{"headers": { "_total": 1, "values": [{ "name": "x-li-auth-token",
"value": "NAME_SEARCH:-Ogn" }] }, "url": "/v1/people/oAFz-3CZyv"}';
/**
* @var string Sample JSON error message.
* @since 3.2.0
*/
protected $errorString = '{"errorCode":401, "message": "Generic error"}';
/**
* Backup of the SERVER superglobal
*
* @var array
* @since 3.6
*/
protected $backupServer;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @return void
*/
protected function setUp()
{
parent::setUp();
$this->backupServer = $_SERVER;
$_SERVER['HTTP_HOST'] = 'example.com';
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0';
$_SERVER['REQUEST_URI'] = '/index.php';
$_SERVER['SCRIPT_NAME'] = '/index.php';
$key = "app_key";
$secret = "app_secret";
$my_url = "http://127.0.0.1/gsoc/joomla-platform/linkedin_test.php";
$this->options = new JRegistry;
$this->input = new JInput;
$this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock();
$this->oauth = new JLinkedinOauth($this->options, $this->client, $this->input);
$this->oauth->setToken(array('key' => $key, 'secret' => $secret));
$this->object = new JLinkedinPeople($this->options, $this->client, $this->oauth);
$this->options->set('consumer_key', $key);
$this->options->set('consumer_secret', $secret);
$this->options->set('callback', $my_url);
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @return void
*
* @see \PHPUnit\Framework\TestCase::tearDown()
* @since 3.6
*/
protected function tearDown()
{
$_SERVER = $this->backupServer;
unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object);
parent::tearDown();
}
/**
* Provides test data for request format detection.
*
* @return array
*
* @since 3.2.0
*/
public function seedIdUrl()
{
// Member ID or url
return array(
array('lcnIwDU0S6', null),
array(null, 'http://www.linkedin.com/in/dianaprajescu'),
array(null, null)
);
}
/**
* Tests the getProfile method
*
* @param string $id Member id of the profile you want.
* @param string $url The public profile URL.
*
* @return void
*
* @dataProvider seedIdUrl
* @since 3.2.0
*/
public function testGetProfile($id, $url)
{
$fields = '(id,first-name,last-name)';
$language = 'en-US';
// Set request parameters.
$data['format'] = 'json';
$path = '/v1/people/';
if ($url)
{
$path .= 'url=' . $this->oauth->safeEncode($url) . ':public';
$type = 'public';
}
else
{
$type = 'standard';
}
if ($id)
{
$path .= 'id=' . $id;
}
elseif (!$url)
{
$path .= '~';
}
$path .= ':' . $fields;
$header = array('Accept-Language' => $language);
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getProfile($id, $url, $fields, $type, $language),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getProfile method - failure
*
* @param string $id Member id of the profile you want.
* @param string $url The public profile URL.
*
* @return void
*
* @dataProvider seedIdUrl
* @since 3.2.0
* @expectedException DomainException
*/
public function testGetProfileFailure($id, $url)
{
$fields = '(id,first-name,last-name)';
$language = 'en-US';
// Set request parameters.
$data['format'] = 'json';
$path = '/v1/people/';
if ($url)
{
$path .= 'url=' . $this->oauth->safeEncode($url) . ':public';
$type = 'public';
}
else
{
$type = 'standard';
}
if ($id)
{
$path .= 'id=' . $id;
}
elseif (!$url)
{
$path .= '~';
}
$path .= ':' . $fields;
$header = array('Accept-Language' => $language);
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
$this->object->getProfile($id, $url, $fields, $type, $language);
}
/**
* Tests the getConnections method
*
* @return void
*
* @since 3.2.0
*/
public function testGetConnections()
{
$fields = '(id,first-name,last-name)';
$start = 1;
$count = 50;
$modified = 'new';
$modified_since = '1267401600000';
// Set request parameters.
$data['format'] = 'json';
$data['start'] = $start;
$data['count'] = $count;
$data['modified'] = $modified;
$data['modified-since'] = $modified_since;
$path = '/v1/people/~/connections';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->assertThat(
$this->object->getConnections($fields, $start, $count, $modified, $modified_since),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the getConnections method - failure
*
* @return void
*
* @since 3.2.0
* @expectedException DomainException
*/
public function testGetConnectionsFailure()
{
$fields = '(id,first-name,last-name)';
$start = 1;
$count = 50;
$modified = 'new';
$modified_since = '1267401600000';
// Set request parameters.
$data['format'] = 'json';
$data['start'] = $start;
$data['count'] = $count;
$data['modified'] = $modified;
$data['modified-since'] = $modified_since;
$path = '/v1/people/~/connections';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->object->getConnections($fields, $start, $count, $modified, $modified_since);
}
/**
* Provides test data for request format detection.
*
* @return array
*
* @since 3.2.0
*/
public function seedFields()
{
// Fields
return array(
array('(people:(id,first-name,last-name,api-standard-profile-request))'),
array('(people:(id,first-name,last-name))')
);
}
/**
* Tests the search method
*
* @param string $fields Request fields beyond the default ones. provide 'api-standard-profile-request' field for out of network profiles.
*
* @return void
*
* @dataProvider seedFields
* @since 3.2.0
*/
public function testSearch($fields)
{
$keywords = 'Princess';
$first_name = 'Clair';
$last_name = 'Standish';
$company_name = 'Smth';
$current_company = true;
$title = 'developer';
$current_title = true;
$school_name = 'Shermer High School';
$current_school = true;
$country_code = 'us';
$postal_code = 12345;
$distance = 500;
$facets = 'location,industry,network,language,current-company,past-company,school';
$facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345);
$start = 1;
$count = 50;
$sort = 'distance';
// Set request parameters.
$data['format'] = 'json';
$data['keywords'] = $keywords;
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$data['company-name'] = $company_name;
$data['current-company'] = $current_company;
$data['title'] = $title;
$data['current-title'] = $current_title;
$data['school-name'] = $school_name;
$data['current-school'] = $current_school;
$data['country-code'] = $country_code;
$data['postal-code'] = $postal_code;
$data['distance'] = $distance;
$data['facets'] = $facets;
$data['facet'] = array();
$data['facet'][] = 'location,' . $facet[0];
$data['facet'][] = 'industry,' . $facet[1];
$data['facet'][] = 'network,' . $facet[2];
$data['facet'][] = 'language,' . $facet[3];
$data['facet'][] = 'current-company,' . $facet[4];
$data['facet'][] = 'past-company,' . $facet[5];
$data['facet'][] = 'school,' . $facet[6];
$data['start'] = $start;
$data['count'] = $count;
$data['sort'] = $sort;
$path = '/v1/people-search';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = $this->oauth->toUrl($path, $data);
if (strpos($fields, 'api-standard-profile-request') === false)
{
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
}
else
{
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->outString;
$this->client->expects($this->at(0))
->method('get')
->with($path)
->will($this->returnValue($returnData));
$returnData = new stdClass;
$returnData->code = 200;
$returnData->body = $this->sampleString;
$path = '/v1/people/oAFz-3CZyv';
$path = $this->oauth->toUrl($path, $data);
$name = 'x-li-auth-token';
$value = 'NAME_SEARCH:-Ogn';
$header[$name] = $value;
$this->client->expects($this->at(1))
->method('get', $header)
->with($path)
->will($this->returnValue($returnData));
}
$this->assertThat(
$this->object->search(
$fields, $keywords, $first_name, $last_name, $company_name,
$current_company, $title, $current_title, $school_name, $current_school, $country_code,
$postal_code, $distance, $facets, $facet, $start, $count, $sort
),
$this->equalTo(json_decode($this->sampleString))
);
}
/**
* Tests the search method - failure
*
* @return void
*
* @since 3.2.0
* @expectedException DomainException
*/
public function testSearchFailure()
{
$fields = '(id,first-name,last-name)';
$keywords = 'Princess';
$first_name = 'Clair';
$last_name = 'Standish';
$company_name = 'Smth';
$current_company = true;
$title = 'developer';
$current_title = true;
$school_name = 'Shermer High School';
$current_school = true;
$country_code = 'us';
$postal_code = 12345;
$distance = 500;
$facets = 'location,industry,network,language,current-company,past-company,school';
$facet = array('us-84', 47, 'F', 'en', 1006, 1028, 2345);
$start = 1;
$count = 50;
$sort = 'distance';
// Set request parameters.
$data['format'] = 'json';
$data['keywords'] = $keywords;
$data['first-name'] = $first_name;
$data['last-name'] = $last_name;
$data['company-name'] = $company_name;
$data['current-company'] = $current_company;
$data['title'] = $title;
$data['current-title'] = $current_title;
$data['school-name'] = $school_name;
$data['current-school'] = $current_school;
$data['country-code'] = $country_code;
$data['postal-code'] = $postal_code;
$data['distance'] = $distance;
$data['facets'] = $facets;
$data['facet'] = array();
$data['facet'][] = 'location,' . $facet[0];
$data['facet'][] = 'industry,' . $facet[1];
$data['facet'][] = 'network,' . $facet[2];
$data['facet'][] = 'language,' . $facet[3];
$data['facet'][] = 'current-company,' . $facet[4];
$data['facet'][] = 'past-company,' . $facet[5];
$data['facet'][] = 'school,' . $facet[6];
$data['start'] = $start;
$data['count'] = $count;
$data['sort'] = $sort;
$path = '/v1/people-search';
$path .= ':' . $fields;
$returnData = new stdClass;
$returnData->code = 401;
$returnData->body = $this->errorString;
$path = $this->oauth->toUrl($path, $data);
$this->client->expects($this->once())
->method('get')
->with($path)
->will($this->returnValue($returnData));
$this->object->search(
$fields, $keywords, $first_name, $last_name, $company_name,
$current_company, $title, $current_title, $school_name, $current_school, $country_code,
$postal_code, $distance, $facets, $facet, $start, $count, $sort
);
}
}
| 810/joomla-cms | tests/unit/suites/libraries/joomla/linkedin/JLinkedinPeopleTest.php | PHP | gpl-2.0 | 13,369 |
<?php
/* Copyright (C) 2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2015 Frederic France <frederic.france@free.fr>
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/actions_fetchobject.inc.php
* \brief Code for actions on fetching object page
*/
// $action must be defined
// $object must be defined (object is loaded in this file with fetch)
// $cancel must be defined
// $id or $ref must be defined (object is loaded in this file with fetch)
if (($id > 0 || (! empty($ref) && ! in_array($action, array('create','createtask')))) && empty($cancel))
{
$ret = $object->fetch($id,$ref);
if ($ret > 0)
{
$object->fetch_thirdparty();
$id = $object->id;
}
else
{
setEventMessages($object->error, $object->errors, 'errors');
$action='';
}
}
| atm-robin/dolibarr | htdocs/core/actions_fetchobject.inc.php | PHP | gpl-3.0 | 1,522 |
// Inspired from https://github.com/tsi/inlineDisqussions
(function () {
'use strict';
var website = openerp.website,
qweb = openerp.qweb;
website.blog_discussion = openerp.Class.extend({
init: function(options) {
var self = this ;
self.discus_identifier;
var defaults = {
position: 'right',
post_id: $('#blog_post_name').attr('data-blog-id'),
content : false,
public_user: false,
};
self.settings = $.extend({}, defaults, options);
// TODO: bundlify qweb templates
website.add_template_file('/website_blog/static/src/xml/website_blog.inline.discussion.xml').then(function () {
self.do_render(self);
});
},
do_render: function(data) {
var self = this;
if ($('#discussions_wrapper').length === 0 && self.settings.content.length > 0) {
$('<div id="discussions_wrapper"></div>').insertAfter($('#blog_content'));
}
// Attach a discussion to each paragraph.
self.discussions_handler(self.settings.content);
// Hide the discussion.
$('html').click(function(event) {
if($(event.target).parents('#discussions_wrapper, .main-discussion-link-wrp').length === 0) {
self.hide_discussion();
}
if(!$(event.target).hasClass('discussion-link') && !$(event.target).parents('.popover').length){
if($('.move_discuss').length){
$('[enable_chatter_discuss=True]').removeClass('move_discuss');
$('[enable_chatter_discuss=True]').animate({
'marginLeft': "+=40%"
});
$('#discussions_wrapper').animate({
'marginLeft': "+=250px"
});
}
}
});
},
prepare_data : function(identifier, comment_count) {
var self = this;
return openerp.jsonRpc("/blogpost/get_discussion/", 'call', {
'post_id': self.settings.post_id,
'path': identifier,
'count': comment_count, //if true only get length of total comment, display on discussion thread.
})
},
prepare_multi_data : function(identifiers, comment_count) {
var self = this;
return openerp.jsonRpc("/blogpost/get_discussions/", 'call', {
'post_id': self.settings.post_id,
'paths': identifiers,
'count': comment_count, //if true only get length of total comment, display on discussion thread.
})
},
discussions_handler: function() {
var self = this;
var node_by_id = {};
$(self.settings.content).each(function(i) {
var node = $(this);
var identifier = node.attr('data-chatter-id');
if (identifier) {
node_by_id[identifier] = node;
}
});
self.prepare_multi_data(_.keys(node_by_id), true).then( function (multi_data) {
_.forEach(multi_data, function(data) {
self.prepare_discuss_link(data.val, data.path, node_by_id[data.path]);
});
});
},
prepare_discuss_link : function(data, identifier, node) {
var self = this;
var cls = data > 0 ? 'discussion-link has-comments' : 'discussion-link';
var a = $('<a class="'+ cls +' css_editable_mode_hidden" />')
.attr('data-discus-identifier', identifier)
.attr('data-discus-position', self.settings.position)
.text(data > 0 ? data : '+')
.attr('data-contentwrapper', '.mycontent')
.wrap('<div class="discussion" />')
.parent()
.appendTo('#discussions_wrapper');
a.css({
'top': node.offset().top,
'left': self.settings.position == 'right' ? node.outerWidth() + node.offset().left: node.offset().left - a.outerWidth()
});
// node.attr('data-discus-identifier', identifier)
node.mouseover(function() {
a.addClass("hovered");
}).mouseout(function() {
a.removeClass("hovered");
});
a.delegate('a.discussion-link', "click", function(e) {
e.preventDefault();
if(!$('.move_discuss').length){
$('[enable_chatter_discuss=True]').addClass('move_discuss');
$('[enable_chatter_discuss=True]').animate({
'marginLeft': "-=40%"
});
$('#discussions_wrapper').animate({
'marginLeft': "-=250px"
});
}
if ($(this).is('.active')) {
e.stopPropagation();
self.hide_discussion();
}
else {
self.get_discussion($(this), function(source) {});
}
});
},
get_discussion : function(source, callback) {
var self = this;
var identifier = source.attr('data-discus-identifier');
self.hide_discussion();
self.discus_identifier = identifier;
var elt = $('a[data-discus-identifier="'+identifier+'"]');
elt.append(qweb.render("website.blog_discussion.popover", {'identifier': identifier , 'options': self.settings}));
var comment = '';
self.prepare_data(identifier,false).then(function(data){
_.each(data, function(res){
comment += qweb.render("website.blog_discussion.comment", {'res': res});
});
$('.discussion_history').html('<ul class="media-list">'+comment+'</ul>');
self.create_popover(elt, identifier);
// Add 'active' class.
$('a.discussion-link, a.main-discussion-link').removeClass('active').filter(source).addClass('active');
elt.popover('hide').filter(source).popover('show');
callback(source);
});
},
create_popover : function(elt, identifier) {
var self = this;
elt.popover({
placement:'right',
trigger:'manual',
html:true, content:function(){
return $($(this).data('contentwrapper')).html();
}
}).parent().delegate(self).on('click','button#comment_post',function(e) {
e.stopImmediatePropagation();
self.post_discussion(identifier);
});
},
validate : function(public_user){
var comment = $(".popover textarea#inline_comment").val();
if (public_user){
var author_name = $('.popover input#author_name').val();
var author_email = $('.popover input#author_email').val();
if(!comment || !author_name || !author_email){
if (!author_name)
$('div#author_name').addClass('has-error');
else
$('div#author_name').removeClass('has-error');
if (!author_email)
$('div#author_email').addClass('has-error');
else
$('div#author_email').removeClass('has-error');
if(!comment)
$('div#inline_comment').addClass('has-error');
else
$('div#inline_comment').removeClass('has-error');
return false
}
}
else if(!comment) {
$('div#inline_comment').addClass('has-error');
return false
}
$("div#inline_comment").removeClass('has-error');
$('div#author_name').removeClass('has-error');
$('div#author_email').removeClass('has-error');
$(".popover textarea#inline_comment").val('');
$('.popover input#author_name').val('');
$('.popover input#author_email').val('');
return [comment, author_name, author_email]
},
post_discussion : function(identifier) {
var self = this;
var val = self.validate(self.settings.public_user)
if(!val) return
openerp.jsonRpc("/blogpost/post_discussion", 'call', {
'blog_post_id': self.settings.post_id,
'path': self.discus_identifier,
'comment': val[0],
'name' : val[1],
'email': val[2],
}).then(function(res){
$(".popover ul.media-list").prepend(qweb.render("website.blog_discussion.comment", {'res': res[0]}))
var ele = $('a[data-discus-identifier="'+ self.discus_identifier +'"]');
ele.text(_.isNaN(parseInt(ele.text())) ? 1 : parseInt(ele.text())+1)
ele.addClass('has-comments');
});
},
hide_discussion : function() {
var self = this;
$('a[data-discus-identifier="'+ self.discus_identifier+'"]').popover('destroy');
$('a.discussion-link').removeClass('active');
}
});
})();
| jjscarafia/odoo | addons/website_blog/static/src/js/website_blog.inline.discussion.js | JavaScript | agpl-3.0 | 9,713 |
/*
* Copyright (c) 2005-2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.event.ws.internal.builders.exceptions;
public class InvalidExpirationTimeException extends Exception {
public InvalidExpirationTimeException(String message) {
super(message);
}
public InvalidExpirationTimeException(String message, Throwable cause) {
super(message, cause);
}
} | madhawa-gunasekara/carbon-commons | components/event/org.wso2.carbon.event.ws/src/main/java/org/wso2/carbon/event/ws/internal/builders/exceptions/InvalidExpirationTimeException.java | Java | apache-2.0 | 1,026 |
require "cmd/missing"
require "formula"
require "keg"
require "language/python"
require "version"
class Volumes
def initialize
@volumes = get_mounts
end
def which path
vols = get_mounts path
# no volume found
if vols.empty?
return -1
end
vol_index = @volumes.index(vols[0])
# volume not found in volume list
if vol_index.nil?
return -1
end
return vol_index
end
def get_mounts path=nil
vols = []
# get the volume of path, if path is nil returns all volumes
args = %w[/bin/df -P]
args << path if path
Utils.popen_read(*args) do |io|
io.each_line do |line|
case line.chomp
# regex matches: /dev/disk0s2 489562928 440803616 48247312 91% /
when /^.+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]{1,3}%\s+(.+)/
vols << $1
end
end
end
return vols
end
end
class Checks
############# HELPERS
# Finds files in HOMEBREW_PREFIX *and* /usr/local.
# Specify paths relative to a prefix eg. "include/foo.h".
# Sets @found for your convenience.
def find_relative_paths *relative_paths
@found = %W[#{HOMEBREW_PREFIX} /usr/local].uniq.inject([]) do |found, prefix|
found + relative_paths.map{|f| File.join(prefix, f) }.select{|f| File.exist? f }
end
end
def inject_file_list(list, str)
list.inject(str) { |s, f| s << " #{f}\n" }
end
# Git will always be on PATH because of the wrapper script in
# Library/ENV/scm, so we check if there is a *real*
# git here to avoid multiple warnings.
def git?
return @git if instance_variable_defined?(:@git)
@git = system "git --version >/dev/null 2>&1"
end
############# END HELPERS
# Sorry for the lack of an indent here, the diff would have been unreadable.
# See https://github.com/Homebrew/homebrew/pull/9986
def check_path_for_trailing_slashes
bad_paths = ENV['PATH'].split(File::PATH_SEPARATOR).select { |p| p[-1..-1] == '/' }
return if bad_paths.empty?
s = <<-EOS.undent
Some directories in your path end in a slash.
Directories in your path should not end in a slash. This can break other
doctor checks. The following directories should be edited:
EOS
bad_paths.each{|p| s << " #{p}"}
s
end
# Installing MacGPG2 interferes with Homebrew in a big way
# https://github.com/GPGTools/MacGPG2
def check_for_macgpg2
return if File.exist? '/usr/local/MacGPG2/share/gnupg/VERSION'
suspects = %w{
/Applications/start-gpg-agent.app
/Library/Receipts/libiconv1.pkg
/usr/local/MacGPG2
}
if suspects.any? { |f| File.exist? f } then <<-EOS.undent
You may have installed MacGPG2 via the package installer.
Several other checks in this script will turn up problems, such as stray
dylibs in /usr/local and permissions issues with share and man in /usr/local/.
EOS
end
end
def __check_stray_files(dir, pattern, white_list, message)
return unless File.directory?(dir)
files = Dir.chdir(dir) {
Dir[pattern].select { |f| File.file?(f) && !File.symlink?(f) } - Dir.glob(white_list)
}.map { |file| File.join(dir, file) }
inject_file_list(files, message) unless files.empty?
end
def check_for_stray_dylibs
# Dylibs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libfuse.2.dylib", # MacFuse
"libfuse_ino64.2.dylib", # MacFuse
"libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer
"libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer
"libosxfuse_i32.2.dylib", # OSXFuse
"libosxfuse_i64.2.dylib", # OSXFuse
"libTrAPI.dylib", # TrAPI / Endpoint Security VPN
"libntfs-3g.*.dylib", # NTFS-3G
"libntfs.*.dylib", # NTFS-3G
"libublio.*.dylib", # NTFS-3G
]
__check_stray_files "/usr/local/lib", "*.dylib", white_list, <<-EOS.undent
Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected dylibs:
EOS
end
def check_for_stray_static_libs
# Static libs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update
"libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update
"libntfs-3g.a", # NTFS-3G
"libntfs.a", # NTFS-3G
"libublio.a", # NTFS-3G
]
__check_stray_files "/usr/local/lib", "*.a", white_list, <<-EOS.undent
Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected static libraries:
EOS
end
def check_for_stray_pcs
# Package-config files which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"fuse.pc", # OSXFuse/MacFuse
"macfuse.pc", # OSXFuse MacFuse compatibility layer
"osxfuse.pc", # OSXFuse
"libntfs-3g.pc", # NTFS-3G
"libublio.pc",# NTFS-3G
]
__check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<-EOS.undent
Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .pc files:
EOS
end
def check_for_stray_las
white_list = [
"libfuse.la", # MacFuse
"libfuse_ino64.la", # MacFuse
"libosxfuse_i32.la", # OSXFuse
"libosxfuse_i64.la", # OSXFuse
"libntfs-3g.la", # NTFS-3G
"libntfs.la", # NTFS-3G
"libublio.la", # NTFS-3G
]
__check_stray_files "/usr/local/lib", "*.la", white_list, <<-EOS.undent
Unbrewed .la files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .la files:
EOS
end
def check_for_stray_headers
white_list = [
"fuse.h", # MacFuse
"fuse/**/*.h", # MacFuse
"macfuse/**/*.h", # OSXFuse MacFuse compatibility layer
"osxfuse/**/*.h", # OSXFuse
"ntfs/**/*.h", # NTFS-3G
"ntfs-3g/**/*.h", # NTFS-3G
]
__check_stray_files "/usr/local/include", "**/*.h", white_list, <<-EOS.undent
Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected header files:
EOS
end
def check_for_other_package_managers
ponk = MacOS.macports_or_fink
unless ponk.empty?
<<-EOS.undent
You have MacPorts or Fink installed:
#{ponk.join(", ")}
This can cause trouble. You don't have to uninstall them, but you may want to
temporarily move them out of the way, e.g.
sudo mv /opt/local ~/macports
EOS
end
end
def check_for_broken_symlinks
broken_symlinks = []
Keg::PRUNEABLE_DIRECTORIES.select(&:directory?).each do |d|
d.find do |path|
if path.symlink? && !path.resolved_path_exists?
broken_symlinks << path
end
end
end
unless broken_symlinks.empty? then <<-EOS.undent
Broken symlinks were found. Remove them with `brew prune`:
#{broken_symlinks * "\n "}
EOS
end
end
def check_for_unsupported_osx
if MacOS.version >= "10.11" then <<-EOS.undent
You are using OS X #{MacOS.version}.
We do not provide support for this pre-release version.
You may encounter build failures or other breakage.
EOS
end
end
if MacOS.version >= "10.9"
def check_for_installed_developer_tools
unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent
No developer tools installed.
Install the Command Line Tools:
xcode-select --install
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated?
<<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from the App Store.
EOS
end
end
def check_clt_up_to_date
if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent
A newer Command Line Tools release is available.
Update them from Software Update in the App Store.
EOS
end
end
elsif MacOS.version == "10.8" || MacOS.version == "10.7"
def check_for_installed_developer_tools
unless MacOS::Xcode.installed? || MacOS::CLT.installed? then <<-EOS.undent
No developer tools installed.
You should install the Command Line Tools.
The standalone package can be obtained from
https://developer.apple.com/downloads
or it can be installed via Xcode's preferences.
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from
https://developer.apple.com/downloads
EOS
end
end
def check_clt_up_to_date
if MacOS::CLT.installed? && MacOS::CLT.outdated? then <<-EOS.undent
A newer Command Line Tools release is available.
The standalone package can be obtained from
https://developer.apple.com/downloads
or it can be installed via Xcode's preferences.
EOS
end
end
else
def check_for_installed_developer_tools
unless MacOS::Xcode.installed? then <<-EOS.undent
Xcode is not installed. Most formulae need Xcode to build.
It can be installed from
https://developer.apple.com/downloads
EOS
end
end
def check_xcode_up_to_date
if MacOS::Xcode.installed? && MacOS::Xcode.outdated? then <<-EOS.undent
Your Xcode (#{MacOS::Xcode.version}) is outdated
Please update to Xcode #{MacOS::Xcode.latest_version}.
Xcode can be updated from
https://developer.apple.com/downloads
EOS
end
end
end
def check_for_osx_gcc_installer
if (MacOS.version < "10.7" || MacOS::Xcode.version > "4.1") && \
MacOS.clang_version == "2.1"
message = <<-EOS.undent
You seem to have osx-gcc-installer installed.
Homebrew doesn't support osx-gcc-installer. It causes many builds to fail and
is an unlicensed distribution of really old Xcode files.
EOS
if MacOS.version >= :mavericks
message += <<-EOS.undent
Please run `xcode-select --install` to install the CLT.
EOS
elsif MacOS.version >= :lion
message += <<-EOS.undent
Please install the CLT or Xcode #{MacOS::Xcode.latest_version}.
EOS
else
message += <<-EOS.undent
Please install Xcode #{MacOS::Xcode.latest_version}.
EOS
end
end
end
def check_for_stray_developer_directory
# if the uninstaller script isn't there, it's a good guess neither are
# any troublesome leftover Xcode files
uninstaller = Pathname.new("/Developer/Library/uninstall-developer-folder")
if MacOS::Xcode.version >= "4.3" && uninstaller.exist? then <<-EOS.undent
You have leftover files from an older version of Xcode.
You should delete them using:
#{uninstaller}
EOS
end
end
def check_for_bad_install_name_tool
return if MacOS.version < "10.9"
libs = Pathname.new("/usr/bin/install_name_tool").dynamically_linked_libraries
# otool may not work, for example if the Xcode license hasn't been accepted yet
return if libs.empty?
unless libs.include? "/usr/lib/libxcselect.dylib" then <<-EOS.undent
You have an outdated version of /usr/bin/install_name_tool installed.
This will cause binary package installations to fail.
This can happen if you install osx-gcc-installer or RailsInstaller.
To restore it, you must reinstall OS X or restore the binary from
the OS packages.
EOS
end
end
def __check_subdir_access base
target = HOMEBREW_PREFIX+base
return unless target.exist?
cant_read = []
target.find do |d|
next unless d.directory?
cant_read << d unless d.writable_real?
end
cant_read.sort!
if cant_read.length > 0 then
s = <<-EOS.undent
Some directories in #{target} aren't writable.
This can happen if you "sudo make install" software that isn't managed
by Homebrew. If a brew tries to add locale information to one of these
directories, then the install will fail during the link step.
You should probably `chown` them:
EOS
cant_read.each{ |f| s << " #{f}\n" }
s
end
end
def check_access_share_locale
__check_subdir_access 'share/locale'
end
def check_access_share_man
__check_subdir_access 'share/man'
end
def check_access_usr_local
return unless HOMEBREW_PREFIX.to_s == '/usr/local'
unless File.writable_real?("/usr/local") then <<-EOS.undent
The /usr/local directory is not writable.
Even if this directory was writable when you installed Homebrew, other
software may change permissions on this directory. Some versions of the
"InstantOn" component of Airfoil are known to do this.
You should probably change the ownership and permissions of /usr/local
back to your user account.
EOS
end
end
def check_tmpdir_sticky_bit
world_writable = HOMEBREW_TEMP.stat.mode & 0777 == 0777
if world_writable && !HOMEBREW_TEMP.sticky? then <<-EOS.undent
#{HOMEBREW_TEMP} is world-writable but does not have the sticky bit set.
Please run "Repair Disk Permissions" in Disk Utility.
EOS
end
end
(Keg::TOP_LEVEL_DIRECTORIES + ["lib/pkgconfig"]).each do |d|
define_method("check_access_#{d.sub("/", "_")}") do
dir = HOMEBREW_PREFIX.join(d)
if dir.exist? && !dir.writable_real? then <<-EOS.undent
#{dir} isn't writable.
This can happen if you "sudo make install" software that isn't managed by
by Homebrew. If a formula tries to write a file to this directory, the
install will fail during the link step.
You should probably `chown` #{dir}
EOS
end
end
end
def check_access_site_packages
if Language::Python.homebrew_site_packages.exist? && !Language::Python.homebrew_site_packages.writable_real?
<<-EOS.undent
#{Language::Python.homebrew_site_packages} isn't writable.
This can happen if you "sudo pip install" software that isn't managed
by Homebrew. If you install a formula with Python modules, the install
will fail during the link step.
You should probably `chown` #{Language::Python.homebrew_site_packages}
EOS
end
end
def check_access_logs
if HOMEBREW_LOGS.exist? and not HOMEBREW_LOGS.writable_real?
<<-EOS.undent
#{HOMEBREW_LOGS} isn't writable.
Homebrew writes debugging logs to this location.
You should probably `chown` #{HOMEBREW_LOGS}
EOS
end
end
def check_access_cache
if HOMEBREW_CACHE.exist? && !HOMEBREW_CACHE.writable_real?
<<-EOS.undent
#{HOMEBREW_CACHE} isn't writable.
This can happen if you run `brew install` or `brew fetch` as another user.
Homebrew caches downloaded files to this location.
You should probably `chown` #{HOMEBREW_CACHE}
EOS
end
end
def check_access_cellar
if HOMEBREW_CELLAR.exist? && !HOMEBREW_CELLAR.writable_real?
<<-EOS.undent
#{HOMEBREW_CELLAR} isn't writable.
You should `chown` #{HOMEBREW_CELLAR}
EOS
end
end
def check_access_prefix_opt
opt = HOMEBREW_PREFIX.join("opt")
if opt.exist? && !opt.writable_real?
<<-EOS.undent
#{opt} isn't writable.
You should `chown` #{opt}
EOS
end
end
def check_ruby_version
ruby_version = MacOS.version >= "10.9" ? "2.0" : "1.8"
if RUBY_VERSION[/\d\.\d/] != ruby_version then <<-EOS.undent
Ruby version #{RUBY_VERSION} is unsupported on #{MacOS.version}. Homebrew
is developed and tested on Ruby #{ruby_version}, and may not work correctly
on other Rubies. Patches are accepted as long as they don't cause breakage
on supported Rubies.
EOS
end
end
def check_homebrew_prefix
unless HOMEBREW_PREFIX.to_s == '/usr/local'
<<-EOS.undent
Your Homebrew is not installed to /usr/local
You can install Homebrew anywhere you want, but some brews may only build
correctly if you install in /usr/local. Sorry!
EOS
end
end
def check_xcode_prefix
prefix = MacOS::Xcode.prefix
return if prefix.nil?
if prefix.to_s.match(' ')
<<-EOS.undent
Xcode is installed to a directory with a space in the name.
This will cause some formulae to fail to build.
EOS
end
end
def check_xcode_prefix_exists
prefix = MacOS::Xcode.prefix
return if prefix.nil?
unless prefix.exist?
<<-EOS.undent
The directory Xcode is reportedly installed to doesn't exist:
#{prefix}
You may need to `xcode-select` the proper path if you have moved Xcode.
EOS
end
end
def check_xcode_select_path
if not MacOS::CLT.installed? and not File.file? "#{MacOS.active_developer_dir}/usr/bin/xcodebuild"
path = MacOS::Xcode.bundle_path
path = '/Developer' if path.nil? or not path.directory?
<<-EOS.undent
Your Xcode is configured with an invalid path.
You should change it to the correct path:
sudo xcode-select -switch #{path}
EOS
end
end
def check_user_path_1
$seen_prefix_bin = false
$seen_prefix_sbin = false
out = nil
paths.each do |p|
case p
when '/usr/bin'
unless $seen_prefix_bin
# only show the doctor message if there are any conflicts
# rationale: a default install should not trigger any brew doctor messages
conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"].
map{ |fn| File.basename fn }.
select{ |bn| File.exist? "/usr/bin/#{bn}" }
if conflicts.size > 0
out = <<-EOS.undent
/usr/bin occurs before #{HOMEBREW_PREFIX}/bin
This means that system-provided programs will be used instead of those
provided by Homebrew. The following tools exist at both paths:
#{conflicts * "\n "}
Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin
occurs before /usr/bin. Here is a one-liner:
echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile}
EOS
end
end
when "#{HOMEBREW_PREFIX}/bin"
$seen_prefix_bin = true
when "#{HOMEBREW_PREFIX}/sbin"
$seen_prefix_sbin = true
end
end
out
end
def check_user_path_2
unless $seen_prefix_bin
<<-EOS.undent
Homebrew's bin was not found in your PATH.
Consider setting the PATH for example like so
echo 'export PATH="#{HOMEBREW_PREFIX}/bin:$PATH"' >> #{shell_profile}
EOS
end
end
def check_user_path_3
# Don't complain about sbin not being in the path if it doesn't exist
sbin = (HOMEBREW_PREFIX+'sbin')
if sbin.directory? and sbin.children.length > 0
unless $seen_prefix_sbin
<<-EOS.undent
Homebrew's sbin was not found in your PATH but you have installed
formulae that put executables in #{HOMEBREW_PREFIX}/sbin.
Consider setting the PATH for example like so
echo 'export PATH="#{HOMEBREW_PREFIX}/sbin:$PATH"' >> #{shell_profile}
EOS
end
end
end
def check_user_curlrc
if %w[CURL_HOME HOME].any?{|key| ENV[key] and File.exist? "#{ENV[key]}/.curlrc" } then <<-EOS.undent
You have a curlrc file
If you have trouble downloading packages with Homebrew, then maybe this
is the problem? If the following command doesn't work, then try removing
your curlrc:
curl http://github.com
EOS
end
end
def check_which_pkg_config
binary = which 'pkg-config'
return if binary.nil?
mono_config = Pathname.new("/usr/bin/pkg-config")
if mono_config.exist? && mono_config.realpath.to_s.include?("Mono.framework") then <<-EOS.undent
You have a non-Homebrew 'pkg-config' in your PATH:
/usr/bin/pkg-config => #{mono_config.realpath}
This was most likely created by the Mono installer. `./configure` may
have problems finding brew-installed packages using this other pkg-config.
Mono no longer installs this file as of 3.0.4. You should
`sudo rm /usr/bin/pkg-config` and upgrade to the latest version of Mono.
EOS
elsif binary.to_s != "#{HOMEBREW_PREFIX}/bin/pkg-config" then <<-EOS.undent
You have a non-Homebrew 'pkg-config' in your PATH:
#{binary}
`./configure` may have problems finding brew-installed packages using
this other pkg-config.
EOS
end
end
def check_for_gettext
find_relative_paths("lib/libgettextlib.dylib",
"lib/libintl.dylib",
"include/libintl.h")
return if @found.empty?
# Our gettext formula will be caught by check_linked_keg_only_brews
f = Formulary.factory("gettext") rescue nil
return if f and f.linked_keg.directory? and @found.all? do |path|
Pathname.new(path).realpath.to_s.start_with? "#{HOMEBREW_CELLAR}/gettext"
end
s = <<-EOS.undent_________________________________________________________72
gettext files detected at a system prefix
These files can cause compilation and link failures, especially if they
are compiled with improper architectures. Consider removing these files:
EOS
inject_file_list(@found, s)
end
def check_for_iconv
unless find_relative_paths("lib/libiconv.dylib", "include/iconv.h").empty?
if (f = Formulary.factory("libiconv") rescue nil) and f.linked_keg.directory?
if not f.keg_only? then <<-EOS.undent
A libiconv formula is installed and linked
This will break stuff. For serious. Unlink it.
EOS
else
# NOOP because: check_for_linked_keg_only_brews
end
else
s = <<-EOS.undent_________________________________________________________72
libiconv files detected at a system prefix other than /usr
Homebrew doesn't provide a libiconv formula, and expects to link against
the system version in /usr. libiconv in other prefixes can cause
compile or link failure, especially if compiled with improper
architectures. OS X itself never installs anything to /usr/local so
it was either installed by a user or some other third party software.
tl;dr: delete these files:
EOS
inject_file_list(@found, s)
end
end
end
def check_for_config_scripts
return unless HOMEBREW_CELLAR.exist?
real_cellar = HOMEBREW_CELLAR.realpath
scripts = []
whitelist = %W[
/usr/bin /usr/sbin
/usr/X11/bin /usr/X11R6/bin /opt/X11/bin
#{HOMEBREW_PREFIX}/bin #{HOMEBREW_PREFIX}/sbin
/Applications/Server.app/Contents/ServerRoot/usr/bin
/Applications/Server.app/Contents/ServerRoot/usr/sbin
].map(&:downcase)
paths.each do |p|
next if whitelist.include?(p.downcase) || !File.directory?(p)
realpath = Pathname.new(p).realpath.to_s
next if realpath.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s)
scripts += Dir.chdir(p) { Dir["*-config"] }.map { |c| File.join(p, c) }
end
unless scripts.empty?
s = <<-EOS.undent
"config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.
Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:
EOS
s << scripts.map { |f| " #{f}" }.join("\n")
end
end
def check_DYLD_vars
found = ENV.keys.grep(/^DYLD_/)
unless found.empty?
s = <<-EOS.undent
Setting DYLD_* vars can break dynamic linking.
Set variables:
EOS
s << found.map { |e| " #{e}: #{ENV.fetch(e)}\n" }.join
if found.include? 'DYLD_INSERT_LIBRARIES'
s += <<-EOS.undent
Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail.
Having this set is common if you use this software:
http://asepsis.binaryage.com/
EOS
end
s
end
end
def check_for_symlinked_cellar
return unless HOMEBREW_CELLAR.exist?
if HOMEBREW_CELLAR.symlink?
<<-EOS.undent
Symlinked Cellars can cause problems.
Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR}
which resolves to: #{HOMEBREW_CELLAR.realpath}
The recommended Homebrew installations are either:
(A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX
(B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar".
Older installations of Homebrew may have created a symlinked Cellar, but this can
cause problems when two formula install to locations that are mapped on top of each
other during the linking step.
EOS
end
end
def check_for_multiple_volumes
return unless HOMEBREW_CELLAR.exist?
volumes = Volumes.new
# Find the volumes for the TMP folder & HOMEBREW_CELLAR
real_cellar = HOMEBREW_CELLAR.realpath
tmp = Pathname.new(Dir.mktmpdir("doctor", HOMEBREW_TEMP))
real_temp = tmp.realpath.parent
where_cellar = volumes.which real_cellar
where_temp = volumes.which real_temp
Dir.delete tmp
unless where_cellar == where_temp then <<-EOS.undent
Your Cellar and TEMP directories are on different volumes.
OS X won't move relative symlinks across volumes unless the target file already
exists. Brews known to be affected by this are Git and Narwhal.
You should set the "HOMEBREW_TEMP" environmental variable to a suitable
directory on the same volume as your Cellar.
EOS
end
end
def check_filesystem_case_sensitive
volumes = Volumes.new
case_sensitive_vols = [HOMEBREW_PREFIX, HOMEBREW_REPOSITORY, HOMEBREW_CELLAR, HOMEBREW_TEMP].select do |dir|
# We select the dir as being case-sensitive if either the UPCASED or the
# downcased variant is missing.
# Of course, on a case-insensitive fs, both exist because the os reports so.
# In the rare situation when the user has indeed a downcased and an upcased
# dir (e.g. /TMP and /tmp) this check falsely thinks it is case-insensitive
# but we don't care beacuse: 1. there is more than one dir checked, 2. the
# check is not vital and 3. we would have to touch files otherwise.
upcased = Pathname.new(dir.to_s.upcase)
downcased = Pathname.new(dir.to_s.downcase)
dir.exist? && !(upcased.exist? && downcased.exist?)
end.map { |case_sensitive_dir| volumes.get_mounts(case_sensitive_dir) }.uniq
return if case_sensitive_vols.empty?
<<-EOS.undent
The filesystem on #{case_sensitive_vols.join(",")} appears to be case-sensitive.
The default OS X filesystem is case-insensitive. Please report any apparent problems.
EOS
end
def __check_git_version
# https://help.github.com/articles/https-cloning-errors
`git --version`.chomp =~ /git version ((?:\d+\.?)+)/
if $1 and Version.new($1) < Version.new("1.7.10") then <<-EOS.undent
An outdated version of Git was detected in your PATH.
Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub.
Please upgrade: brew upgrade git
EOS
end
end
def check_for_git
if git?
__check_git_version
else <<-EOS.undent
Git could not be found in your PATH.
Homebrew uses Git for several internal functions, and some formulae use Git
checkouts instead of stable tarballs. You may want to install Git:
brew install git
EOS
end
end
def check_git_newline_settings
return unless git?
autocrlf = `git config --get core.autocrlf`.chomp
if autocrlf == 'true' then <<-EOS.undent
Suspicious Git newline settings found.
The detected Git newline settings will cause checkout problems:
core.autocrlf = #{autocrlf}
If you are not routinely dealing with Windows-based projects,
consider removing these by running:
`git config --global core.autocrlf input`
EOS
end
end
def check_git_origin
return unless git? && (HOMEBREW_REPOSITORY/'.git').exist?
HOMEBREW_REPOSITORY.cd do
origin = `git config --get remote.origin.url`.strip
if origin.empty? then <<-EOS.undent
Missing git origin remote.
Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the Homebrew remote:
cd #{HOMEBREW_REPOSITORY}
git remote add origin https://github.com/Homebrew/homebrew.git
EOS
elsif origin !~ /(mxcl|Homebrew)\/homebrew(\.git)?$/ then <<-EOS.undent
Suspicious git origin remote found.
With a non-standard origin, Homebrew won't pull updates from
the main repository. The current git origin is:
#{origin}
Unless you have compelling reasons, consider setting the
origin remote to point at the main repository, located at:
https://github.com/Homebrew/homebrew.git
EOS
end
end
end
def check_for_autoconf
return unless MacOS::Xcode.provides_autotools?
autoconf = which('autoconf')
safe_autoconfs = %w[/usr/bin/autoconf /Developer/usr/bin/autoconf]
unless autoconf.nil? or safe_autoconfs.include? autoconf.to_s then <<-EOS.undent
An "autoconf" in your path blocks the Xcode-provided version at:
#{autoconf}
This custom autoconf may cause some Homebrew formulae to fail to compile.
EOS
end
end
def __check_linked_brew f
f.rack.subdirs.each do |prefix|
prefix.find do |src|
next if src == prefix
dst = HOMEBREW_PREFIX + src.relative_path_from(prefix)
return true if dst.symlink? && src == dst.resolved_path
end
end
false
end
def check_for_linked_keg_only_brews
return unless HOMEBREW_CELLAR.exist?
linked = Formula.installed.select { |f|
f.keg_only? && __check_linked_brew(f)
}
unless linked.empty?
s = <<-EOS.undent
Some keg-only formula are linked into the Cellar.
Linking a keg-only formula, such as gettext, into the cellar with
`brew link <formula>` will cause other formulae to detect them during
the `./configure` step. This may cause problems when compiling those
other formulae.
Binaries provided by keg-only formulae may override system binaries
with other strange results.
You may wish to `brew unlink` these brews:
EOS
linked.each { |f| s << " #{f.full_name}\n" }
s
end
end
def check_for_other_frameworks
# Other frameworks that are known to cause problems when present
%w{expat.framework libexpat.framework libcurl.framework}.
map{ |frmwrk| "/Library/Frameworks/#{frmwrk}" }.
select{ |frmwrk| File.exist? frmwrk }.
map do |frmwrk| <<-EOS.undent
#{frmwrk} detected
This can be picked up by CMake's build system and likely cause the build to
fail. You may need to move this file out of the way to compile CMake.
EOS
end.join
end
def check_tmpdir
tmpdir = ENV['TMPDIR']
"TMPDIR #{tmpdir.inspect} doesn't exist." unless tmpdir.nil? or File.directory? tmpdir
end
def check_missing_deps
return unless HOMEBREW_CELLAR.exist?
missing = Set.new
Homebrew.missing_deps(Formula.installed).each_value do |deps|
missing.merge(deps)
end
if missing.any? then <<-EOS.undent
Some installed formula are missing dependencies.
You should `brew install` the missing dependencies:
brew install #{missing.sort_by(&:full_name) * " "}
Run `brew missing` for more details.
EOS
end
end
def check_git_status
return unless git?
HOMEBREW_REPOSITORY.cd do
unless `git status --untracked-files=all --porcelain -- Library/Homebrew/ 2>/dev/null`.chomp.empty?
<<-EOS.undent_________________________________________________________72
You have uncommitted modifications to Homebrew
If this a surprise to you, then you should stash these modifications.
Stashing returns Homebrew to a pristine state but can be undone
should you later need to do so for some reason.
cd #{HOMEBREW_LIBRARY} && git stash && git clean -d -f
EOS
end
end
end
def check_for_enthought_python
if which "enpkg" then <<-EOS.undent
Enthought Python was found in your PATH.
This can cause build problems, as this software installs its own
copies of iconv and libxml2 into directories that are picked up by
other build systems.
EOS
end
end
def check_for_library_python
if File.exist?("/Library/Frameworks/Python.framework") then <<-EOS.undent
Python is installed at /Library/Frameworks/Python.framework
Homebrew only supports building against the System-provided Python or a
brewed Python. In particular, Pythons installed to /Library can interfere
with other software installs.
EOS
end
end
def check_for_old_homebrew_share_python_in_path
s = ''
['', '3'].map do |suffix|
if paths.include?((HOMEBREW_PREFIX/"share/python#{suffix}").to_s)
s += "#{HOMEBREW_PREFIX}/share/python#{suffix} is not needed in PATH.\n"
end
end
unless s.empty?
s += <<-EOS.undent
Formerly homebrew put Python scripts you installed via `pip` or `pip3`
(or `easy_install`) into that directory above but now it can be removed
from your PATH variable.
Python scripts will now install into #{HOMEBREW_PREFIX}/bin.
You can delete anything, except 'Extras', from the #{HOMEBREW_PREFIX}/share/python
(and #{HOMEBREW_PREFIX}/share/python3) dir and install affected Python packages
anew with `pip install --upgrade`.
EOS
end
end
def check_for_bad_python_symlink
return unless which "python"
`python -V 2>&1` =~ /Python (\d+)\./
# This won't be the right warning if we matched nothing at all
return if $1.nil?
unless $1 == "2" then <<-EOS.undent
python is symlinked to python#$1
This will confuse build scripts and in general lead to subtle breakage.
EOS
end
end
def check_for_non_prefixed_coreutils
gnubin = "#{Formulary.factory('coreutils').prefix}/libexec/gnubin"
if paths.include? gnubin then <<-EOS.undent
Putting non-prefixed coreutils in your path can cause gmp builds to fail.
EOS
end
end
def check_for_non_prefixed_findutils
default_names = Tab.for_name('findutils').with? "default-names"
if default_names then <<-EOS.undent
Putting non-prefixed findutils in your path can cause python builds to fail.
EOS
end
end
def check_for_pydistutils_cfg_in_home
if File.exist? "#{ENV['HOME']}/.pydistutils.cfg" then <<-EOS.undent
A .pydistutils.cfg file was found in $HOME, which may cause Python
builds to fail. See:
https://bugs.python.org/issue6138
https://bugs.python.org/issue4655
EOS
end
end
def check_for_outdated_homebrew
return unless git?
HOMEBREW_REPOSITORY.cd do
if File.directory? ".git"
local = `git rev-parse -q --verify refs/remotes/origin/master`.chomp
remote = /^([a-f0-9]{40})/.match(`git ls-remote origin refs/heads/master 2>/dev/null`)
if remote.nil? || local == remote[0]
return
end
end
timestamp = if File.directory? ".git"
`git log -1 --format="%ct" HEAD`.to_i
else
HOMEBREW_LIBRARY.mtime.to_i
end
if Time.now.to_i - timestamp > 60 * 60 * 24 then <<-EOS.undent
Your Homebrew is outdated.
You haven't updated for at least 24 hours. This is a long time in brewland!
To update Homebrew, run `brew update`.
EOS
end
end
end
def check_for_unlinked_but_not_keg_only
return unless HOMEBREW_CELLAR.exist?
unlinked = HOMEBREW_CELLAR.children.reject do |rack|
if not rack.directory?
true
elsif not (HOMEBREW_REPOSITORY/"Library/LinkedKegs"/rack.basename).directory?
begin
Formulary.from_rack(rack).keg_only?
rescue FormulaUnavailableError, TapFormulaAmbiguityError
false
end
else
true
end
end.map{ |pn| pn.basename }
if not unlinked.empty? then <<-EOS.undent
You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
#{unlinked * "\n "}
EOS
end
end
def check_xcode_license_approved
# If the user installs Xcode-only, they have to approve the
# license or no "xc*" tool will work.
if `/usr/bin/xcrun clang 2>&1` =~ /license/ and not $?.success? then <<-EOS.undent
You have not agreed to the Xcode license.
Builds will fail! Agree to the license by opening Xcode.app or running:
sudo xcodebuild -license
EOS
end
end
def check_for_latest_xquartz
return unless MacOS::XQuartz.version
return if MacOS::XQuartz.provided_by_apple?
installed_version = Version.new(MacOS::XQuartz.version)
latest_version = Version.new(MacOS::XQuartz.latest_version)
return if installed_version >= latest_version
<<-EOS.undent
Your XQuartz (#{installed_version}) is outdated
Please install XQuartz #{latest_version}:
https://xquartz.macosforge.org
EOS
end
def check_for_old_env_vars
if ENV["HOMEBREW_KEEP_INFO"]
<<-EOS.undent
`HOMEBREW_KEEP_INFO` is no longer used
info files are no longer deleted by default; you may
remove this environment variable.
EOS
end
end
def check_for_pth_support
homebrew_site_packages = Language::Python.homebrew_site_packages
return unless homebrew_site_packages.directory?
return if Language::Python.reads_brewed_pth_files?("python") != false
return unless Language::Python.in_sys_path?("python", homebrew_site_packages)
user_site_packages = Language::Python.user_site_packages "python"
<<-EOS.undent
Your default Python does not recognize the Homebrew site-packages
directory as a special site-packages directory, which means that .pth
files will not be followed. This means you will not be able to import
some modules after installing them with Homebrew, like wxpython. To fix
this for the current user, you can run:
mkdir -p #{user_site_packages}
echo 'import site; site.addsitedir("#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth
EOS
end
def check_for_external_cmd_name_conflict
cmds = paths.map { |p| Dir["#{p}/brew-*"] }.flatten.uniq
cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) }
cmd_map = {}
cmds.each do |cmd|
cmd_name = File.basename(cmd, ".rb")
cmd_map[cmd_name] ||= []
cmd_map[cmd_name] << cmd
end
cmd_map.reject! { |cmd_name, cmd_paths| cmd_paths.size == 1 }
return if cmd_map.empty?
s = "You have external commands with conflicting names."
cmd_map.each do |cmd_name, cmd_paths|
s += "\n\nFound command `#{cmd_name}` in following places:\n"
s += cmd_paths.map { |f| " #{f}" }.join("\n")
end
s
end
def all
methods.map(&:to_s).grep(/^check_/)
end
end # end class Checks
module Homebrew
def doctor
checks = Checks.new
if ARGV.include? '--list-checks'
puts checks.all.sort
exit
end
inject_dump_stats(checks) if ARGV.switch? 'D'
if ARGV.named.empty?
methods = checks.all.sort
methods << "check_for_linked_keg_only_brews" << "check_for_outdated_homebrew"
methods = methods.reverse.uniq.reverse
else
methods = ARGV.named
end
first_warning = true
methods.each do |method|
begin
out = checks.send(method)
rescue NoMethodError
Homebrew.failed = true
puts "No check available by the name: #{method}"
next
end
unless out.nil? or out.empty?
if first_warning
puts <<-EOS.undent
#{Tty.white}Please note that these warnings are just used to help the Homebrew maintainers
with debugging if you file an issue. If everything you use Homebrew for is
working fine: please don't worry and just ignore them. Thanks!#{Tty.reset}
EOS
end
puts
opoo out
Homebrew.failed = true
first_warning = false
end
end
puts "Your system is ready to brew." unless Homebrew.failed?
end
def inject_dump_stats checks
checks.extend Module.new {
def send(method, *)
time = Time.now
super
ensure
$times[method] = Time.now - time
end
}
$times = {}
at_exit {
puts $times.sort_by{|k, v| v }.map{|k, v| "#{k}: #{v}"}
}
end
end
| wolfd/homebrew | Library/Homebrew/cmd/doctor.rb | Ruby | bsd-2-clause | 40,730 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/corewm/window_animations.h"
#include <math.h>
#include <algorithm>
#include <vector>
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "base/stl_util.h"
#include "base/time/time.h"
#include "ui/aura/client/animation_host.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_property.h"
#include "ui/compositor/compositor_observer.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animation_sequence.h"
#include "ui/compositor/layer_animator.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/gfx/interpolated_transform.h"
#include "ui/gfx/rect_conversions.h"
#include "ui/gfx/screen.h"
#include "ui/gfx/vector2d.h"
#include "ui/gfx/vector3d_f.h"
#include "ui/views/corewm/corewm_switches.h"
#include "ui/views/corewm/window_util.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
DECLARE_WINDOW_PROPERTY_TYPE(int)
DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationType)
DECLARE_WINDOW_PROPERTY_TYPE(views::corewm::WindowVisibilityAnimationTransition)
DECLARE_WINDOW_PROPERTY_TYPE(float)
DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(VIEWS_EXPORT, bool)
using aura::Window;
using base::TimeDelta;
using ui::Layer;
namespace views {
namespace corewm {
namespace {
const float kWindowAnimation_Vertical_TranslateY = 15.f;
} // namespace
DEFINE_WINDOW_PROPERTY_KEY(int,
kWindowVisibilityAnimationTypeKey,
WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT);
DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationDurationKey, 0);
DEFINE_WINDOW_PROPERTY_KEY(WindowVisibilityAnimationTransition,
kWindowVisibilityAnimationTransitionKey,
ANIMATE_BOTH);
DEFINE_WINDOW_PROPERTY_KEY(float,
kWindowVisibilityAnimationVerticalPositionKey,
kWindowAnimation_Vertical_TranslateY);
namespace {
const int kDefaultAnimationDurationForMenuMS = 150;
const float kWindowAnimation_HideOpacity = 0.f;
const float kWindowAnimation_ShowOpacity = 1.f;
const float kWindowAnimation_TranslateFactor = 0.5f;
const float kWindowAnimation_ScaleFactor = .95f;
const int kWindowAnimation_Rotate_DurationMS = 180;
const int kWindowAnimation_Rotate_OpacityDurationPercent = 90;
const float kWindowAnimation_Rotate_TranslateY = -20.f;
const float kWindowAnimation_Rotate_PerspectiveDepth = 500.f;
const float kWindowAnimation_Rotate_DegreesX = 5.f;
const float kWindowAnimation_Rotate_ScaleFactor = .99f;
const float kWindowAnimation_Bounce_Scale = 1.02f;
const int kWindowAnimation_Bounce_DurationMS = 180;
const int kWindowAnimation_Bounce_GrowShrinkDurationPercent = 40;
base::TimeDelta GetWindowVisibilityAnimationDuration(aura::Window* window) {
int duration =
window->GetProperty(kWindowVisibilityAnimationDurationKey);
if (duration == 0 && window->type() == aura::client::WINDOW_TYPE_MENU) {
return base::TimeDelta::FromMilliseconds(
kDefaultAnimationDurationForMenuMS);
}
return TimeDelta::FromInternalValue(duration);
}
// Gets/sets the WindowVisibilityAnimationType associated with a window.
// TODO(beng): redundant/fold into method on public api?
int GetWindowVisibilityAnimationType(aura::Window* window) {
int type = window->GetProperty(kWindowVisibilityAnimationTypeKey);
if (type == WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) {
return (window->type() == aura::client::WINDOW_TYPE_MENU ||
window->type() == aura::client::WINDOW_TYPE_TOOLTIP) ?
WINDOW_VISIBILITY_ANIMATION_TYPE_FADE :
WINDOW_VISIBILITY_ANIMATION_TYPE_DROP;
}
return type;
}
// Observes a hide animation.
// A window can be hidden for a variety of reasons. Sometimes, Hide() will be
// called and life is simple. Sometimes, the window is actually bound to a
// views::Widget and that Widget is closed, and life is a little more
// complicated. When a Widget is closed the aura::Window* is actually not
// destroyed immediately - it is actually just immediately hidden and then
// destroyed when the stack unwinds. To handle this case, we start the hide
// animation immediately when the window is hidden, then when the window is
// subsequently destroyed this object acquires ownership of the window's layer,
// so that it can continue animating it until the animation completes.
// Regardless of whether or not the window is destroyed, this object deletes
// itself when the animation completes.
class HidingWindowAnimationObserver : public ui::ImplicitAnimationObserver,
public aura::WindowObserver {
public:
explicit HidingWindowAnimationObserver(aura::Window* window)
: window_(window) {
window_->AddObserver(this);
}
virtual ~HidingWindowAnimationObserver() {
STLDeleteElements(&layers_);
}
private:
// Overridden from ui::ImplicitAnimationObserver:
virtual void OnImplicitAnimationsCompleted() OVERRIDE {
// Window may have been destroyed by this point.
if (window_) {
aura::client::AnimationHost* animation_host =
aura::client::GetAnimationHost(window_);
if (animation_host)
animation_host->OnWindowHidingAnimationCompleted();
window_->RemoveObserver(this);
}
delete this;
}
// Overridden from aura::WindowObserver:
virtual void OnWindowDestroying(aura::Window* window) OVERRIDE {
DCHECK_EQ(window, window_);
DCHECK(layers_.empty());
AcquireAllLayers(window_);
// If the Widget has views with layers, then it is necessary to take
// ownership of those layers too.
views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window_);
const views::Widget* const_widget = widget;
if (widget && const_widget->GetRootView() && widget->GetContentsView())
AcquireAllViewLayers(widget->GetContentsView());
window_->RemoveObserver(this);
window_ = NULL;
}
void AcquireAllLayers(aura::Window* window) {
ui::Layer* layer = window->AcquireLayer();
DCHECK(layer);
layers_.push_back(layer);
for (aura::Window::Windows::const_iterator it = window->children().begin();
it != window->children().end();
++it)
AcquireAllLayers(*it);
}
void AcquireAllViewLayers(views::View* view) {
for (int i = 0; i < view->child_count(); ++i)
AcquireAllViewLayers(view->child_at(i));
if (view->layer()) {
ui::Layer* layer = view->RecreateLayer();
if (layer) {
layer->SuppressPaint();
layers_.push_back(layer);
}
}
}
aura::Window* window_;
std::vector<ui::Layer*> layers_;
DISALLOW_COPY_AND_ASSIGN(HidingWindowAnimationObserver);
};
void GetTransformRelativeToRoot(ui::Layer* layer, gfx::Transform* transform) {
const Layer* root = layer;
while (root->parent())
root = root->parent();
layer->GetTargetTransformRelativeTo(root, transform);
}
gfx::Rect GetLayerWorldBoundsAfterTransform(ui::Layer* layer,
const gfx::Transform& transform) {
gfx::Transform in_world = transform;
GetTransformRelativeToRoot(layer, &in_world);
gfx::RectF transformed = layer->bounds();
in_world.TransformRect(&transformed);
return gfx::ToEnclosingRect(transformed);
}
// Augment the host window so that the enclosing bounds of the full
// animation will fit inside of it.
void AugmentWindowSize(aura::Window* window,
const gfx::Transform& end_transform) {
aura::client::AnimationHost* animation_host =
aura::client::GetAnimationHost(window);
if (!animation_host)
return;
const gfx::Rect& world_at_start = window->bounds();
gfx::Rect world_at_end =
GetLayerWorldBoundsAfterTransform(window->layer(), end_transform);
gfx::Rect union_in_window_space =
gfx::UnionRects(world_at_start, world_at_end);
// Calculate the top left and bottom right deltas to be added to the window
// bounds.
gfx::Vector2d top_left_delta(world_at_start.x() - union_in_window_space.x(),
world_at_start.y() - union_in_window_space.y());
gfx::Vector2d bottom_right_delta(
union_in_window_space.x() + union_in_window_space.width() -
(world_at_start.x() + world_at_start.width()),
union_in_window_space.y() + union_in_window_space.height() -
(world_at_start.y() + world_at_start.height()));
DCHECK(top_left_delta.x() >= 0 && top_left_delta.y() >= 0 &&
bottom_right_delta.x() >= 0 && bottom_right_delta.y() >= 0);
animation_host->SetHostTransitionOffsets(top_left_delta, bottom_right_delta);
}
// Shows a window using an animation, animating its opacity from 0.f to 1.f,
// its visibility to true, and its transform from |start_transform| to
// |end_transform|.
void AnimateShowWindowCommon(aura::Window* window,
const gfx::Transform& start_transform,
const gfx::Transform& end_transform) {
window->layer()->set_delegate(window);
AugmentWindowSize(window, end_transform);
window->layer()->SetOpacity(kWindowAnimation_HideOpacity);
window->layer()->SetTransform(start_transform);
window->layer()->SetVisible(true);
{
// Property sets within this scope will be implicitly animated.
ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator());
base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window);
if (duration.ToInternalValue() > 0)
settings.SetTransitionDuration(duration);
window->layer()->SetTransform(end_transform);
window->layer()->SetOpacity(kWindowAnimation_ShowOpacity);
}
}
// Hides a window using an animation, animating its opacity from 1.f to 0.f,
// its visibility to false, and its transform to |end_transform|.
void AnimateHideWindowCommon(aura::Window* window,
const gfx::Transform& end_transform) {
AugmentWindowSize(window, end_transform);
window->layer()->set_delegate(NULL);
// Property sets within this scope will be implicitly animated.
ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator());
settings.AddObserver(new HidingWindowAnimationObserver(window));
base::TimeDelta duration = GetWindowVisibilityAnimationDuration(window);
if (duration.ToInternalValue() > 0)
settings.SetTransitionDuration(duration);
window->layer()->SetOpacity(kWindowAnimation_HideOpacity);
window->layer()->SetTransform(end_transform);
window->layer()->SetVisible(false);
}
static gfx::Transform GetScaleForWindow(aura::Window* window) {
gfx::Rect bounds = window->bounds();
gfx::Transform scale = gfx::GetScaleTransform(
gfx::Point(kWindowAnimation_TranslateFactor * bounds.width(),
kWindowAnimation_TranslateFactor * bounds.height()),
kWindowAnimation_ScaleFactor);
return scale;
}
// Show/Hide windows using a shrink animation.
void AnimateShowWindow_Drop(aura::Window* window) {
AnimateShowWindowCommon(window, GetScaleForWindow(window), gfx::Transform());
}
void AnimateHideWindow_Drop(aura::Window* window) {
AnimateHideWindowCommon(window, GetScaleForWindow(window));
}
// Show/Hide windows using a vertical Glenimation.
void AnimateShowWindow_Vertical(aura::Window* window) {
gfx::Transform transform;
transform.Translate(0, window->GetProperty(
kWindowVisibilityAnimationVerticalPositionKey));
AnimateShowWindowCommon(window, transform, gfx::Transform());
}
void AnimateHideWindow_Vertical(aura::Window* window) {
gfx::Transform transform;
transform.Translate(0, window->GetProperty(
kWindowVisibilityAnimationVerticalPositionKey));
AnimateHideWindowCommon(window, transform);
}
// Show/Hide windows using a fade.
void AnimateShowWindow_Fade(aura::Window* window) {
AnimateShowWindowCommon(window, gfx::Transform(), gfx::Transform());
}
void AnimateHideWindow_Fade(aura::Window* window) {
AnimateHideWindowCommon(window, gfx::Transform());
}
ui::LayerAnimationElement* CreateGrowShrinkElement(
aura::Window* window, bool grow) {
scoped_ptr<ui::InterpolatedTransform> scale(new ui::InterpolatedScale(
gfx::Point3F(kWindowAnimation_Bounce_Scale,
kWindowAnimation_Bounce_Scale,
1),
gfx::Point3F(1, 1, 1)));
scoped_ptr<ui::InterpolatedTransform> scale_about_pivot(
new ui::InterpolatedTransformAboutPivot(
gfx::Point(window->bounds().width() * 0.5,
window->bounds().height() * 0.5),
scale.release()));
scale_about_pivot->SetReversed(grow);
scoped_ptr<ui::LayerAnimationElement> transition(
ui::LayerAnimationElement::CreateInterpolatedTransformElement(
scale_about_pivot.release(),
base::TimeDelta::FromMilliseconds(
kWindowAnimation_Bounce_DurationMS *
kWindowAnimation_Bounce_GrowShrinkDurationPercent / 100)));
transition->set_tween_type(grow ? gfx::Tween::EASE_OUT : gfx::Tween::EASE_IN);
return transition.release();
}
void AnimateBounce(aura::Window* window) {
ui::ScopedLayerAnimationSettings scoped_settings(
window->layer()->GetAnimator());
scoped_settings.SetPreemptionStrategy(
ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);
window->layer()->set_delegate(window);
scoped_ptr<ui::LayerAnimationSequence> sequence(
new ui::LayerAnimationSequence);
sequence->AddElement(CreateGrowShrinkElement(window, true));
ui::LayerAnimationElement::AnimatableProperties paused_properties;
paused_properties.insert(ui::LayerAnimationElement::BOUNDS);
sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement(
paused_properties,
base::TimeDelta::FromMilliseconds(
kWindowAnimation_Bounce_DurationMS *
(100 - 2 * kWindowAnimation_Bounce_GrowShrinkDurationPercent) /
100)));
sequence->AddElement(CreateGrowShrinkElement(window, false));
window->layer()->GetAnimator()->StartAnimation(sequence.release());
}
void AddLayerAnimationsForRotate(aura::Window* window, bool show) {
window->layer()->set_delegate(window);
if (show)
window->layer()->SetOpacity(kWindowAnimation_HideOpacity);
base::TimeDelta duration = base::TimeDelta::FromMilliseconds(
kWindowAnimation_Rotate_DurationMS);
if (!show) {
new HidingWindowAnimationObserver(window);
window->layer()->GetAnimator()->SchedulePauseForProperties(
duration * (100 - kWindowAnimation_Rotate_OpacityDurationPercent) / 100,
ui::LayerAnimationElement::OPACITY,
-1);
}
scoped_ptr<ui::LayerAnimationElement> opacity(
ui::LayerAnimationElement::CreateOpacityElement(
show ? kWindowAnimation_ShowOpacity : kWindowAnimation_HideOpacity,
duration * kWindowAnimation_Rotate_OpacityDurationPercent / 100));
opacity->set_tween_type(gfx::Tween::EASE_IN_OUT);
window->layer()->GetAnimator()->ScheduleAnimation(
new ui::LayerAnimationSequence(opacity.release()));
float xcenter = window->bounds().width() * 0.5;
gfx::Transform transform;
transform.Translate(xcenter, 0);
transform.ApplyPerspectiveDepth(kWindowAnimation_Rotate_PerspectiveDepth);
transform.Translate(-xcenter, 0);
scoped_ptr<ui::InterpolatedTransform> perspective(
new ui::InterpolatedConstantTransform(transform));
scoped_ptr<ui::InterpolatedTransform> scale(
new ui::InterpolatedScale(1, kWindowAnimation_Rotate_ScaleFactor));
scoped_ptr<ui::InterpolatedTransform> scale_about_pivot(
new ui::InterpolatedTransformAboutPivot(
gfx::Point(xcenter, kWindowAnimation_Rotate_TranslateY),
scale.release()));
scoped_ptr<ui::InterpolatedTransform> translation(
new ui::InterpolatedTranslation(gfx::Point(), gfx::Point(
0, kWindowAnimation_Rotate_TranslateY)));
scoped_ptr<ui::InterpolatedTransform> rotation(
new ui::InterpolatedAxisAngleRotation(
gfx::Vector3dF(1, 0, 0), 0, kWindowAnimation_Rotate_DegreesX));
scale_about_pivot->SetChild(perspective.release());
translation->SetChild(scale_about_pivot.release());
rotation->SetChild(translation.release());
rotation->SetReversed(show);
scoped_ptr<ui::LayerAnimationElement> transition(
ui::LayerAnimationElement::CreateInterpolatedTransformElement(
rotation.release(), duration));
window->layer()->GetAnimator()->ScheduleAnimation(
new ui::LayerAnimationSequence(transition.release()));
}
void AnimateShowWindow_Rotate(aura::Window* window) {
AddLayerAnimationsForRotate(window, true);
}
void AnimateHideWindow_Rotate(aura::Window* window) {
AddLayerAnimationsForRotate(window, false);
}
bool AnimateShowWindow(aura::Window* window) {
if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) {
if (HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) {
// Since hide animation may have changed opacity and transform,
// reset them to show the window.
window->layer()->set_delegate(window);
window->layer()->SetOpacity(kWindowAnimation_ShowOpacity);
window->layer()->SetTransform(gfx::Transform());
}
return false;
}
switch (GetWindowVisibilityAnimationType(window)) {
case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP:
AnimateShowWindow_Drop(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL:
AnimateShowWindow_Vertical(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE:
AnimateShowWindow_Fade(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE:
AnimateShowWindow_Rotate(window);
return true;
default:
return false;
}
}
bool AnimateHideWindow(aura::Window* window) {
if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) {
if (HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) {
// Since show animation may have changed opacity and transform,
// reset them, though the change should be hidden.
window->layer()->set_delegate(NULL);
window->layer()->SetOpacity(kWindowAnimation_HideOpacity);
window->layer()->SetTransform(gfx::Transform());
}
return false;
}
switch (GetWindowVisibilityAnimationType(window)) {
case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP:
AnimateHideWindow_Drop(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL:
AnimateHideWindow_Vertical(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE:
AnimateHideWindow_Fade(window);
return true;
case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE:
AnimateHideWindow_Rotate(window);
return true;
default:
return false;
}
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// External interface
void SetWindowVisibilityAnimationType(aura::Window* window, int type) {
window->SetProperty(kWindowVisibilityAnimationTypeKey, type);
}
int GetWindowVisibilityAnimationType(aura::Window* window) {
return window->GetProperty(kWindowVisibilityAnimationTypeKey);
}
void SetWindowVisibilityAnimationTransition(
aura::Window* window,
WindowVisibilityAnimationTransition transition) {
window->SetProperty(kWindowVisibilityAnimationTransitionKey, transition);
}
bool HasWindowVisibilityAnimationTransition(
aura::Window* window,
WindowVisibilityAnimationTransition transition) {
WindowVisibilityAnimationTransition prop = window->GetProperty(
kWindowVisibilityAnimationTransitionKey);
return (prop & transition) != 0;
}
void SetWindowVisibilityAnimationDuration(aura::Window* window,
const TimeDelta& duration) {
window->SetProperty(kWindowVisibilityAnimationDurationKey,
static_cast<int>(duration.ToInternalValue()));
}
void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window,
float position) {
window->SetProperty(kWindowVisibilityAnimationVerticalPositionKey, position);
}
ui::ImplicitAnimationObserver* CreateHidingWindowAnimationObserver(
aura::Window* window) {
return new HidingWindowAnimationObserver(window);
}
bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible) {
if (WindowAnimationsDisabled(window))
return false;
if (visible)
return AnimateShowWindow(window);
// Don't start hiding the window again if it's already being hidden.
return window->layer()->GetTargetOpacity() != 0.0f &&
AnimateHideWindow(window);
}
bool AnimateWindow(aura::Window* window, WindowAnimationType type) {
switch (type) {
case WINDOW_ANIMATION_TYPE_BOUNCE:
AnimateBounce(window);
return true;
default:
NOTREACHED();
return false;
}
}
bool WindowAnimationsDisabled(aura::Window* window) {
return (window &&
window->GetProperty(aura::client::kAnimationsDisabledKey)) ||
CommandLine::ForCurrentProcess()->HasSwitch(
switches::kWindowAnimationsDisabled);
}
} // namespace corewm
} // namespace views
| DirtyUnicorns/android_external_chromium-org | ui/views/corewm/window_animations.cc | C++ | bsd-3-clause | 21,476 |
/* @flow */
function a(x: {[key: string]: ?string}, y: string): string {
if (x[y]) {
return x[y];
}
return "";
}
function b(x: {y: {[key: string]: ?string}}, z: string): string {
if (x.y[z]) {
return x.y[z];
}
return "";
}
function c(x: {[key: string]: ?string}, y: {z: string}): string {
if (x[y.z]) {
return x[y.z];
}
return "";
}
function d(x: {y: {[key: string]: ?string}}, a: {b: string}): string {
if (x.y[a.b]) {
return x.y[a.b];
}
return "";
}
function a_array(x: Array<?string>, y: number): string {
if (x[y]) {
return x[y];
}
return "";
}
function b_array(x: {y: Array<?string>}, z: number): string {
if (x.y[z]) {
return x.y[z];
}
return "";
}
function c_array(x: Array<?string>, y: {z: number}): string {
if (x[y.z]) {
return x[y.z];
}
return "";
}
function d_array(x: {y: Array<?string>}, a: {b: number}): string {
if (x.y[a.b]) {
return x.y[a.b];
}
return "";
}
// --- name-sensitive havoc ---
function c2(x: {[key: string]: ?string}, y: {z: string}): string {
if (x[y.z]) {
y.z = "HEY";
return x[y.z]; // error
}
return "";
}
function c3(x: {[key: string]: ?string}, y: {z: string, a: string}): string {
if (x[y.z]) {
y.a = "HEY";
return x[y.z]; // ok
}
return "";
}
| JohnyDays/flow | tests/refinements/property.js | JavaScript | bsd-3-clause | 1,303 |
// Copyright 2012-2015 Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package elastic
import (
"encoding/json"
"fmt"
"log"
"net/url"
"strings"
"github.com/olivere/elastic/uritemplates"
)
var (
_ = fmt.Print
_ = log.Print
_ = strings.Index
_ = uritemplates.Expand
_ = url.Parse
)
// PutMappingService allows to register specific mapping definition
// for a specific type.
// See http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-put-mapping.html.
type PutMappingService struct {
client *Client
pretty bool
typ string
index []string
masterTimeout string
ignoreUnavailable *bool
allowNoIndices *bool
expandWildcards string
ignoreConflicts *bool
timeout string
bodyJson map[string]interface{}
bodyString string
}
// NewPutMappingService creates a new PutMappingService.
func NewPutMappingService(client *Client) *PutMappingService {
return &PutMappingService{
client: client,
index: make([]string, 0),
}
}
// Index is a list of index names the mapping should be added to
// (supports wildcards); use `_all` or omit to add the mapping on all indices.
func (s *PutMappingService) Index(index ...string) *PutMappingService {
s.index = append(s.index, index...)
return s
}
// Type is the name of the document type.
func (s *PutMappingService) Type(typ string) *PutMappingService {
s.typ = typ
return s
}
// Timeout is an explicit operation timeout.
func (s *PutMappingService) Timeout(timeout string) *PutMappingService {
s.timeout = timeout
return s
}
// MasterTimeout specifies the timeout for connection to master.
func (s *PutMappingService) MasterTimeout(masterTimeout string) *PutMappingService {
s.masterTimeout = masterTimeout
return s
}
// IgnoreUnavailable indicates whether specified concrete indices should be
// ignored when unavailable (missing or closed).
func (s *PutMappingService) IgnoreUnavailable(ignoreUnavailable bool) *PutMappingService {
s.ignoreUnavailable = &ignoreUnavailable
return s
}
// AllowNoIndices indicates whether to ignore if a wildcard indices
// expression resolves into no concrete indices.
// This includes `_all` string or when no indices have been specified.
func (s *PutMappingService) AllowNoIndices(allowNoIndices bool) *PutMappingService {
s.allowNoIndices = &allowNoIndices
return s
}
// ExpandWildcards indicates whether to expand wildcard expression to
// concrete indices that are open, closed or both.
func (s *PutMappingService) ExpandWildcards(expandWildcards string) *PutMappingService {
s.expandWildcards = expandWildcards
return s
}
// IgnoreConflicts specifies whether to ignore conflicts while updating
// the mapping (default: false).
func (s *PutMappingService) IgnoreConflicts(ignoreConflicts bool) *PutMappingService {
s.ignoreConflicts = &ignoreConflicts
return s
}
// Pretty indicates that the JSON response be indented and human readable.
func (s *PutMappingService) Pretty(pretty bool) *PutMappingService {
s.pretty = pretty
return s
}
// BodyJson contains the mapping definition.
func (s *PutMappingService) BodyJson(mapping map[string]interface{}) *PutMappingService {
s.bodyJson = mapping
return s
}
// BodyString is the mapping definition serialized as a string.
func (s *PutMappingService) BodyString(mapping string) *PutMappingService {
s.bodyString = mapping
return s
}
// buildURL builds the URL for the operation.
func (s *PutMappingService) buildURL() (string, url.Values, error) {
var err error
var path string
// Build URL: Typ MUST be specified and is verified in Validate.
if len(s.index) > 0 {
path, err = uritemplates.Expand("/{index}/_mapping/{type}", map[string]string{
"index": strings.Join(s.index, ","),
"type": s.typ,
})
} else {
path, err = uritemplates.Expand("/_mapping/{type}", map[string]string{
"type": s.typ,
})
}
if err != nil {
return "", url.Values{}, err
}
// Add query string parameters
params := url.Values{}
if s.pretty {
params.Set("pretty", "1")
}
if s.ignoreUnavailable != nil {
params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
}
if s.allowNoIndices != nil {
params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
}
if s.expandWildcards != "" {
params.Set("expand_wildcards", s.expandWildcards)
}
if s.ignoreConflicts != nil {
params.Set("ignore_conflicts", fmt.Sprintf("%v", *s.ignoreConflicts))
}
if s.timeout != "" {
params.Set("timeout", s.timeout)
}
if s.masterTimeout != "" {
params.Set("master_timeout", s.masterTimeout)
}
return path, params, nil
}
// Validate checks if the operation is valid.
func (s *PutMappingService) Validate() error {
var invalid []string
if s.typ == "" {
invalid = append(invalid, "Type")
}
if s.bodyString == "" && s.bodyJson == nil {
invalid = append(invalid, "BodyJson")
}
if len(invalid) > 0 {
return fmt.Errorf("missing required fields: %v", invalid)
}
return nil
}
// Do executes the operation.
func (s *PutMappingService) Do() (*PutMappingResponse, error) {
// Check pre-conditions
if err := s.Validate(); err != nil {
return nil, err
}
// Get URL for request
path, params, err := s.buildURL()
if err != nil {
return nil, err
}
// Setup HTTP request body
var body interface{}
if s.bodyJson != nil {
body = s.bodyJson
} else {
body = s.bodyString
}
// Get HTTP response
res, err := s.client.PerformRequest("PUT", path, params, body)
if err != nil {
return nil, err
}
// Return operation response
ret := new(PutMappingResponse)
if err := json.Unmarshal(res.Body, ret); err != nil {
return nil, err
}
return ret, nil
}
// PutMappingResponse is the response of PutMappingService.Do.
type PutMappingResponse struct {
Acknowledged bool `json:"acknowledged"`
}
| seekingalpha/bosun | vendor/github.com/olivere/elastic/put_mapping.go | GO | mit | 5,940 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UICore;
namespace SlimTuneUI.CoreVis
{
[DisplayName("Hotspots")]
public partial class HotSpots : UserControl, IVisualizer
{
ProfilerWindowBase m_mainWindow;
Connection m_connection;
Snapshot m_snapshot;
//drawing stuff
Font m_functionFont = new Font(SystemFonts.DefaultFont.FontFamily, 12, FontStyle.Bold);
Font m_objectFont = new Font(SystemFonts.DefaultFont.FontFamily, 9, FontStyle.Regular);
class ListTag
{
public ListBox Right;
public double TotalTime;
}
public event EventHandler Refreshed;
public string DisplayName
{
get { return "Hotspots"; }
}
public UserControl Control
{
get { return this; }
}
public Snapshot Snapshot
{
get { return m_snapshot; }
}
public bool SupportsRefresh
{
get { return true; }
}
public HotSpots()
{
InitializeComponent();
HotspotsList.Tag = new ListTag();
}
public bool Initialize(ProfilerWindowBase mainWindow, Connection connection, Snapshot snapshot)
{
if(mainWindow == null)
throw new ArgumentNullException("mainWindow");
if(connection == null)
throw new ArgumentNullException("connection");
m_mainWindow = mainWindow;
m_connection = connection;
m_snapshot = snapshot;
UpdateHotspots();
return true;
}
public void OnClose()
{
}
public void RefreshView()
{
var rightTag = HotspotsList.Tag as ListTag;
if(rightTag != null)
RemoveList(rightTag.Right);
UpdateHotspots();
Utilities.FireEvent(this, Refreshed);
}
private void UpdateHotspots()
{
HotspotsList.Items.Clear();
using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id))
using(var tx = session.BeginTransaction())
{
//find the total time consumed
var totalQuery = session.CreateQuery("select sum(call.Time) from Call call where call.ChildId = 0");
var totalTimeFuture = totalQuery.FutureValue<double>();
//find the functions that consumed the most time-exclusive. These are hotspots.
var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = 0 order by c.Time desc");
query.SetMaxResults(20);
var hotspots = query.Future<Call>();
var totalTime = totalTimeFuture.Value;
(HotspotsList.Tag as ListTag).TotalTime = totalTime;
foreach(var call in hotspots)
{
if(call.Time / totalTime < 0.01f)
{
//less than 1% is not a hotspot, and since we're ordered by Time we can exit
break;
}
HotspotsList.Items.Add(call);
}
tx.Commit();
}
}
private bool UpdateParents(Call child, ListBox box)
{
using(var session = m_connection.DataEngine.OpenSession(m_snapshot.Id))
using(var tx = session.BeginTransaction())
{
var query = session.CreateQuery("from Call c inner join fetch c.Parent where c.ChildId = :funcId order by c.Time desc")
.SetInt32("funcId", child.Parent.Id);
var parents = query.List<Call>();
double totalTime = 0;
foreach(var call in parents)
{
if(call.ParentId == 0)
return false;
totalTime += call.Time;
box.Items.Add(call);
}
(box.Tag as ListTag).TotalTime = totalTime;
tx.Commit();
}
return true;
}
private void RefreshTimer_Tick(object sender, EventArgs e)
{
//UpdateHotspots();
}
private void RemoveList(ListBox list)
{
if(list == null)
return;
RemoveList((list.Tag as ListTag).Right);
ScrollPanel.Controls.Remove(list);
}
private void CallList_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox list = sender as ListBox;
RemoveList((list.Tag as ListTag).Right);
//create a new listbox to the right
ListBox lb = new ListBox();
lb.Size = list.Size;
lb.Location = new Point(list.Right + 4, 4);
lb.IntegralHeight = false;
lb.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left;
lb.FormattingEnabled = true;
lb.DrawMode = DrawMode.OwnerDrawFixed;
lb.ItemHeight = HotspotsList.ItemHeight;
lb.Tag = new ListTag();
lb.Format += new ListControlConvertEventHandler(CallList_Format);
lb.SelectedIndexChanged += new EventHandler(CallList_SelectedIndexChanged);
lb.DrawItem += new DrawItemEventHandler(CallList_DrawItem);
if(UpdateParents(list.SelectedItem as Call, lb))
{
ScrollPanel.Controls.Add(lb);
ScrollPanel.ScrollControlIntoView(lb);
(list.Tag as ListTag).Right = lb;
}
}
private void CallList_Format(object sender, ListControlConvertEventArgs e)
{
Call call = e.ListItem as Call;
e.Value = call.Parent.Name;
}
private void CallList_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox list = sender as ListBox;
Call item = list.Items[e.Index] as Call;
int splitIndex = item.Parent.Name.LastIndexOf('.');
string functionName = item.Parent.Name.Substring(splitIndex + 1);
string objectName = "- " + item.Parent.Name.Substring(0, splitIndex);
double percent = 100 * item.Time / (list.Tag as ListTag).TotalTime;
string functionString = string.Format("{0:0.##}%: {1}", percent, functionName);
Brush brush = Brushes.Black;
if((e.State & DrawItemState.Selected) == DrawItemState.Selected)
brush = Brushes.White;
e.DrawBackground();
e.Graphics.DrawString(functionString, m_functionFont, brush, new PointF(e.Bounds.X, e.Bounds.Y));
e.Graphics.DrawString(objectName, m_objectFont, brush, new PointF(e.Bounds.X + 4, e.Bounds.Y + 18));
e.DrawFocusRectangle();
}
}
}
| mohdmasd/slimtune | CoreVis/HotSpots.cs | C# | mit | 5,633 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\Sylius\Bundle\UserBundle\Reloader;
use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Component\User\Model\UserInterface;
use PhpSpec\ObjectBehavior;
/**
* @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
*/
class UserReloaderSpec extends ObjectBehavior
{
function let(ObjectManager $objectManager)
{
$this->beConstructedWith($objectManager);
}
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\UserBundle\Reloader\UserReloader');
}
function it_implements_user_reloader_interface()
{
$this->shouldImplement('Sylius\Bundle\UserBundle\Reloader\UserReloaderInterface');
}
function it_reloads_user($objectManager, UserInterface $user)
{
$objectManager->refresh($user)->shouldBeCalled();
$this->reloadUser($user);
}
}
| wwojcik/Sylius | src/Sylius/Bundle/UserBundle/spec/Reloader/UserReloaderSpec.php | PHP | mit | 1,079 |
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* 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.
*/
/// <reference path="../_references.ts"/>
module powerbi.visuals.sampleDataViews {
import DataViewTransform = powerbi.data.DataViewTransform;
export class SalesByCountryData extends SampleDataViews implements ISampleDataViewsMethods {
public name: string = "SalesByCountryData";
public displayName: string = "Sales By Country";
public visuals: string[] = ['default'];
private sampleData = [
[742731.43, 162066.43, 283085.78, 300263.49, 376074.57, 814724.34],
[123455.43, 40566.43, 200457.78, 5000.49, 320000.57, 450000.34]
];
private sampleMin: number = 30000;
private sampleMax: number = 1000000;
private sampleSingleData: number = 55943.67;
public getDataViews(): DataView[] {
var fieldExpr = powerbi.data.SQExprBuilder.fieldDef({ schema: 's', entity: "table1", column: "country" });
var categoryValues = ["Australia", "Canada", "France", "Germany", "United Kingdom", "United States"];
var categoryIdentities = categoryValues.map(function (value) {
var expr = powerbi.data.SQExprBuilder.equal(fieldExpr, powerbi.data.SQExprBuilder.text(value));
return powerbi.data.createDataViewScopeIdentity(expr);
});
// Metadata, describes the data columns, and provides the visual with hints
// so it can decide how to best represent the data
var dataViewMetadata: powerbi.DataViewMetadata = {
columns: [
{
displayName: 'Country',
queryName: 'Country',
type: powerbi.ValueType.fromDescriptor({ text: true })
},
{
displayName: 'Sales Amount (2014)',
isMeasure: true,
format: "$0,000.00",
queryName: 'sales1',
type: powerbi.ValueType.fromDescriptor({ numeric: true }),
objects: { dataPoint: { fill: { solid: { color: 'purple' } } } },
},
{
displayName: 'Sales Amount (2015)',
isMeasure: true,
format: "$0,000.00",
queryName: 'sales2',
type: powerbi.ValueType.fromDescriptor({ numeric: true })
}
]
};
var columns = [
{
source: dataViewMetadata.columns[1],
// Sales Amount for 2014
values: this.sampleData[0],
},
{
source: dataViewMetadata.columns[2],
// Sales Amount for 2015
values: this.sampleData[1],
}
];
var dataValues: DataViewValueColumns = DataViewTransform.createValueColumns(columns);
var tableDataValues = categoryValues.map(function (countryName, idx) {
return [countryName, columns[0].values[idx], columns[1].values[idx]];
});
return [{
metadata: dataViewMetadata,
categorical: {
categories: [{
source: dataViewMetadata.columns[0],
values: categoryValues,
identity: categoryIdentities,
}],
values: dataValues
},
table: {
rows: tableDataValues,
columns: dataViewMetadata.columns,
},
single: { value: this.sampleSingleData }
}];
}
public randomize(): void {
this.sampleData = this.sampleData.map((item) => {
return item.map(() => this.getRandomValue(this.sampleMin, this.sampleMax));
});
this.sampleSingleData = this.getRandomValue(this.sampleMin, this.sampleMax);
}
}
} | yduit/PowerBI-visuals | src/Clients/PowerBIVisualsPlayground/sampleDataViews/SalesByCountryData.ts | TypeScript | mit | 5,374 |
<?php
/**
* @package Joomla.Site
* @subpackage mod_custom
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
if ($params->def('prepare_content', 1))
{
JPluginHelper::importPlugin('content');
$module->content = JHtml::_('content.prepare', $module->content, '', 'mod_custom.content');
}
$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'), ENT_COMPAT, 'UTF-8');
require JModuleHelper::getLayoutPath('mod_custom', $params->get('layout', 'default'));
| 810/joomla-cms | modules/mod_custom/mod_custom.php | PHP | gpl-2.0 | 626 |
// license:BSD-3-Clause
// copyright-holders:Ryan Holtz
//============================================================
//
// clearreader.cpp - BGFX clear state JSON reader
//
//============================================================
#include <bgfx/bgfx.h>
#include "clearreader.h"
#include "clear.h"
clear_state* clear_reader::read_from_value(const Value& value, std::string prefix)
{
if (!validate_parameters(value, prefix))
{
return nullptr;
}
uint64_t clear_flags = 0;
uint32_t clear_color = 0;
float clear_depth = 1.0f;
uint8_t clear_stencil = 0;
if (value.HasMember("clearcolor"))
{
const Value& colors = value["clearcolor"];
for (int i = 0; i < colors.Size(); i++)
{
if (!READER_CHECK(colors[i].IsNumber(), (prefix + "clearcolor[" + std::to_string(i) + "] must be a numeric value\n").c_str())) return nullptr;
auto val = int32_t(float(colors[i].GetDouble()) * 255.0f);
if (val > 255) val = 255;
if (val < 0) val = 0;
clear_color |= val << (24 - (i * 3));
}
clear_flags |= BGFX_CLEAR_COLOR;
}
if (value.HasMember("cleardepth"))
{
get_float(value, "cleardepth", &clear_depth, &clear_depth);
clear_flags |= BGFX_CLEAR_DEPTH;
}
if (value.HasMember("clearstencil"))
{
clear_stencil = uint8_t(get_int(value, "clearstencil", clear_stencil));
clear_flags |= BGFX_CLEAR_STENCIL;
}
return new clear_state(clear_flags, clear_color, clear_depth, clear_stencil);
}
bool clear_reader::validate_parameters(const Value& value, std::string prefix)
{
if (!READER_CHECK(!value.HasMember("clearcolor") || (value["clearcolor"].IsArray() && value["clearcolor"].GetArray().Size() == 4), (prefix + "'clearcolor' must be an array of four numeric RGBA values representing the color to which to clear the color buffer\n").c_str())) return false;
if (!READER_CHECK(!value.HasMember("cleardepth") || value["cleardepth"].IsNumber(), (prefix + "'cleardepth' must be a numeric value representing the depth to which to clear the depth buffer\n").c_str())) return false;
if (!READER_CHECK(!value.HasMember("clearstencil") || value["clearstencil"].IsNumber(), (prefix + "'clearstencil' must be a numeric value representing the stencil value to which to clear the stencil buffer\n").c_str())) return false;
return true;
}
| johnparker007/mame | src/osd/modules/render/bgfx/clearreader.cpp | C++ | gpl-2.0 | 2,264 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file was automatically generated by informer-gen
package v1alpha1
import (
internalinterfaces "k8s.io/sample-apiserver/pkg/client/informers/externalversions/internalinterfaces"
)
// Interface provides access to all the informers in this group version.
type Interface interface {
// Fischers returns a FischerInformer.
Fischers() FischerInformer
// Flunders returns a FlunderInformer.
Flunders() FlunderInformer
}
type version struct {
internalinterfaces.SharedInformerFactory
}
// New returns a new Interface.
func New(f internalinterfaces.SharedInformerFactory) Interface {
return &version{f}
}
// Fischers returns a FischerInformer.
func (v *version) Fischers() FischerInformer {
return &fischerInformer{factory: v.SharedInformerFactory}
}
// Flunders returns a FlunderInformer.
func (v *version) Flunders() FlunderInformer {
return &flunderInformer{factory: v.SharedInformerFactory}
}
| shakamunyi/kubernetes | vendor/k8s.io/sample-apiserver/pkg/client/informers/externalversions/wardle/v1alpha1/interface.go | GO | apache-2.0 | 1,483 |
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.test.autoconfigure.web.servlet;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.gargoylesoftware.htmlunit.WebClient;
import org.openqa.selenium.WebDriver;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.autoconfigure.properties.PropertyMapping;
import org.springframework.boot.test.autoconfigure.properties.SkipPropertyMapping;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
/**
* Annotation that can be applied to a test class to enable and configure
* auto-configuration of {@link MockMvc}.
*
* @author Phillip Webb
* @since 1.4.0
* @see MockMvcAutoConfiguration
* @see SpringBootMockMvcBuilderCustomizer
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@ImportAutoConfiguration
@PropertyMapping("spring.test.mockmvc")
public @interface AutoConfigureMockMvc {
/**
* If filters from the application context should be registered with MockMVC. Defaults
* to {@code true}.
* @return if filters should be added
*/
boolean addFilters() default true;
/**
* How {@link MvcResult} information should be printed after each MockMVC invocation.
* @return how information is printed
*/
@PropertyMapping(skip = SkipPropertyMapping.ON_DEFAULT_VALUE)
MockMvcPrint print() default MockMvcPrint.DEFAULT;
/**
* If {@link MvcResult} information should be printed only if the test fails.
* @return {@code true} if printing only occurs on failure
*/
boolean printOnlyOnFailure() default true;
/**
* If a {@link WebClient} should be auto-configured when HtmlUnit is on the classpath.
* Defaults to {@code true}.
* @return if a {@link WebClient} is auto-configured
*/
@PropertyMapping("webclient.enabled")
boolean webClientEnabled() default true;
/**
* If a {@link WebDriver} should be auto-configured when Selenium is on the classpath.
* Defaults to {@code true}.
* @return if a {@link WebDriver} is auto-configured
*/
@PropertyMapping("webdriver.enabled")
boolean webDriverEnabled() default true;
}
| tiarebalbi/spring-boot | spring-boot-project/spring-boot-test-autoconfigure/src/main/java/org/springframework/boot/test/autoconfigure/web/servlet/AutoConfigureMockMvc.java | Java | apache-2.0 | 2,989 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: acl
version_added: "1.4"
short_description: Sets and retrieves file ACL information.
description:
- Sets and retrieves file ACL information.
options:
path:
required: true
default: null
description:
- The full path of the file or object.
aliases: ['name']
state:
required: false
default: query
choices: [ 'query', 'present', 'absent' ]
description:
- defines whether the ACL should be present or not. The C(query) state gets the current acl without changing it, for use in 'register' operations.
follow:
required: false
default: yes
choices: [ 'yes', 'no' ]
description:
- whether to follow symlinks on the path if a symlink is encountered.
default:
version_added: "1.5"
required: false
default: no
choices: [ 'yes', 'no' ]
description:
- if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if
path is a file.
entity:
version_added: "1.5"
required: false
description:
- actual user or group that the ACL applies to when matching entity types user or group are selected.
etype:
version_added: "1.5"
required: false
default: null
choices: [ 'user', 'group', 'mask', 'other' ]
description:
- the entity type of the ACL to apply, see setfacl documentation for more info.
permissions:
version_added: "1.5"
required: false
default: null
description:
- Permissions to apply/remove can be any combination of r, w and x (read, write and execute respectively)
entry:
required: false
default: null
description:
- DEPRECATED. The acl to set or remove. This must always be quoted in the form of '<etype>:<qualifier>:<perms>'. The qualifier may be empty for
some types, but the type and perms are always required. '-' can be used as placeholder when you do not care about permissions. This is now
superseded by entity, type and permissions fields.
recursive:
version_added: "2.0"
required: false
default: no
choices: [ 'yes', 'no' ]
description:
- Recursively sets the specified ACL (added in Ansible 2.0). Incompatible with C(state=query).
author:
- "Brian Coca (@bcoca)"
- "Jérémie Astori (@astorije)"
notes:
- The "acl" module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binaries are installed.
- As of Ansible 2.0, this module only supports Linux distributions.
- As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well.
'''
EXAMPLES = '''
# Grant user Joe read access to a file
- acl:
path: /etc/foo.conf
entity: joe
etype: user
permissions: r
state: present
# Removes the acl for Joe on a specific file
- acl:
path: /etc/foo.conf
entity: joe
etype: user
state: absent
# Sets default acl for joe on foo.d
- acl:
path: /etc/foo.d
entity: joe
etype: user
permissions: rw
default: yes
state: present
# Same as previous but using entry shorthand
- acl:
path: /etc/foo.d
entry: "default:user:joe:rw-"
state: present
# Obtain the acl for a specific file
- acl:
path: /etc/foo.conf
register: acl_info
'''
RETURN = '''
acl:
description: Current acl on provided path (after changes, if any)
returned: success
type: list
sample: [ "user::rwx", "group::rwx", "other::rwx" ]
'''
import os
from ansible.module_utils.basic import AnsibleModule, get_platform
from ansible.module_utils.pycompat24 import get_exception
def split_entry(entry):
''' splits entry and ensures normalized return'''
a = entry.split(':')
d = None
if entry.lower().startswith("d"):
d = True
a.pop(0)
if len(a) == 2:
a.append(None)
t, e, p = a
t = t.lower()
if t.startswith("u"):
t = "user"
elif t.startswith("g"):
t = "group"
elif t.startswith("m"):
t = "mask"
elif t.startswith("o"):
t = "other"
else:
t = None
return [d, t, e, p]
def build_entry(etype, entity, permissions=None, use_nfsv4_acls=False):
'''Builds and returns an entry string. Does not include the permissions bit if they are not provided.'''
if use_nfsv4_acls:
return ':'.join([etype, entity, permissions, 'allow'])
if permissions:
return etype + ':' + entity + ':' + permissions
else:
return etype + ':' + entity
def build_command(module, mode, path, follow, default, recursive, entry=''):
'''Builds and returns a getfacl/setfacl command.'''
if mode == 'set':
cmd = [module.get_bin_path('setfacl', True)]
cmd.append('-m "%s"' % entry)
elif mode == 'rm':
cmd = [module.get_bin_path('setfacl', True)]
cmd.append('-x "%s"' % entry)
else: # mode == 'get'
cmd = [module.get_bin_path('getfacl', True)]
# prevents absolute path warnings and removes headers
if get_platform().lower() == 'linux':
cmd.append('--omit-header')
cmd.append('--absolute-names')
if recursive:
cmd.append('--recursive')
if not follow:
if get_platform().lower() == 'linux':
cmd.append('--physical')
elif get_platform().lower() == 'freebsd':
cmd.append('-h')
if default:
if mode == 'rm':
cmd.insert(1, '-k')
else: # mode == 'set' or mode == 'get'
cmd.insert(1, '-d')
cmd.append(path)
return cmd
def acl_changed(module, cmd):
'''Returns true if the provided command affects the existing ACLs, false otherwise.'''
# FreeBSD do not have a --test flag, so by default, it is safer to always say "true"
if get_platform().lower() == 'freebsd':
return True
cmd = cmd[:] # lists are mutables so cmd would be overwritten without this
cmd.insert(1, '--test')
lines = run_acl(module, cmd)
for line in lines:
if not line.endswith('*,*'):
return True
return False
def run_acl(module, cmd, check_rc=True):
try:
(rc, out, err) = module.run_command(' '.join(cmd), check_rc=check_rc)
except Exception:
e = get_exception()
module.fail_json(msg=e.strerror)
lines = []
for l in out.splitlines():
if not l.startswith('#'):
lines.append(l.strip())
if lines and not lines[-1].split():
# trim last line only when it is empty
return lines[:-1]
else:
return lines
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(required=True, aliases=['name'], type='path'),
entry=dict(required=False, type='str'),
entity=dict(required=False, type='str', default=''),
etype=dict(
required=False,
choices=['other', 'user', 'group', 'mask'],
type='str'
),
permissions=dict(required=False, type='str'),
state=dict(
required=False,
default='query',
choices=['query', 'present', 'absent'],
type='str'
),
follow=dict(required=False, type='bool', default=True),
default=dict(required=False, type='bool', default=False),
recursive=dict(required=False, type='bool', default=False),
use_nfsv4_acls=dict(required=False, type='bool', default=False)
),
supports_check_mode=True,
)
if get_platform().lower() not in ['linux', 'freebsd']:
module.fail_json(msg="The acl module is not available on this system.")
path = module.params.get('path')
entry = module.params.get('entry')
entity = module.params.get('entity')
etype = module.params.get('etype')
permissions = module.params.get('permissions')
state = module.params.get('state')
follow = module.params.get('follow')
default = module.params.get('default')
recursive = module.params.get('recursive')
use_nfsv4_acls = module.params.get('use_nfsv4_acls')
if not os.path.exists(path):
module.fail_json(msg="Path not found or not accessible.")
if state == 'query' and recursive:
module.fail_json(msg="'recursive' MUST NOT be set when 'state=query'.")
if not entry:
if state == 'absent' and permissions:
module.fail_json(msg="'permissions' MUST NOT be set when 'state=absent'.")
if state == 'absent' and not entity:
module.fail_json(msg="'entity' MUST be set when 'state=absent'.")
if state in ['present', 'absent'] and not etype:
module.fail_json(msg="'etype' MUST be set when 'state=%s'." % state)
if entry:
if etype or entity or permissions:
module.fail_json(msg="'entry' MUST NOT be set when 'entity', 'etype' or 'permissions' are set.")
if state == 'present' and not entry.count(":") in [2, 3]:
module.fail_json(msg="'entry' MUST have 3 or 4 sections divided by ':' when 'state=present'.")
if state == 'absent' and not entry.count(":") in [1, 2]:
module.fail_json(msg="'entry' MUST have 2 or 3 sections divided by ':' when 'state=absent'.")
if state == 'query':
module.fail_json(msg="'entry' MUST NOT be set when 'state=query'.")
default_flag, etype, entity, permissions = split_entry(entry)
if default_flag is not None:
default = default_flag
if get_platform().lower() == 'freebsd':
if recursive:
module.fail_json(msg="recursive is not supported on that platform.")
changed = False
msg = ""
if state == 'present':
entry = build_entry(etype, entity, permissions, use_nfsv4_acls)
command = build_command(
module, 'set', path, follow,
default, recursive, entry
)
changed = acl_changed(module, command)
if changed and not module.check_mode:
run_acl(module, command)
msg = "%s is present" % entry
elif state == 'absent':
entry = build_entry(etype, entity, use_nfsv4_acls)
command = build_command(
module, 'rm', path, follow,
default, recursive, entry
)
changed = acl_changed(module, command)
if changed and not module.check_mode:
run_acl(module, command, False)
msg = "%s is absent" % entry
elif state == 'query':
msg = "current acl"
acl = run_acl(
module,
build_command(module, 'get', path, follow, default, recursive)
)
module.exit_json(changed=changed, msg=msg, acl=acl)
if __name__ == '__main__':
main()
| e-gob/plataforma-kioscos-autoatencion | scripts/ansible-play/.venv/lib/python2.7/site-packages/ansible/modules/files/acl.py | Python | bsd-3-clause | 11,261 |
<?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/
namespace phpbb\template;
interface template
{
/**
* Clear the cache
*
* @return \phpbb\template\template
*/
public function clear_cache();
/**
* Sets the template filenames for handles.
*
* @param array $filename_array Should be a hash of handle => filename pairs.
* @return \phpbb\template\template $this
*/
public function set_filenames(array $filename_array);
/**
* Get the style tree of the style preferred by the current user
*
* @return array Style tree, most specific first
*/
public function get_user_style();
/**
* Set style location based on (current) user's chosen style.
*
* @param array $style_directories The directories to add style paths for
* E.g. array('ext/foo/bar/styles', 'styles')
* Default: array('styles') (phpBB's style directory)
* @return \phpbb\template\template $this
*/
public function set_style($style_directories = array('styles'));
/**
* Set custom style location (able to use directory outside of phpBB).
*
* Note: Templates are still compiled to phpBB's cache directory.
*
* @param string|array $names Array of names or string of name of template(s) in inheritance tree order, used by extensions.
* @param string|array or string $paths Array of style paths, relative to current root directory
* @return \phpbb\template\template $this
*/
public function set_custom_style($names, $paths);
/**
* Clears all variables and blocks assigned to this template.
*
* @return \phpbb\template\template $this
*/
public function destroy();
/**
* Reset/empty complete block
*
* @param string $blockname Name of block to destroy
* @return \phpbb\template\template $this
*/
public function destroy_block_vars($blockname);
/**
* Display a template for provided handle.
*
* The template will be loaded and compiled, if necessary, first.
*
* This function calls hooks.
*
* @param string $handle Handle to display
* @return \phpbb\template\template $this
*/
public function display($handle);
/**
* Display the handle and assign the output to a template variable
* or return the compiled result.
*
* @param string $handle Handle to operate on
* @param string $template_var Template variable to assign compiled handle to
* @param bool $return_content If true return compiled handle, otherwise assign to $template_var
* @return \phpbb\template\template|string if $return_content is true return string of the compiled handle, otherwise return $this
*/
public function assign_display($handle, $template_var = '', $return_content = true);
/**
* Assign key variable pairs from an array
*
* @param array $vararray A hash of variable name => value pairs
* @return \phpbb\template\template $this
*/
public function assign_vars(array $vararray);
/**
* Assign a single scalar value to a single key.
*
* Value can be a string, an integer or a boolean.
*
* @param string $varname Variable name
* @param string $varval Value to assign to variable
* @return \phpbb\template\template $this
*/
public function assign_var($varname, $varval);
/**
* Append text to the string value stored in a key.
*
* Text is appended using the string concatenation operator (.).
*
* @param string $varname Variable name
* @param string $varval Value to append to variable
* @return \phpbb\template\template $this
*/
public function append_var($varname, $varval);
/**
* Assign key variable pairs from an array to a specified block
* @param string $blockname Name of block to assign $vararray to
* @param array $vararray A hash of variable name => value pairs
* @return \phpbb\template\template $this
*/
public function assign_block_vars($blockname, array $vararray);
/**
* Assign key variable pairs from an array to a whole specified block loop
* @param string $blockname Name of block to assign $block_vars_array to
* @param array $block_vars_array An array of hashes of variable name => value pairs
* @return \phpbb\template\template $this
*/
public function assign_block_vars_array($blockname, array $block_vars_array);
/**
* Change already assigned key variable pair (one-dimensional - single loop entry)
*
* An example of how to use this function:
* {@example alter_block_array.php}
*
* @param string $blockname the blockname, for example 'loop'
* @param array $vararray the var array to insert/add or merge
* @param mixed $key Key to search for
*
* array: KEY => VALUE [the key/value pair to search for within the loop to determine the correct position]
*
* int: Position [the position to change or insert at directly given]
*
* If key is false the position is set to 0
* If key is true the position is set to the last entry
*
* @param string $mode Mode to execute (valid modes are 'insert' and 'change')
*
* If insert, the vararray is inserted at the given position (position counting from zero).
* If change, the current block gets merged with the vararray (resulting in new \key/value pairs be added and existing keys be replaced by the new \value).
*
* Since counting begins by zero, inserting at the last position will result in this array: array(vararray, last positioned array)
* and inserting at position 1 will result in this array: array(first positioned array, vararray, following vars)
*
* @return bool false on error, true on success
*/
public function alter_block_array($blockname, array $vararray, $key = false, $mode = 'insert');
/**
* Get path to template for handle (required for BBCode parser)
*
* @param string $handle Handle to retrieve the source file
* @return string
*/
public function get_source_file_for_handle($handle);
}
| kivi8/ars-poetica | www/forum/phpbb/template/template.php | PHP | bsd-3-clause | 5,881 |
//##################################################################################################################
// #TOOLBAR#
/* global CMS */
(function ($) {
'use strict';
// CMS.$ will be passed for $
$(document).ready(function () {
/*!
* Toolbar
* Handles all features related to the toolbar
*/
CMS.Toolbar = new CMS.Class({
implement: [CMS.API.Helpers],
options: {
preventSwitch: false,
preventSwitchMessage: 'Switching is disabled.',
messageDelay: 2000
},
initialize: function (options) {
this.container = $('#cms-toolbar');
this.options = $.extend(true, {}, this.options, options);
this.config = CMS.config;
this.settings = CMS.settings;
// elements
this.body = $('html');
this.toolbar = this.container.find('.cms-toolbar').hide();
this.toolbarTrigger = this.container.find('.cms-toolbar-trigger');
this.navigations = this.container.find('.cms-toolbar-item-navigation');
this.buttons = this.container.find('.cms-toolbar-item-buttons');
this.switcher = this.container.find('.cms-toolbar-item-switch');
this.messages = this.container.find('.cms-messages');
this.screenBlock = this.container.find('.cms-screenblock');
// states
this.click = 'click.cms';
this.timer = function () {};
this.lockToolbar = false;
// setup initial stuff
this._setup();
// setup events
this._events();
},
// initial methods
_setup: function () {
// setup toolbar visibility, we need to reverse the options to set the correct state
(this.settings.toolbar === 'expanded') ? this._showToolbar(0, true) : this._hideToolbar(0, true);
// hide publish button
var publishBtn = $('.cms-btn-publish').parent();
publishBtn.hide();
if ($('.cms-btn-publish-active').length) {
publishBtn.show();
}
// check if debug is true
if (CMS.config.debug) {
this._debug();
}
// check if there are messages and display them
if (CMS.config.messages) {
this.openMessage(CMS.config.messages);
}
// check if there are error messages and display them
if (CMS.config.error) {
this.showError(CMS.config.error);
}
// enforce open state if user is not logged in but requests the toolbar
if (!CMS.config.auth || CMS.config.settings.version !== this.settings.version) {
this.toggleToolbar(true);
this.settings = this.setSettings(CMS.config.settings);
}
// should switcher indicate that there is an unpublished page?
if (CMS.config.publisher) {
this.openMessage(CMS.config.publisher, 'right');
setInterval(function () {
CMS.$('.cms-toolbar-item-switch').toggleClass('cms-toolbar-item-switch-highlight');
}, this.options.messageDelay);
}
// open sideframe if it was previously opened
if (this.settings.sideframe.url) {
var sideframe = new CMS.Sideframe();
sideframe.open(this.settings.sideframe.url, false);
}
// if there is a screenblock, do some resize magic
if (this.screenBlock.length) {
this._screenBlock();
}
// add toolbar ready class to body and fire event
this.body.addClass('cms-ready');
$(document).trigger('cms-ready');
},
_events: function () {
var that = this;
// attach event to the trigger handler
this.toolbarTrigger.bind(this.click, function (e) {
e.preventDefault();
that.toggleToolbar();
});
// attach event to the navigation elements
this.navigations.each(function () {
var item = $(this);
var lists = item.find('li');
var root = 'cms-toolbar-item-navigation';
var hover = 'cms-toolbar-item-navigation-hover';
var disabled = 'cms-toolbar-item-navigation-disabled';
var children = 'cms-toolbar-item-navigation-children';
// remove events from first level
item.find('a').bind(that.click, function (e) {
e.preventDefault();
if ($(this).attr('href') !== '' &&
$(this).attr('href') !== '#' &&
!$(this).parent().hasClass(disabled) &&
!$(this).parent().hasClass(disabled)) {
that._delegate($(this));
reset();
return false;
}
});
// handle click states
lists.bind(that.click, function (e) {
e.stopPropagation();
var el = $(this);
// close if el is first item
if (el.parent().hasClass(root) && el.hasClass(hover) || el.hasClass(disabled)) {
reset();
return false;
} else {
reset();
el.addClass(hover);
}
// activate hover selection
item.find('> li').bind('mouseenter', function () {
// cancel if item is already active
if ($(this).hasClass(hover)) {
return false;
}
$(this).trigger(that.click);
});
// create the document event
$(document).bind(that.click, reset);
});
// attach hover
lists.find('li').bind('mouseenter mouseleave', function () {
var el = $(this);
var parent = el.closest('.cms-toolbar-item-navigation-children')
.add(el.parents('.cms-toolbar-item-navigation-children'));
var hasChildren = el.hasClass(children) || parent.length;
// do not attach hover effect if disabled
// cancel event if element has already hover class
if (el.hasClass(disabled) || el.hasClass(hover)) {
return false;
}
// reset
lists.find('li').removeClass(hover);
// add hover effect
el.addClass(hover);
// handle children elements
if (hasChildren) {
el.find('> ul').show();
// add parent class
parent.addClass(hover);
} else {
lists.find('ul ul').hide();
}
// Remove stale submenus
el.siblings().find('> ul').hide();
});
// fix leave event
lists.find('> ul').bind('mouseleave', function () {
lists.find('li').removeClass(hover);
});
// removes classes and events
function reset() {
lists.removeClass(hover);
lists.find('ul ul').hide();
item.find('> li').unbind('mouseenter');
$(document).unbind(that.click);
}
});
// attach event to the switcher elements
this.switcher.each(function () {
$(this).bind(that.click, function (e) {
e.preventDefault();
that._setSwitcher($(e.currentTarget));
});
});
// attach event for first page publish
this.buttons.each(function () {
var btn = $(this);
// in case the button has a data-rel attribute
if (btn.find('a').attr('data-rel')) {
btn.on('click', function (e) {
e.preventDefault();
that._delegate($(this).find('a'));
});
}
// in case of the publish button
btn.find('.cms-publish-page').bind(that.click, function (e) {
if (!confirm(that.config.lang.publish)) {
e.preventDefault();
}
});
btn.find('.cms-btn-publish').bind(that.click, function (e) {
e.preventDefault();
// send post request to prevent xss attacks
$.ajax({
'type': 'post',
'url': $(this).prop('href'),
'data': {
'csrfmiddlewaretoken': CMS.config.csrf
},
'success': function () {
CMS.API.Helpers.reloadBrowser();
},
'error': function (request) {
throw new Error(request);
}
});
});
});
},
// public methods
toggleToolbar: function (show) {
// overwrite state when provided
if (show) {
this.settings.toolbar = 'collapsed';
}
// toggle bar
(this.settings.toolbar === 'collapsed') ? this._showToolbar(200) : this._hideToolbar(200);
},
openMessage: function (msg, dir, delay, error) {
// set toolbar freeze
this._lock(true);
// add content to element
this.messages.find('.cms-messages-inner').html(msg);
// clear timeout
clearTimeout(this.timer);
// determine width
var that = this;
var width = 320;
var height = this.messages.outerHeight(true);
var top = this.toolbar.outerHeight(true);
var close = this.messages.find('.cms-messages-close');
close.hide();
close.bind(this.click, function () {
that.closeMessage();
});
// set top to 0 if toolbar is collapsed
if (this.settings.toolbar === 'collapsed') {
top = 0;
}
// do we need to add debug styles?
if (this.config.debug) {
top = top + 5;
}
// set correct position and show
this.messages.css('top', -height).show();
// error handling
this.messages.removeClass('cms-messages-error');
if (error) {
this.messages.addClass('cms-messages-error');
}
// dir should be left, center, right
dir = dir || 'center';
// set correct direction and animation
switch (dir) {
case 'left':
this.messages.css({
'top': top,
'left': -width,
'right': 'auto',
'margin-left': 0
});
this.messages.animate({ 'left': 0 });
break;
case 'right':
this.messages.css({
'top': top,
'right': -width,
'left': 'auto',
'margin-left': 0
});
this.messages.animate({ 'right': 0 });
break;
default:
this.messages.css({
'left': '50%',
'right': 'auto',
'margin-left': -(width / 2)
});
this.messages.animate({ 'top': top });
}
// cancel autohide if delay is 0
if (delay === 0) {
close.show();
return false;
}
// add delay to hide
this.timer = setTimeout(function () {
that.closeMessage();
}, delay || this.options.messageDelay);
},
closeMessage: function () {
this.messages.fadeOut(300);
// unlock toolbar
this._lock(false);
},
openAjax: function (url, post, text, callback, onSuccess) {
var that = this;
// check if we have a confirmation text
var question = (text) ? confirm(text) : true;
// cancel if question has been denied
if (!question) {
return false;
}
// set loader
this._loader(true);
$.ajax({
'type': 'POST',
'url': url,
'data': (post) ? JSON.parse(post) : {},
'success': function (response) {
CMS.API.locked = false;
if (callback) {
callback(that, response);
that._loader(false);
} else if (onSuccess) {
CMS.API.Helpers.reloadBrowser(onSuccess, false, true);
} else {
// reload
CMS.API.Helpers.reloadBrowser(false, false, true);
}
},
'error': function (jqXHR) {
CMS.API.locked = false;
that.showError(jqXHR.response + ' | ' + jqXHR.status + ' ' + jqXHR.statusText);
}
});
},
showError: function (msg, reload) {
this.openMessage(msg, 'center', 0, true);
// force reload if param is passed
if (reload) {
CMS.API.Helpers.reloadBrowser(false, this.options.messageDelay);
}
},
// private methods
_showToolbar: function (speed, init) {
this.toolbarTrigger.addClass('cms-toolbar-trigger-expanded');
this.toolbar.slideDown(speed);
// animate html
this.body.animate({ 'margin-top': (this.config.debug) ? 35 : 30 }, (init) ? 0 : speed, function () {
$(this).addClass('cms-toolbar-expanded');
});
// set messages top to toolbar height
this.messages.css('top', 31);
// set new settings
this.settings.toolbar = 'expanded';
if (!init) {
this.settings = this.setSettings(this.settings);
}
},
_hideToolbar: function (speed, init) {
// cancel if sideframe is active
if (this.lockToolbar) {
return false;
}
this.toolbarTrigger.removeClass('cms-toolbar-trigger-expanded');
this.toolbar.slideUp(speed);
// animate html
this.body.removeClass('cms-toolbar-expanded')
.animate({ 'margin-top': (this.config.debug) ? 5 : 0 }, speed);
// set messages top to 0
this.messages.css('top', 0);
// set new settings
this.settings.toolbar = 'collapsed';
if (!init) {
this.settings = this.setSettings(this.settings);
}
},
_setSwitcher: function (el) {
// save local vars
var active = el.hasClass('cms-toolbar-item-switch-active');
var anchor = el.find('a');
var knob = el.find('.cms-toolbar-item-switch-knob');
var duration = 300;
// prevent if switchopstion is passed
if (this.options.preventSwitch) {
this.openMessage(this.options.preventSwitchMessage, 'right');
return false;
}
// determin what to trigger
if (active) {
knob.animate({
'right': anchor.outerWidth(true) - (knob.outerWidth(true) + 2)
}, duration);
// move anchor behind the knob
anchor.css('z-index', 1).animate({
'padding-top': 6,
'padding-right': 14,
'padding-bottom': 4,
'padding-left': 28
}, duration);
} else {
knob.animate({
'left': anchor.outerWidth(true) - (knob.outerWidth(true) + 2)
}, duration);
// move anchor behind the knob
anchor.css('z-index', 1).animate({
'padding-top': 6,
'padding-right': 28,
'padding-bottom': 4,
'padding-left': 14
}, duration);
}
// reload
setTimeout(function () {
window.location.href = anchor.attr('href');
}, duration);
},
_delegate: function (el) {
// save local vars
var target = el.data('rel');
switch (target) {
case 'modal':
var modal = new CMS.Modal({'onClose': el.data('on-close')});
modal.open(el.attr('href'), el.data('name'));
break;
case 'message':
this.openMessage(el.data('text'));
break;
case 'sideframe':
var sideframe = new CMS.Sideframe({'onClose': el.data('on-close')});
sideframe.open(el.attr('href'), true);
break;
case 'ajax':
this.openAjax(el.attr('href'), JSON.stringify(
el.data('post')), el.data('text'), null, el.data('on-success')
);
break;
default:
window.location.href = el.attr('href');
}
},
_lock: function (lock) {
if (lock) {
this.lockToolbar = true;
// make button look disabled
this.toolbarTrigger.css('opacity', 0.2);
} else {
this.lockToolbar = false;
// make button look disabled
this.toolbarTrigger.css('opacity', 1);
}
},
_loader: function (loader) {
if (loader) {
this.toolbarTrigger.addClass('cms-toolbar-loader');
} else {
this.toolbarTrigger.removeClass('cms-toolbar-loader');
}
},
_debug: function () {
var that = this;
var timeout = 1000;
var timer = function () {};
// bind message event
var debug = this.container.find('.cms-debug-bar');
debug.bind('mouseenter mouseleave', function (e) {
clearTimeout(timer);
if (e.type === 'mouseenter') {
timer = setTimeout(function () {
that.openMessage(that.config.lang.debug);
}, timeout);
}
});
},
_screenBlock: function () {
var interval = 20;
var blocker = this.screenBlock;
var sideframe = $('.cms-sideframe');
// automatically resize screenblock window according to given attributes
$(window).on('resize.cms.screenblock', function () {
var width = $(this).width() - sideframe.width();
blocker.css({
'width': width,
'height': $(window).height()
});
}).trigger('resize');
// set update interval
setInterval(function () {
$(window).trigger('resize.cms.screenblock');
}, interval);
}
});
});
})(CMS.$);
| josjevv/django-cms | cms/static/cms/js/modules/cms.toolbar.js | JavaScript | bsd-3-clause | 22,476 |
from __future__ import absolute_import
import psycopg2 as Database
# Some of these imports are unused, but they are inherited from other engines
# and should be available as part of the backend ``base.py`` namespace.
from django.db.backends.postgresql_psycopg2.base import ( # NOQA
DatabaseWrapper, DatabaseFeatures, DatabaseOperations, DatabaseClient,
DatabaseCreation, DatabaseIntrospection
)
from .decorators import (
capture_transaction_exceptions, auto_reconnect_cursor,
auto_reconnect_connection, less_shitty_error_messages
)
__all__ = ('DatabaseWrapper', 'DatabaseFeatures', 'DatabaseOperations',
'DatabaseOperations', 'DatabaseClient', 'DatabaseCreation',
'DatabaseIntrospection')
class CursorWrapper(object):
"""
A wrapper around the postgresql_psycopg2 backend which handles various events
from cursors, such as auto reconnects and lazy time zone evaluation.
"""
def __init__(self, db, cursor):
self.db = db
self.cursor = cursor
def __getattr__(self, attr):
return getattr(self.cursor, attr)
def __iter__(self):
return iter(self.cursor)
@capture_transaction_exceptions
@auto_reconnect_cursor
@less_shitty_error_messages
def execute(self, sql, params=None):
if params is not None:
return self.cursor.execute(sql, params)
return self.cursor.execute(sql)
@capture_transaction_exceptions
@auto_reconnect_cursor
@less_shitty_error_messages
def executemany(self, sql, paramlist=()):
return self.cursor.executemany(sql, paramlist)
class DatabaseWrapper(DatabaseWrapper):
@auto_reconnect_connection
def _set_isolation_level(self, level):
return super(DatabaseWrapper, self)._set_isolation_level(level)
@auto_reconnect_connection
def _cursor(self, *args, **kwargs):
cursor = super(DatabaseWrapper, self)._cursor()
return CursorWrapper(self, cursor)
def close(self, reconnect=False):
"""
This ensures we dont error if the connection has already been closed.
"""
if self.connection is not None:
if not self.connection.closed:
try:
self.connection.close()
except Database.InterfaceError:
# connection was already closed by something
# like pgbouncer idle timeout.
pass
self.connection = None
class DatabaseFeatures(DatabaseFeatures):
can_return_id_from_insert = True
def __init__(self, connection):
self.connection = connection
| Kryz/sentry | src/sentry/db/postgres/base.py | Python | bsd-3-clause | 2,640 |
import foo from "foo";
import {default as foo2} from "foo";
| hawkrives/6to5 | test/fixtures/transformation/es6-modules-umd/imports-default/actual.js | JavaScript | mit | 60 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-onclickoutside"), require("moment"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-onclickoutside", "moment"], factory);
else if(typeof exports === 'object')
exports["DatePicker"] = factory(require("react"), require("react-onclickoutside"), require("moment"));
else
root["DatePicker"] = factory(root["React"], root["onClickOutside"], root["moment"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_13__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _calendar = __webpack_require__(1);
var _calendar2 = _interopRequireDefault(_calendar);
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _popper_component = __webpack_require__(21);
var _popper_component2 = _interopRequireDefault(_popper_component);
var _classnames2 = __webpack_require__(10);
var _classnames3 = _interopRequireDefault(_classnames2);
var _date_utils = __webpack_require__(12);
var _reactOnclickoutside = __webpack_require__(11);
var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var outsideClickIgnoreClass = 'react-datepicker-ignore-onclickoutside';
var WrappedCalendar = (0, _reactOnclickoutside2.default)(_calendar2.default);
/**
* General datepicker component.
*/
var DatePicker = function (_React$Component) {
_inherits(DatePicker, _React$Component);
_createClass(DatePicker, null, [{
key: 'defaultProps',
get: function get() {
return {
allowSameDay: false,
dateFormat: 'L',
dateFormatCalendar: 'MMMM YYYY',
onChange: function onChange() {},
disabled: false,
disabledKeyboardNavigation: false,
dropdownMode: 'scroll',
onFocus: function onFocus() {},
onBlur: function onBlur() {},
onKeyDown: function onKeyDown() {},
onSelect: function onSelect() {},
onClickOutside: function onClickOutside() {},
onMonthChange: function onMonthChange() {},
monthsShown: 1,
withPortal: false,
shouldCloseOnSelect: true,
showTimeSelect: false,
timeIntervals: 30
};
}
}]);
function DatePicker(props) {
_classCallCheck(this, DatePicker);
var _this = _possibleConstructorReturn(this, (DatePicker.__proto__ || Object.getPrototypeOf(DatePicker)).call(this, props));
_this.getPreSelection = function () {
return _this.props.openToDate ? (0, _date_utils.newDate)(_this.props.openToDate) : _this.props.selectsEnd && _this.props.startDate ? (0, _date_utils.newDate)(_this.props.startDate) : _this.props.selectsStart && _this.props.endDate ? (0, _date_utils.newDate)(_this.props.endDate) : (0, _date_utils.now)(_this.props.utcOffset);
};
_this.calcInitialState = function () {
var defaultPreSelection = _this.getPreSelection();
var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props);
var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props);
var boundedPreSelection = minDate && (0, _date_utils.isBefore)(defaultPreSelection, minDate) ? minDate : maxDate && (0, _date_utils.isAfter)(defaultPreSelection, maxDate) ? maxDate : defaultPreSelection;
return {
open: _this.props.startOpen || false,
preventFocus: false,
preSelection: _this.props.selected ? (0, _date_utils.newDate)(_this.props.selected) : boundedPreSelection
};
};
_this.clearPreventFocusTimeout = function () {
if (_this.preventFocusTimeout) {
clearTimeout(_this.preventFocusTimeout);
}
};
_this.setFocus = function () {
_this.input.focus();
};
_this.setOpen = function (open) {
_this.setState({
open: open,
preSelection: open && _this.state.open ? _this.state.preSelection : _this.calcInitialState().preSelection
});
};
_this.handleFocus = function (event) {
if (!_this.state.preventFocus) {
_this.props.onFocus(event);
_this.setOpen(true);
}
};
_this.cancelFocusInput = function () {
clearTimeout(_this.inputFocusTimeout);
_this.inputFocusTimeout = null;
};
_this.deferFocusInput = function () {
_this.cancelFocusInput();
_this.inputFocusTimeout = setTimeout(function () {
return _this.setFocus();
}, 1);
};
_this.handleDropdownFocus = function () {
_this.cancelFocusInput();
};
_this.handleBlur = function (event) {
if (_this.state.open) {
_this.deferFocusInput();
} else {
_this.props.onBlur(event);
}
};
_this.handleCalendarClickOutside = function (event) {
if (!_this.props.inline) {
_this.setOpen(false);
}
_this.props.onClickOutside(event);
if (_this.props.withPortal) {
event.preventDefault();
}
};
_this.handleChange = function (event) {
if (_this.props.onChangeRaw) {
_this.props.onChangeRaw(event);
if (event.isDefaultPrevented()) {
return;
}
}
_this.setState({ inputValue: event.target.value });
var date = (0, _date_utils.parseDate)(event.target.value, _this.props);
if (date || !event.target.value) {
_this.setSelected(date, event, true);
}
};
_this.handleSelect = function (date, event) {
// Preventing onFocus event to fix issue
// https://github.com/Hacker0x01/react-datepicker/issues/628
_this.setState({ preventFocus: true }, function () {
_this.preventFocusTimeout = setTimeout(function () {
return _this.setState({ preventFocus: false });
}, 50);
return _this.preventFocusTimeout;
});
_this.setSelected(date, event);
if (!_this.props.shouldCloseOnSelect) {
_this.setPreSelection(date);
} else if (!_this.props.inline) {
_this.setOpen(false);
}
};
_this.setSelected = function (date, event, keepInput) {
var changedDate = date;
if (changedDate !== null && (0, _date_utils.isDayDisabled)(changedDate, _this.props)) {
return;
}
if (!(0, _date_utils.isSameDay)(_this.props.selected, changedDate) || _this.props.allowSameDay) {
if (changedDate !== null) {
if (_this.props.selected) {
changedDate = (0, _date_utils.setTime)((0, _date_utils.newDate)(changedDate), {
hour: (0, _date_utils.getHour)(_this.props.selected),
minute: (0, _date_utils.getMinute)(_this.props.selected),
second: (0, _date_utils.getSecond)(_this.props.selected)
});
}
_this.setState({
preSelection: changedDate
});
}
_this.props.onChange(changedDate, event);
}
_this.props.onSelect(changedDate, event);
if (!keepInput) {
_this.setState({ inputValue: null });
}
};
_this.setPreSelection = function (date) {
var isDateRangePresent = typeof _this.props.minDate !== 'undefined' && typeof _this.props.maxDate !== 'undefined';
var isValidDateSelection = isDateRangePresent && date ? (0, _date_utils.isDayInRange)(date, _this.props.minDate, _this.props.maxDate) : true;
if (isValidDateSelection) {
_this.setState({
preSelection: date
});
}
};
_this.handleTimeChange = function (time) {
var selected = _this.props.selected ? _this.props.selected : _this.getPreSelection();
var changedDate = (0, _date_utils.setTime)((0, _date_utils.cloneDate)(selected), {
hour: (0, _date_utils.getHour)(time),
minute: (0, _date_utils.getMinute)(time)
});
_this.setState({
preSelection: changedDate
});
_this.props.onChange(changedDate);
};
_this.onInputClick = function () {
if (!_this.props.disabled) {
_this.setOpen(true);
}
};
_this.onInputKeyDown = function (event) {
_this.props.onKeyDown(event);
var eventKey = event.key;
if (!_this.state.open && !_this.props.inline) {
if (eventKey !== 'Enter' && eventKey !== 'Escape' && eventKey !== 'Tab') {
_this.onInputClick();
}
return;
}
var copy = (0, _date_utils.newDate)(_this.state.preSelection);
if (eventKey === 'Enter') {
event.preventDefault();
if ((0, _date_utils.isMoment)(_this.state.preSelection) || (0, _date_utils.isDate)(_this.state.preSelection)) {
_this.handleSelect(copy, event);
!_this.props.shouldCloseOnSelect && _this.setPreSelection(copy);
} else {
_this.setOpen(false);
}
} else if (eventKey === 'Escape') {
event.preventDefault();
_this.setOpen(false);
} else if (eventKey === 'Tab') {
_this.setOpen(false);
} else if (!_this.props.disabledKeyboardNavigation) {
var newSelection = void 0;
switch (eventKey) {
case 'ArrowLeft':
event.preventDefault();
newSelection = (0, _date_utils.subtractDays)(copy, 1);
break;
case 'ArrowRight':
event.preventDefault();
newSelection = (0, _date_utils.addDays)(copy, 1);
break;
case 'ArrowUp':
event.preventDefault();
newSelection = (0, _date_utils.subtractWeeks)(copy, 1);
break;
case 'ArrowDown':
event.preventDefault();
newSelection = (0, _date_utils.addWeeks)(copy, 1);
break;
case 'PageUp':
event.preventDefault();
newSelection = (0, _date_utils.subtractMonths)(copy, 1);
break;
case 'PageDown':
event.preventDefault();
newSelection = (0, _date_utils.addMonths)(copy, 1);
break;
case 'Home':
event.preventDefault();
newSelection = (0, _date_utils.subtractYears)(copy, 1);
break;
case 'End':
event.preventDefault();
newSelection = (0, _date_utils.addYears)(copy, 1);
break;
}
_this.setPreSelection(newSelection);
}
};
_this.onClearClick = function (event) {
event.preventDefault();
_this.props.onChange(null, event);
_this.setState({ inputValue: null });
};
_this.renderCalendar = function () {
if (!_this.props.inline && (!_this.state.open || _this.props.disabled)) {
return null;
}
return _react2.default.createElement(
WrappedCalendar,
{
ref: function ref(elem) {
_this.calendar = elem;
},
locale: _this.props.locale,
dateFormat: _this.props.dateFormatCalendar,
useWeekdaysShort: _this.props.useWeekdaysShort,
dropdownMode: _this.props.dropdownMode,
selected: _this.props.selected,
preSelection: _this.state.preSelection,
onSelect: _this.handleSelect,
onWeekSelect: _this.props.onWeekSelect,
openToDate: _this.props.openToDate,
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
selectsStart: _this.props.selectsStart,
selectsEnd: _this.props.selectsEnd,
startDate: _this.props.startDate,
endDate: _this.props.endDate,
excludeDates: _this.props.excludeDates,
filterDate: _this.props.filterDate,
onClickOutside: _this.handleCalendarClickOutside,
formatWeekNumber: _this.props.formatWeekNumber,
highlightDates: _this.props.highlightDates,
includeDates: _this.props.includeDates,
inline: _this.props.inline,
peekNextMonth: _this.props.peekNextMonth,
showMonthDropdown: _this.props.showMonthDropdown,
showWeekNumbers: _this.props.showWeekNumbers,
showYearDropdown: _this.props.showYearDropdown,
withPortal: _this.props.withPortal,
forceShowMonthNavigation: _this.props.forceShowMonthNavigation,
scrollableYearDropdown: _this.props.scrollableYearDropdown,
todayButton: _this.props.todayButton,
weekLabel: _this.props.weekLabel,
utcOffset: _this.props.utcOffset,
outsideClickIgnoreClass: outsideClickIgnoreClass,
fixedHeight: _this.props.fixedHeight,
monthsShown: _this.props.monthsShown,
onDropdownFocus: _this.handleDropdownFocus,
onMonthChange: _this.props.onMonthChange,
dayClassName: _this.props.dayClassName,
showTimeSelect: _this.props.showTimeSelect,
onTimeChange: _this.handleTimeChange,
timeFormat: _this.props.timeFormat,
timeIntervals: _this.props.timeIntervals,
minTime: _this.props.minTime,
maxTime: _this.props.maxTime,
excludeTimes: _this.props.excludeTimes,
className: _this.props.calendarClassName,
yearDropdownItemNumber: _this.props.yearDropdownItemNumber },
_this.props.children
);
};
_this.renderDateInput = function () {
var className = (0, _classnames3.default)(_this.props.className, _defineProperty({}, outsideClickIgnoreClass, _this.state.open));
var customInput = _this.props.customInput || _react2.default.createElement('input', { type: 'text' });
var inputValue = typeof _this.props.value === 'string' ? _this.props.value : typeof _this.state.inputValue === 'string' ? _this.state.inputValue : (0, _date_utils.safeDateFormat)(_this.props.selected, _this.props);
return _react2.default.cloneElement(customInput, {
ref: function ref(input) {
_this.input = input;
},
value: inputValue,
onBlur: _this.handleBlur,
onChange: _this.handleChange,
onClick: _this.onInputClick,
onFocus: _this.handleFocus,
onKeyDown: _this.onInputKeyDown,
id: _this.props.id,
name: _this.props.name,
autoFocus: _this.props.autoFocus,
placeholder: _this.props.placeholderText,
disabled: _this.props.disabled,
autoComplete: _this.props.autoComplete,
className: className,
title: _this.props.title,
readOnly: _this.props.readOnly,
required: _this.props.required,
tabIndex: _this.props.tabIndex
});
};
_this.renderClearButton = function () {
if (_this.props.isClearable && _this.props.selected != null) {
return _react2.default.createElement('a', { className: 'react-datepicker__close-icon', href: '#', onClick: _this.onClearClick });
} else {
return null;
}
};
_this.state = _this.calcInitialState();
return _this;
}
_createClass(DatePicker, [{
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var currentMonth = this.props.selected && (0, _date_utils.getMonth)(this.props.selected);
var nextMonth = nextProps.selected && (0, _date_utils.getMonth)(nextProps.selected);
if (this.props.inline && currentMonth !== nextMonth) {
this.setPreSelection(nextProps.selected);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearPreventFocusTimeout();
}
}, {
key: 'render',
value: function render() {
var calendar = this.renderCalendar();
if (this.props.inline && !this.props.withPortal) {
return calendar;
}
if (this.props.withPortal) {
return _react2.default.createElement(
'div',
null,
!this.props.inline ? _react2.default.createElement(
'div',
{ className: 'react-datepicker__input-container' },
this.renderDateInput(),
this.renderClearButton()
) : null,
this.state.open || this.props.inline ? _react2.default.createElement(
'div',
{ className: 'react-datepicker__portal' },
calendar
) : null
);
}
return _react2.default.createElement(_popper_component2.default, {
className: this.props.popperClassName,
hidePopper: !this.state.open || this.props.disabled,
popperModifiers: this.props.popperModifiers,
targetComponent: _react2.default.createElement(
'div',
{ className: 'react-datepicker__input-container' },
this.renderDateInput(),
this.renderClearButton()
),
popperContainer: this.props.popperContainer,
popperComponent: calendar,
popperPlacement: this.props.popperPlacement });
}
}]);
return DatePicker;
}(_react2.default.Component);
DatePicker.propTypes = {
allowSameDay: _propTypes2.default.bool,
autoComplete: _propTypes2.default.string,
autoFocus: _propTypes2.default.bool,
calendarClassName: _propTypes2.default.string,
children: _propTypes2.default.node,
className: _propTypes2.default.string,
customInput: _propTypes2.default.element,
dateFormat: _propTypes2.default.oneOfType([// eslint-disable-line react/no-unused-prop-types
_propTypes2.default.string, _propTypes2.default.array]),
dateFormatCalendar: _propTypes2.default.string,
dayClassName: _propTypes2.default.func,
disabled: _propTypes2.default.bool,
disabledKeyboardNavigation: _propTypes2.default.bool,
dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired,
endDate: _propTypes2.default.object,
excludeDates: _propTypes2.default.array,
filterDate: _propTypes2.default.func,
fixedHeight: _propTypes2.default.bool,
formatWeekNumber: _propTypes2.default.func,
highlightDates: _propTypes2.default.array,
id: _propTypes2.default.string,
includeDates: _propTypes2.default.array,
inline: _propTypes2.default.bool,
isClearable: _propTypes2.default.bool,
locale: _propTypes2.default.string,
maxDate: _propTypes2.default.object,
minDate: _propTypes2.default.object,
monthsShown: _propTypes2.default.number,
name: _propTypes2.default.string,
onBlur: _propTypes2.default.func,
onChange: _propTypes2.default.func.isRequired,
onSelect: _propTypes2.default.func,
onWeekSelect: _propTypes2.default.func,
onClickOutside: _propTypes2.default.func,
onChangeRaw: _propTypes2.default.func,
onFocus: _propTypes2.default.func,
onKeyDown: _propTypes2.default.func,
onMonthChange: _propTypes2.default.func,
openToDate: _propTypes2.default.object,
peekNextMonth: _propTypes2.default.bool,
placeholderText: _propTypes2.default.string,
popperContainer: _propTypes2.default.func,
popperClassName: _propTypes2.default.string, // <PopperComponent/> props
popperModifiers: _propTypes2.default.object, // <PopperComponent/> props
popperPlacement: _propTypes2.default.oneOf(_popper_component.popperPlacementPositions), // <PopperComponent/> props
readOnly: _propTypes2.default.bool,
required: _propTypes2.default.bool,
scrollableYearDropdown: _propTypes2.default.bool,
selected: _propTypes2.default.object,
selectsEnd: _propTypes2.default.bool,
selectsStart: _propTypes2.default.bool,
showMonthDropdown: _propTypes2.default.bool,
showWeekNumbers: _propTypes2.default.bool,
showYearDropdown: _propTypes2.default.bool,
forceShowMonthNavigation: _propTypes2.default.bool,
startDate: _propTypes2.default.object,
startOpen: _propTypes2.default.bool,
tabIndex: _propTypes2.default.number,
title: _propTypes2.default.string,
todayButton: _propTypes2.default.string,
useWeekdaysShort: _propTypes2.default.bool,
utcOffset: _propTypes2.default.number,
value: _propTypes2.default.string,
weekLabel: _propTypes2.default.string,
withPortal: _propTypes2.default.bool,
yearDropdownItemNumber: _propTypes2.default.number,
shouldCloseOnSelect: _propTypes2.default.bool,
showTimeSelect: _propTypes2.default.bool,
timeFormat: _propTypes2.default.string,
timeIntervals: _propTypes2.default.number,
minTime: _propTypes2.default.object,
maxTime: _propTypes2.default.object,
excludeTimes: _propTypes2.default.array
};
exports.default = DatePicker;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _year_dropdown = __webpack_require__(2);
var _year_dropdown2 = _interopRequireDefault(_year_dropdown);
var _month_dropdown = __webpack_require__(14);
var _month_dropdown2 = _interopRequireDefault(_month_dropdown);
var _month = __webpack_require__(16);
var _month2 = _interopRequireDefault(_month);
var _time = __webpack_require__(20);
var _time2 = _interopRequireDefault(_time);
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var _date_utils = __webpack_require__(12);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var DROPDOWN_FOCUS_CLASSNAMES = ['react-datepicker__year-select', 'react-datepicker__month-select'];
var isDropdownSelect = function isDropdownSelect() {
var element = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var classNames = (element.className || '').split(/\s+/);
return DROPDOWN_FOCUS_CLASSNAMES.some(function (testClassname) {
return classNames.indexOf(testClassname) >= 0;
});
};
var Calendar = function (_React$Component) {
_inherits(Calendar, _React$Component);
_createClass(Calendar, null, [{
key: 'defaultProps',
get: function get() {
return {
onDropdownFocus: function onDropdownFocus() {},
monthsShown: 1,
forceShowMonthNavigation: false
};
}
}]);
function Calendar(props) {
_classCallCheck(this, Calendar);
var _this = _possibleConstructorReturn(this, (Calendar.__proto__ || Object.getPrototypeOf(Calendar)).call(this, props));
_this.handleClickOutside = function (event) {
_this.props.onClickOutside(event);
};
_this.handleDropdownFocus = function (event) {
if (isDropdownSelect(event.target)) {
_this.props.onDropdownFocus();
}
};
_this.getDateInView = function () {
var _this$props = _this.props,
preSelection = _this$props.preSelection,
selected = _this$props.selected,
openToDate = _this$props.openToDate,
utcOffset = _this$props.utcOffset;
var minDate = (0, _date_utils.getEffectiveMinDate)(_this.props);
var maxDate = (0, _date_utils.getEffectiveMaxDate)(_this.props);
var current = (0, _date_utils.now)(utcOffset);
var initialDate = openToDate || selected || preSelection;
if (initialDate) {
return initialDate;
} else {
if (minDate && (0, _date_utils.isBefore)(current, minDate)) {
return minDate;
} else if (maxDate && (0, _date_utils.isAfter)(current, maxDate)) {
return maxDate;
}
}
return current;
};
_this.localizeDate = function (date) {
return (0, _date_utils.localizeDate)(date, _this.props.locale);
};
_this.increaseMonth = function () {
_this.setState({
date: (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), 1)
}, function () {
return _this.handleMonthChange(_this.state.date);
});
};
_this.decreaseMonth = function () {
_this.setState({
date: (0, _date_utils.subtractMonths)((0, _date_utils.cloneDate)(_this.state.date), 1)
}, function () {
return _this.handleMonthChange(_this.state.date);
});
};
_this.handleDayClick = function (day, event) {
return _this.props.onSelect(day, event);
};
_this.handleDayMouseEnter = function (day) {
return _this.setState({ selectingDate: day });
};
_this.handleMonthMouseLeave = function () {
return _this.setState({ selectingDate: null });
};
_this.handleMonthChange = function (date) {
if (_this.props.onMonthChange) {
_this.props.onMonthChange(date);
}
};
_this.changeYear = function (year) {
_this.setState({
date: (0, _date_utils.setYear)((0, _date_utils.cloneDate)(_this.state.date), year)
});
};
_this.changeMonth = function (month) {
_this.setState({
date: (0, _date_utils.setMonth)((0, _date_utils.cloneDate)(_this.state.date), month)
}, function () {
return _this.handleMonthChange(_this.state.date);
});
};
_this.header = function () {
var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date;
var startOfWeek = (0, _date_utils.getStartOfWeek)((0, _date_utils.cloneDate)(date));
var dayNames = [];
if (_this.props.showWeekNumbers) {
dayNames.push(_react2.default.createElement(
'div',
{ key: 'W', className: 'react-datepicker__day-name' },
_this.props.weekLabel || '#'
));
}
return dayNames.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) {
var day = (0, _date_utils.addDays)((0, _date_utils.cloneDate)(startOfWeek), offset);
var localeData = (0, _date_utils.getLocaleData)(day);
var weekDayName = _this.props.useWeekdaysShort ? (0, _date_utils.getWeekdayShortInLocale)(localeData, day) : (0, _date_utils.getWeekdayMinInLocale)(localeData, day);
return _react2.default.createElement(
'div',
{ key: offset, className: 'react-datepicker__day-name' },
weekDayName
);
}));
};
_this.renderPreviousMonthButton = function () {
if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledBefore)(_this.state.date, 'month', _this.props)) {
return;
}
return _react2.default.createElement('a', {
className: 'react-datepicker__navigation react-datepicker__navigation--previous',
onClick: _this.decreaseMonth });
};
_this.renderNextMonthButton = function () {
if (!_this.props.forceShowMonthNavigation && (0, _date_utils.allDaysDisabledAfter)(_this.state.date, 'month', _this.props)) {
return;
}
var classes = ['react-datepicker__navigation', 'react-datepicker__navigation--next'];
if (_this.props.showTimeSelect) {
classes.push('react-datepicker__navigation--next--with-time');
}
if (_this.props.todayButton) {
classes.push('react-datepicker__navigation--next--with-today-button');
}
return _react2.default.createElement('a', {
className: classes.join(' '),
onClick: _this.increaseMonth });
};
_this.renderCurrentMonth = function () {
var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.state.date;
var classes = ['react-datepicker__current-month'];
if (_this.props.showYearDropdown) {
classes.push('react-datepicker__current-month--hasYearDropdown');
}
if (_this.props.showMonthDropdown) {
classes.push('react-datepicker__current-month--hasMonthDropdown');
}
return _react2.default.createElement(
'div',
{ className: classes.join(' ') },
(0, _date_utils.formatDate)(date, _this.props.dateFormat)
);
};
_this.renderYearDropdown = function () {
var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!_this.props.showYearDropdown || overrideHide) {
return;
}
return _react2.default.createElement(_year_dropdown2.default, {
dropdownMode: _this.props.dropdownMode,
onChange: _this.changeYear,
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
year: (0, _date_utils.getYear)(_this.state.date),
scrollableYearDropdown: _this.props.scrollableYearDropdown,
yearDropdownItemNumber: _this.props.yearDropdownItemNumber });
};
_this.renderMonthDropdown = function () {
var overrideHide = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!_this.props.showMonthDropdown) {
return;
}
return _react2.default.createElement(_month_dropdown2.default, {
dropdownMode: _this.props.dropdownMode,
locale: _this.props.locale,
dateFormat: _this.props.dateFormat,
onChange: _this.changeMonth,
month: (0, _date_utils.getMonth)(_this.state.date) });
};
_this.renderTodayButton = function () {
if (!_this.props.todayButton) {
return;
}
return _react2.default.createElement(
'div',
{
className: 'react-datepicker__today-button',
onClick: function onClick(e) {
return _this.props.onSelect((0, _date_utils.getStartOfDate)((0, _date_utils.now)(_this.props.utcOffset)), e);
} },
_this.props.todayButton
);
};
_this.renderMonths = function () {
var monthList = [];
for (var i = 0; i < _this.props.monthsShown; ++i) {
var monthDate = (0, _date_utils.addMonths)((0, _date_utils.cloneDate)(_this.state.date), i);
var monthKey = 'month-' + i;
monthList.push(_react2.default.createElement(
'div',
{ key: monthKey, ref: function ref(div) {
_this.monthContainer = div;
}, className: 'react-datepicker__month-container' },
_react2.default.createElement(
'div',
{ className: 'react-datepicker__header' },
_this.renderCurrentMonth(monthDate),
_react2.default.createElement(
'div',
{
className: 'react-datepicker__header__dropdown react-datepicker__header__dropdown--' + _this.props.dropdownMode,
onFocus: _this.handleDropdownFocus },
_this.renderMonthDropdown(i !== 0),
_this.renderYearDropdown(i !== 0)
),
_react2.default.createElement(
'div',
{ className: 'react-datepicker__day-names' },
_this.header(monthDate)
)
),
_react2.default.createElement(_month2.default, {
day: monthDate,
dayClassName: _this.props.dayClassName,
onDayClick: _this.handleDayClick,
onDayMouseEnter: _this.handleDayMouseEnter,
onMouseLeave: _this.handleMonthMouseLeave,
onWeekSelect: _this.props.onWeekSelect,
formatWeekNumber: _this.props.formatWeekNumber,
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
excludeDates: _this.props.excludeDates,
highlightDates: _this.props.highlightDates,
selectingDate: _this.state.selectingDate,
includeDates: _this.props.includeDates,
inline: _this.props.inline,
fixedHeight: _this.props.fixedHeight,
filterDate: _this.props.filterDate,
preSelection: _this.props.preSelection,
selected: _this.props.selected,
selectsStart: _this.props.selectsStart,
selectsEnd: _this.props.selectsEnd,
showWeekNumbers: _this.props.showWeekNumbers,
startDate: _this.props.startDate,
endDate: _this.props.endDate,
peekNextMonth: _this.props.peekNextMonth,
utcOffset: _this.props.utcOffset })
));
}
return monthList;
};
_this.renderTimeSection = function () {
if (_this.props.showTimeSelect) {
return _react2.default.createElement(_time2.default, {
selected: _this.props.selected,
onChange: _this.props.onTimeChange,
format: _this.props.timeFormat,
intervals: _this.props.timeIntervals,
minTime: _this.props.minTime,
maxTime: _this.props.maxTime,
excludeTimes: _this.props.excludeTimes,
todayButton: _this.props.todayButton,
showMonthDropdown: _this.props.showMonthDropdown,
showYearDropdown: _this.props.showYearDropdown,
withPortal: _this.props.withPortal,
monthRef: _this.state.monthContainer });
} else {
return;
}
};
_this.state = {
date: _this.localizeDate(_this.getDateInView()),
selectingDate: null,
monthContainer: _this.monthContainer
};
return _this;
}
_createClass(Calendar, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
/* monthContainer height is needed in time component to determine the height for the ul in the time component. setState here so height is given after final component layout is rendered */
if (this.props.showTimeSelect) {
this.assignMonthContainer = function () {
_this2.setState({ monthContainer: _this2.monthContainer });
}();
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (nextProps.preSelection && !(0, _date_utils.isSameDay)(nextProps.preSelection, this.props.preSelection)) {
this.setState({
date: this.localizeDate(nextProps.preSelection)
});
} else if (nextProps.openToDate && !(0, _date_utils.isSameDay)(nextProps.openToDate, this.props.openToDate)) {
this.setState({
date: this.localizeDate(nextProps.openToDate)
});
}
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: (0, _classnames2.default)('react-datepicker', this.props.className) },
_react2.default.createElement('div', { className: 'react-datepicker__triangle' }),
this.renderPreviousMonthButton(),
this.renderNextMonthButton(),
this.renderMonths(),
this.renderTodayButton(),
this.renderTimeSection(),
this.props.children
);
}
}]);
return Calendar;
}(_react2.default.Component);
Calendar.propTypes = {
className: _propTypes2.default.string,
children: _propTypes2.default.node,
dateFormat: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.array]).isRequired,
dayClassName: _propTypes2.default.func,
dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired,
endDate: _propTypes2.default.object,
excludeDates: _propTypes2.default.array,
filterDate: _propTypes2.default.func,
fixedHeight: _propTypes2.default.bool,
formatWeekNumber: _propTypes2.default.func,
highlightDates: _propTypes2.default.array,
includeDates: _propTypes2.default.array,
inline: _propTypes2.default.bool,
locale: _propTypes2.default.string,
maxDate: _propTypes2.default.object,
minDate: _propTypes2.default.object,
monthsShown: _propTypes2.default.number,
onClickOutside: _propTypes2.default.func.isRequired,
onMonthChange: _propTypes2.default.func,
forceShowMonthNavigation: _propTypes2.default.bool,
onDropdownFocus: _propTypes2.default.func,
onSelect: _propTypes2.default.func.isRequired,
onWeekSelect: _propTypes2.default.func,
showTimeSelect: _propTypes2.default.bool,
timeFormat: _propTypes2.default.string,
timeIntervals: _propTypes2.default.number,
onTimeChange: _propTypes2.default.func,
minTime: _propTypes2.default.object,
maxTime: _propTypes2.default.object,
excludeTimes: _propTypes2.default.array,
openToDate: _propTypes2.default.object,
peekNextMonth: _propTypes2.default.bool,
scrollableYearDropdown: _propTypes2.default.bool,
preSelection: _propTypes2.default.object,
selected: _propTypes2.default.object,
selectsEnd: _propTypes2.default.bool,
selectsStart: _propTypes2.default.bool,
showMonthDropdown: _propTypes2.default.bool,
showWeekNumbers: _propTypes2.default.bool,
showYearDropdown: _propTypes2.default.bool,
startDate: _propTypes2.default.object,
todayButton: _propTypes2.default.string,
useWeekdaysShort: _propTypes2.default.bool,
withPortal: _propTypes2.default.bool,
utcOffset: _propTypes2.default.number,
weekLabel: _propTypes2.default.string,
yearDropdownItemNumber: _propTypes2.default.number
};
exports.default = Calendar;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _year_dropdown_options = __webpack_require__(9);
var _year_dropdown_options2 = _interopRequireDefault(_year_dropdown_options);
var _reactOnclickoutside = __webpack_require__(11);
var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside);
var _date_utils = __webpack_require__(12);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WrappedYearDropdownOptions = (0, _reactOnclickoutside2.default)(_year_dropdown_options2.default);
var YearDropdown = function (_React$Component) {
_inherits(YearDropdown, _React$Component);
function YearDropdown() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, YearDropdown);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = YearDropdown.__proto__ || Object.getPrototypeOf(YearDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
dropdownVisible: false
}, _this.renderSelectOptions = function () {
var minYear = _this.props.minDate ? (0, _date_utils.getYear)(_this.props.minDate) : 1900;
var maxYear = _this.props.maxDate ? (0, _date_utils.getYear)(_this.props.maxDate) : 2100;
var options = [];
for (var i = minYear; i <= maxYear; i++) {
options.push(_react2.default.createElement(
'option',
{ key: i, value: i },
i
));
}
return options;
}, _this.onSelectChange = function (e) {
_this.onChange(e.target.value);
}, _this.renderSelectMode = function () {
return _react2.default.createElement(
'select',
{
value: _this.props.year,
className: 'react-datepicker__year-select',
onChange: _this.onSelectChange },
_this.renderSelectOptions()
);
}, _this.renderReadView = function (visible) {
return _react2.default.createElement(
'div',
{ key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__year-read-view', onClick: _this.toggleDropdown },
_react2.default.createElement('span', { className: 'react-datepicker__year-read-view--down-arrow' }),
_react2.default.createElement(
'span',
{ className: 'react-datepicker__year-read-view--selected-year' },
_this.props.year
)
);
}, _this.renderDropdown = function () {
return _react2.default.createElement(WrappedYearDropdownOptions, {
key: 'dropdown',
ref: 'options',
year: _this.props.year,
onChange: _this.onChange,
onCancel: _this.toggleDropdown,
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
scrollableYearDropdown: _this.props.scrollableYearDropdown,
yearDropdownItemNumber: _this.props.yearDropdownItemNumber });
}, _this.renderScrollMode = function () {
var dropdownVisible = _this.state.dropdownVisible;
var result = [_this.renderReadView(!dropdownVisible)];
if (dropdownVisible) {
result.unshift(_this.renderDropdown());
}
return result;
}, _this.onChange = function (year) {
_this.toggleDropdown();
if (year === _this.props.year) return;
_this.props.onChange(year);
}, _this.toggleDropdown = function () {
_this.setState({
dropdownVisible: !_this.state.dropdownVisible
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(YearDropdown, [{
key: 'render',
value: function render() {
var renderedDropdown = void 0;
switch (this.props.dropdownMode) {
case 'scroll':
renderedDropdown = this.renderScrollMode();
break;
case 'select':
renderedDropdown = this.renderSelectMode();
break;
}
return _react2.default.createElement(
'div',
{
className: 'react-datepicker__year-dropdown-container react-datepicker__year-dropdown-container--' + this.props.dropdownMode },
renderedDropdown
);
}
}]);
return YearDropdown;
}(_react2.default.Component);
YearDropdown.propTypes = {
dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired,
maxDate: _propTypes2.default.object,
minDate: _propTypes2.default.object,
onChange: _propTypes2.default.func.isRequired,
scrollableYearDropdown: _propTypes2.default.bool,
year: _propTypes2.default.number.isRequired,
yearDropdownItemNumber: _propTypes2.default.number
};
exports.default = YearDropdown;
/***/ }),
/* 3 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_3__;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
if (false) {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = require('./factoryWithTypeCheckers')(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = __webpack_require__(5)();
}
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var emptyFunction = __webpack_require__(6);
var invariant = __webpack_require__(7);
var ReactPropTypesSecret = __webpack_require__(8);
module.exports = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
};
shim.isRequired = shim;
function getShim() {
return shim;
};
// Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim
};
ReactPropTypes.checkPropTypes = emptyFunction;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/* 6 */
/***/ (function(module, exports) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (false) {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 8 */
/***/ (function(module, exports) {
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function generateYears(year, noOfYear, minDate, maxDate) {
var list = [];
for (var i = 0; i < 2 * noOfYear + 1; i++) {
var newYear = year + noOfYear - i;
var isInRange = true;
if (minDate) {
isInRange = minDate.year() <= newYear;
}
if (maxDate && isInRange) {
isInRange = maxDate.year() >= newYear;
}
if (isInRange) {
list.push(newYear);
}
}
return list;
}
var YearDropdownOptions = function (_React$Component) {
_inherits(YearDropdownOptions, _React$Component);
function YearDropdownOptions(props) {
_classCallCheck(this, YearDropdownOptions);
var _this = _possibleConstructorReturn(this, (YearDropdownOptions.__proto__ || Object.getPrototypeOf(YearDropdownOptions)).call(this, props));
_this.renderOptions = function () {
var selectedYear = _this.props.year;
var options = _this.state.yearsList.map(function (year) {
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__year-option',
key: year,
ref: year,
onClick: _this.onChange.bind(_this, year) },
selectedYear === year ? _react2.default.createElement(
'span',
{ className: 'react-datepicker__year-option--selected' },
'\u2713'
) : '',
year
);
});
var minYear = _this.props.minDate ? _this.props.minDate.year() : null;
var maxYear = _this.props.maxDate ? _this.props.maxDate.year() : null;
if (!maxYear || !_this.state.yearsList.find(function (year) {
return year === maxYear;
})) {
options.unshift(_react2.default.createElement(
'div',
{ className: 'react-datepicker__year-option',
ref: 'upcoming',
key: 'upcoming',
onClick: _this.incrementYears },
_react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-upcoming' })
));
}
if (!minYear || !_this.state.yearsList.find(function (year) {
return year === minYear;
})) {
options.push(_react2.default.createElement(
'div',
{ className: 'react-datepicker__year-option',
ref: 'previous',
key: 'previous',
onClick: _this.decrementYears },
_react2.default.createElement('a', { className: 'react-datepicker__navigation react-datepicker__navigation--years react-datepicker__navigation--years-previous' })
));
}
return options;
};
_this.onChange = function (year) {
_this.props.onChange(year);
};
_this.handleClickOutside = function () {
_this.props.onCancel();
};
_this.shiftYears = function (amount) {
var years = _this.state.yearsList.map(function (year) {
return year + amount;
});
_this.setState({
yearsList: years
});
};
_this.incrementYears = function () {
return _this.shiftYears(1);
};
_this.decrementYears = function () {
return _this.shiftYears(-1);
};
var yearDropdownItemNumber = props.yearDropdownItemNumber,
scrollableYearDropdown = props.scrollableYearDropdown;
var noOfYear = yearDropdownItemNumber || (scrollableYearDropdown ? 10 : 5);
_this.state = {
yearsList: generateYears(_this.props.year, noOfYear, _this.props.minDate, _this.props.maxDate)
};
return _this;
}
_createClass(YearDropdownOptions, [{
key: 'render',
value: function render() {
var dropdownClass = (0, _classnames2.default)({
'react-datepicker__year-dropdown': true,
'react-datepicker__year-dropdown--scrollable': this.props.scrollableYearDropdown
});
return _react2.default.createElement(
'div',
{ className: dropdownClass },
this.renderOptions()
);
}
}]);
return YearDropdownOptions;
}(_react2.default.Component);
YearDropdownOptions.propTypes = {
minDate: _propTypes2.default.object,
maxDate: _propTypes2.default.object,
onCancel: _propTypes2.default.func.isRequired,
onChange: _propTypes2.default.func.isRequired,
scrollableYearDropdown: _propTypes2.default.bool,
year: _propTypes2.default.number.isRequired,
yearDropdownItemNumber: _propTypes2.default.number
};
exports.default = YearDropdownOptions;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ }),
/* 11 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_11__;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.newDate = newDate;
exports.newDateWithOffset = newDateWithOffset;
exports.now = now;
exports.cloneDate = cloneDate;
exports.parseDate = parseDate;
exports.isMoment = isMoment;
exports.isDate = isDate;
exports.formatDate = formatDate;
exports.safeDateFormat = safeDateFormat;
exports.setTime = setTime;
exports.setMonth = setMonth;
exports.setYear = setYear;
exports.setUTCOffset = setUTCOffset;
exports.getSecond = getSecond;
exports.getMinute = getMinute;
exports.getHour = getHour;
exports.getDay = getDay;
exports.getWeek = getWeek;
exports.getMonth = getMonth;
exports.getYear = getYear;
exports.getDate = getDate;
exports.getUTCOffset = getUTCOffset;
exports.getDayOfWeekCode = getDayOfWeekCode;
exports.getStartOfDay = getStartOfDay;
exports.getStartOfWeek = getStartOfWeek;
exports.getStartOfMonth = getStartOfMonth;
exports.getStartOfDate = getStartOfDate;
exports.getEndOfWeek = getEndOfWeek;
exports.getEndOfMonth = getEndOfMonth;
exports.addMinutes = addMinutes;
exports.addDays = addDays;
exports.addWeeks = addWeeks;
exports.addMonths = addMonths;
exports.addYears = addYears;
exports.subtractDays = subtractDays;
exports.subtractWeeks = subtractWeeks;
exports.subtractMonths = subtractMonths;
exports.subtractYears = subtractYears;
exports.isBefore = isBefore;
exports.isAfter = isAfter;
exports.equals = equals;
exports.isSameMonth = isSameMonth;
exports.isSameDay = isSameDay;
exports.isSameUtcOffset = isSameUtcOffset;
exports.isDayInRange = isDayInRange;
exports.getDaysDiff = getDaysDiff;
exports.localizeDate = localizeDate;
exports.getDefaultLocale = getDefaultLocale;
exports.getDefaultLocaleData = getDefaultLocaleData;
exports.registerLocale = registerLocale;
exports.getLocaleData = getLocaleData;
exports.getLocaleDataForLocale = getLocaleDataForLocale;
exports.getWeekdayMinInLocale = getWeekdayMinInLocale;
exports.getWeekdayShortInLocale = getWeekdayShortInLocale;
exports.getMonthInLocale = getMonthInLocale;
exports.isDayDisabled = isDayDisabled;
exports.isTimeDisabled = isTimeDisabled;
exports.isTimeInDisabledRange = isTimeInDisabledRange;
exports.allDaysDisabledBefore = allDaysDisabledBefore;
exports.allDaysDisabledAfter = allDaysDisabledAfter;
exports.getEffectiveMinDate = getEffectiveMinDate;
exports.getEffectiveMaxDate = getEffectiveMaxDate;
var _moment = __webpack_require__(13);
var _moment2 = _interopRequireDefault(_moment);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var dayOfWeekCodes = {
1: 'mon',
2: 'tue',
3: 'wed',
4: 'thu',
5: 'fri',
6: 'sat',
7: 'sun'
// These functions are not exported so
// that we avoid magic strings like 'days'
};function set(date, unit, to) {
return date.set(unit, to);
}
function add(date, amount, unit) {
return date.add(amount, unit);
}
function subtract(date, amount, unit) {
return date.subtract(amount, unit);
}
function get(date, unit) {
return date.get(unit);
}
function getStartOf(date, unit) {
return date.startOf(unit);
}
function getEndOf(date, unit) {
return date.endOf(unit);
}
function getDiff(date1, date2, unit) {
return date1.diff(date2, unit);
}
function isSame(date1, date2, unit) {
return date1.isSame(date2, unit);
}
// ** Date Constructors **
function newDate(point) {
return (0, _moment2.default)(point);
}
function newDateWithOffset(utcOffset) {
return (0, _moment2.default)().utc().utcOffset(utcOffset);
}
function now(maybeFixedUtcOffset) {
if (maybeFixedUtcOffset == null) {
return newDate();
}
return newDateWithOffset(maybeFixedUtcOffset);
}
function cloneDate(date) {
return date.clone();
}
function parseDate(value, _ref) {
var dateFormat = _ref.dateFormat,
locale = _ref.locale;
var m = (0, _moment2.default)(value, dateFormat, locale || _moment2.default.locale(), true);
return m.isValid() ? m : null;
}
// ** Date "Reflection" **
function isMoment(date) {
return _moment2.default.isMoment(date);
}
function isDate(date) {
return _moment2.default.isDate(date);
}
// ** Date Formatting **
function formatDate(date, format) {
return date.format(format);
}
function safeDateFormat(date, _ref2) {
var dateFormat = _ref2.dateFormat,
locale = _ref2.locale;
return date && date.clone().locale(locale || _moment2.default.locale()).format(Array.isArray(dateFormat) ? dateFormat[0] : dateFormat) || '';
}
// ** Date Setters **
function setTime(date, _ref3) {
var hour = _ref3.hour,
minute = _ref3.minute,
second = _ref3.second;
date.set({ hour: hour, minute: minute, second: second });
return date;
}
function setMonth(date, month) {
return set(date, 'month', month);
}
function setYear(date, year) {
return set(date, 'year', year);
}
function setUTCOffset(date, offset) {
return date.utcOffset(offset);
}
// ** Date Getters **
function getSecond(date) {
return get(date, 'second');
}
function getMinute(date) {
return get(date, 'minute');
}
function getHour(date) {
return get(date, 'hour');
}
// Returns day of week
function getDay(date) {
return get(date, 'day');
}
function getWeek(date) {
return get(date, 'week');
}
function getMonth(date) {
return get(date, 'month');
}
function getYear(date) {
return get(date, 'year');
}
// Returns day of month
function getDate(date) {
return get(date, 'date');
}
function getUTCOffset() {
return (0, _moment2.default)().utcOffset();
}
function getDayOfWeekCode(day) {
return dayOfWeekCodes[day.isoWeekday()];
}
// *** Start of ***
function getStartOfDay(date) {
return getStartOf(date, 'day');
}
function getStartOfWeek(date) {
return getStartOf(date, 'week');
}
function getStartOfMonth(date) {
return getStartOf(date, 'month');
}
function getStartOfDate(date) {
return getStartOf(date, 'date');
}
// *** End of ***
function getEndOfWeek(date) {
return getEndOf(date, 'week');
}
function getEndOfMonth(date) {
return getEndOf(date, 'month');
}
// ** Date Math **
// *** Addition ***
function addMinutes(date, amount) {
return add(date, amount, 'minutes');
}
function addDays(date, amount) {
return add(date, amount, 'days');
}
function addWeeks(date, amount) {
return add(date, amount, 'weeks');
}
function addMonths(date, amount) {
return add(date, amount, 'months');
}
function addYears(date, amount) {
return add(date, amount, 'years');
}
// *** Subtraction ***
function subtractDays(date, amount) {
return subtract(date, amount, 'days');
}
function subtractWeeks(date, amount) {
return subtract(date, amount, 'weeks');
}
function subtractMonths(date, amount) {
return subtract(date, amount, 'months');
}
function subtractYears(date, amount) {
return subtract(date, amount, 'years');
}
// ** Date Comparison **
function isBefore(date1, date2) {
return date1.isBefore(date2);
}
function isAfter(date1, date2) {
return date1.isAfter(date2);
}
function equals(date1, date2) {
return date1.isSame(date2);
}
function isSameMonth(date1, date2) {
return isSame(date1, date2, 'month');
}
function isSameDay(moment1, moment2) {
if (moment1 && moment2) {
return moment1.isSame(moment2, 'day');
} else {
return !moment1 && !moment2;
}
}
function isSameUtcOffset(moment1, moment2) {
if (moment1 && moment2) {
return moment1.utcOffset() === moment2.utcOffset();
} else {
return !moment1 && !moment2;
}
}
function isDayInRange(day, startDate, endDate) {
var before = startDate.clone().startOf('day').subtract(1, 'seconds');
var after = endDate.clone().startOf('day').add(1, 'seconds');
return day.clone().startOf('day').isBetween(before, after);
}
// *** Diffing ***
function getDaysDiff(date1, date2) {
return getDiff(date1, date2, 'days');
}
// ** Date Localization **
function localizeDate(date, locale) {
return date.clone().locale(locale || _moment2.default.locale());
}
function getDefaultLocale() {
return _moment2.default.locale();
}
function getDefaultLocaleData() {
return _moment2.default.localeData();
}
function registerLocale(localeName, localeData) {
_moment2.default.defineLocale(localeName, localeData);
}
function getLocaleData(date) {
return date.localeData();
}
function getLocaleDataForLocale(locale) {
return _moment2.default.localeData(locale);
}
function getWeekdayMinInLocale(locale, date) {
return locale.weekdaysMin(date);
}
function getWeekdayShortInLocale(locale, date) {
return locale.weekdaysShort(date);
}
// TODO what is this format exactly?
function getMonthInLocale(locale, date, format) {
return locale.months(date, format);
}
// ** Utils for some components **
function isDayDisabled(day) {
var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
minDate = _ref4.minDate,
maxDate = _ref4.maxDate,
excludeDates = _ref4.excludeDates,
includeDates = _ref4.includeDates,
filterDate = _ref4.filterDate;
return minDate && day.isBefore(minDate, 'day') || maxDate && day.isAfter(maxDate, 'day') || excludeDates && excludeDates.some(function (excludeDate) {
return isSameDay(day, excludeDate);
}) || includeDates && !includeDates.some(function (includeDate) {
return isSameDay(day, includeDate);
}) || filterDate && !filterDate(day.clone()) || false;
}
function isTimeDisabled(time, disabledTimes) {
var l = disabledTimes.length;
for (var i = 0; i < l; i++) {
if (disabledTimes[i].get('hours') === time.get('hours') && disabledTimes[i].get('minutes') === time.get('minutes')) {
return true;
}
}
return false;
}
function isTimeInDisabledRange(time, _ref5) {
var minTime = _ref5.minTime,
maxTime = _ref5.maxTime;
if (!minTime || !maxTime) {
throw new Error('Both minTime and maxTime props required');
}
var base = (0, _moment2.default)().hours(0).minutes(0).seconds(0);
var baseTime = base.clone().hours(time.get('hours')).minutes(time.get('minutes'));
var min = base.clone().hours(minTime.get('hours')).minutes(minTime.get('minutes'));
var max = base.clone().hours(maxTime.get('hours')).minutes(maxTime.get('minutes'));
return !(baseTime.isSameOrAfter(min) && baseTime.isSameOrBefore(max));
}
function allDaysDisabledBefore(day, unit) {
var _ref6 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
minDate = _ref6.minDate,
includeDates = _ref6.includeDates;
var dateBefore = day.clone().subtract(1, unit);
return minDate && dateBefore.isBefore(minDate, unit) || includeDates && includeDates.every(function (includeDate) {
return dateBefore.isBefore(includeDate, unit);
}) || false;
}
function allDaysDisabledAfter(day, unit) {
var _ref7 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
maxDate = _ref7.maxDate,
includeDates = _ref7.includeDates;
var dateAfter = day.clone().add(1, unit);
return maxDate && dateAfter.isAfter(maxDate, unit) || includeDates && includeDates.every(function (includeDate) {
return dateAfter.isAfter(includeDate, unit);
}) || false;
}
function getEffectiveMinDate(_ref8) {
var minDate = _ref8.minDate,
includeDates = _ref8.includeDates;
if (includeDates && minDate) {
return _moment2.default.min(includeDates.filter(function (includeDate) {
return minDate.isSameOrBefore(includeDate, 'day');
}));
} else if (includeDates) {
return _moment2.default.min(includeDates);
} else {
return minDate;
}
}
function getEffectiveMaxDate(_ref9) {
var maxDate = _ref9.maxDate,
includeDates = _ref9.includeDates;
if (includeDates && maxDate) {
return _moment2.default.max(includeDates.filter(function (includeDate) {
return maxDate.isSameOrAfter(includeDate, 'day');
}));
} else if (includeDates) {
return _moment2.default.max(includeDates);
} else {
return maxDate;
}
}
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_13__;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _month_dropdown_options = __webpack_require__(15);
var _month_dropdown_options2 = _interopRequireDefault(_month_dropdown_options);
var _reactOnclickoutside = __webpack_require__(11);
var _reactOnclickoutside2 = _interopRequireDefault(_reactOnclickoutside);
var _date_utils = __webpack_require__(12);
var utils = _interopRequireWildcard(_date_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WrappedMonthDropdownOptions = (0, _reactOnclickoutside2.default)(_month_dropdown_options2.default);
var MonthDropdown = function (_React$Component) {
_inherits(MonthDropdown, _React$Component);
function MonthDropdown() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, MonthDropdown);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdown.__proto__ || Object.getPrototypeOf(MonthDropdown)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
dropdownVisible: false
}, _this.renderSelectOptions = function (monthNames) {
return monthNames.map(function (M, i) {
return _react2.default.createElement(
'option',
{ key: i, value: i },
M
);
});
}, _this.renderSelectMode = function (monthNames) {
return _react2.default.createElement(
'select',
{ value: _this.props.month, className: 'react-datepicker__month-select', onChange: function onChange(e) {
return _this.onChange(e.target.value);
} },
_this.renderSelectOptions(monthNames)
);
}, _this.renderReadView = function (visible, monthNames) {
return _react2.default.createElement(
'div',
{ key: 'read', style: { visibility: visible ? 'visible' : 'hidden' }, className: 'react-datepicker__month-read-view', onClick: _this.toggleDropdown },
_react2.default.createElement(
'span',
{ className: 'react-datepicker__month-read-view--selected-month' },
monthNames[_this.props.month]
),
_react2.default.createElement('span', { className: 'react-datepicker__month-read-view--down-arrow' })
);
}, _this.renderDropdown = function (monthNames) {
return _react2.default.createElement(WrappedMonthDropdownOptions, {
key: 'dropdown',
ref: 'options',
month: _this.props.month,
monthNames: monthNames,
onChange: _this.onChange,
onCancel: _this.toggleDropdown });
}, _this.renderScrollMode = function (monthNames) {
var dropdownVisible = _this.state.dropdownVisible;
var result = [_this.renderReadView(!dropdownVisible, monthNames)];
if (dropdownVisible) {
result.unshift(_this.renderDropdown(monthNames));
}
return result;
}, _this.onChange = function (month) {
_this.toggleDropdown();
if (month !== _this.props.month) {
_this.props.onChange(month);
}
}, _this.toggleDropdown = function () {
return _this.setState({
dropdownVisible: !_this.state.dropdownVisible
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(MonthDropdown, [{
key: 'render',
value: function render() {
var _this2 = this;
var localeData = utils.getLocaleDataForLocale(this.props.locale);
var monthNames = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(function (M) {
return utils.getMonthInLocale(localeData, utils.newDate({ M: M }), _this2.props.dateFormat);
});
var renderedDropdown = void 0;
switch (this.props.dropdownMode) {
case 'scroll':
renderedDropdown = this.renderScrollMode(monthNames);
break;
case 'select':
renderedDropdown = this.renderSelectMode(monthNames);
break;
}
return _react2.default.createElement(
'div',
{
className: 'react-datepicker__month-dropdown-container react-datepicker__month-dropdown-container--' + this.props.dropdownMode },
renderedDropdown
);
}
}]);
return MonthDropdown;
}(_react2.default.Component);
MonthDropdown.propTypes = {
dropdownMode: _propTypes2.default.oneOf(['scroll', 'select']).isRequired,
locale: _propTypes2.default.string,
dateFormat: _propTypes2.default.string.isRequired,
month: _propTypes2.default.number.isRequired,
onChange: _propTypes2.default.func.isRequired
};
exports.default = MonthDropdown;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MonthDropdownOptions = function (_React$Component) {
_inherits(MonthDropdownOptions, _React$Component);
function MonthDropdownOptions() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, MonthDropdownOptions);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MonthDropdownOptions.__proto__ || Object.getPrototypeOf(MonthDropdownOptions)).call.apply(_ref, [this].concat(args))), _this), _this.renderOptions = function () {
return _this.props.monthNames.map(function (month, i) {
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__month-option',
key: month,
ref: month,
onClick: _this.onChange.bind(_this, i) },
_this.props.month === i ? _react2.default.createElement(
'span',
{ className: 'react-datepicker__month-option--selected' },
'\u2713'
) : '',
month
);
});
}, _this.onChange = function (month) {
return _this.props.onChange(month);
}, _this.handleClickOutside = function () {
return _this.props.onCancel();
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(MonthDropdownOptions, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__month-dropdown' },
this.renderOptions()
);
}
}]);
return MonthDropdownOptions;
}(_react2.default.Component);
MonthDropdownOptions.propTypes = {
onCancel: _propTypes2.default.func.isRequired,
onChange: _propTypes2.default.func.isRequired,
month: _propTypes2.default.number.isRequired,
monthNames: _propTypes2.default.arrayOf(_propTypes2.default.string.isRequired).isRequired
};
exports.default = MonthDropdownOptions;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var _week = __webpack_require__(17);
var _week2 = _interopRequireDefault(_week);
var _date_utils = __webpack_require__(12);
var utils = _interopRequireWildcard(_date_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var FIXED_HEIGHT_STANDARD_WEEK_COUNT = 6;
var Month = function (_React$Component) {
_inherits(Month, _React$Component);
function Month() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Month);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Month.__proto__ || Object.getPrototypeOf(Month)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) {
if (_this.props.onDayClick) {
_this.props.onDayClick(day, event);
}
}, _this.handleDayMouseEnter = function (day) {
if (_this.props.onDayMouseEnter) {
_this.props.onDayMouseEnter(day);
}
}, _this.handleMouseLeave = function () {
if (_this.props.onMouseLeave) {
_this.props.onMouseLeave();
}
}, _this.isWeekInMonth = function (startOfWeek) {
var day = _this.props.day;
var endOfWeek = utils.addDays(utils.cloneDate(startOfWeek), 6);
return utils.isSameMonth(startOfWeek, day) || utils.isSameMonth(endOfWeek, day);
}, _this.renderWeeks = function () {
var weeks = [];
var isFixedHeight = _this.props.fixedHeight;
var currentWeekStart = utils.getStartOfWeek(utils.getStartOfMonth(utils.cloneDate(_this.props.day)));
var i = 0;
var breakAfterNextPush = false;
while (true) {
weeks.push(_react2.default.createElement(_week2.default, {
key: i,
day: currentWeekStart,
month: utils.getMonth(_this.props.day),
onDayClick: _this.handleDayClick,
onDayMouseEnter: _this.handleDayMouseEnter,
onWeekSelect: _this.props.onWeekSelect,
formatWeekNumber: _this.props.formatWeekNumber,
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
excludeDates: _this.props.excludeDates,
includeDates: _this.props.includeDates,
inline: _this.props.inline,
highlightDates: _this.props.highlightDates,
selectingDate: _this.props.selectingDate,
filterDate: _this.props.filterDate,
preSelection: _this.props.preSelection,
selected: _this.props.selected,
selectsStart: _this.props.selectsStart,
selectsEnd: _this.props.selectsEnd,
showWeekNumber: _this.props.showWeekNumbers,
startDate: _this.props.startDate,
endDate: _this.props.endDate,
dayClassName: _this.props.dayClassName,
utcOffset: _this.props.utcOffset }));
if (breakAfterNextPush) break;
i++;
currentWeekStart = utils.addWeeks(utils.cloneDate(currentWeekStart), 1);
// If one of these conditions is true, we will either break on this week
// or break on the next week
var isFixedAndFinalWeek = isFixedHeight && i >= FIXED_HEIGHT_STANDARD_WEEK_COUNT;
var isNonFixedAndOutOfMonth = !isFixedHeight && !_this.isWeekInMonth(currentWeekStart);
if (isFixedAndFinalWeek || isNonFixedAndOutOfMonth) {
if (_this.props.peekNextMonth) {
breakAfterNextPush = true;
} else {
break;
}
}
}
return weeks;
}, _this.getClassNames = function () {
var _this$props = _this.props,
selectingDate = _this$props.selectingDate,
selectsStart = _this$props.selectsStart,
selectsEnd = _this$props.selectsEnd;
return (0, _classnames2.default)('react-datepicker__month', {
'react-datepicker__month--selecting-range': selectingDate && (selectsStart || selectsEnd)
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Month, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: this.getClassNames(), onMouseLeave: this.handleMouseLeave, role: 'listbox' },
this.renderWeeks()
);
}
}]);
return Month;
}(_react2.default.Component);
Month.propTypes = {
day: _propTypes2.default.object.isRequired,
dayClassName: _propTypes2.default.func,
endDate: _propTypes2.default.object,
excludeDates: _propTypes2.default.array,
filterDate: _propTypes2.default.func,
fixedHeight: _propTypes2.default.bool,
formatWeekNumber: _propTypes2.default.func,
highlightDates: _propTypes2.default.array,
includeDates: _propTypes2.default.array,
inline: _propTypes2.default.bool,
maxDate: _propTypes2.default.object,
minDate: _propTypes2.default.object,
onDayClick: _propTypes2.default.func,
onDayMouseEnter: _propTypes2.default.func,
onMouseLeave: _propTypes2.default.func,
onWeekSelect: _propTypes2.default.func,
peekNextMonth: _propTypes2.default.bool,
preSelection: _propTypes2.default.object,
selected: _propTypes2.default.object,
selectingDate: _propTypes2.default.object,
selectsEnd: _propTypes2.default.bool,
selectsStart: _propTypes2.default.bool,
showWeekNumbers: _propTypes2.default.bool,
startDate: _propTypes2.default.object,
utcOffset: _propTypes2.default.number
};
exports.default = Month;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _day = __webpack_require__(18);
var _day2 = _interopRequireDefault(_day);
var _week_number = __webpack_require__(19);
var _week_number2 = _interopRequireDefault(_week_number);
var _date_utils = __webpack_require__(12);
var utils = _interopRequireWildcard(_date_utils);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Week = function (_React$Component) {
_inherits(Week, _React$Component);
function Week() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Week);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Week.__proto__ || Object.getPrototypeOf(Week)).call.apply(_ref, [this].concat(args))), _this), _this.handleDayClick = function (day, event) {
if (_this.props.onDayClick) {
_this.props.onDayClick(day, event);
}
}, _this.handleDayMouseEnter = function (day) {
if (_this.props.onDayMouseEnter) {
_this.props.onDayMouseEnter(day);
}
}, _this.handleWeekClick = function (day, weekNumber, event) {
if (typeof _this.props.onWeekSelect === 'function') {
_this.props.onWeekSelect(day, weekNumber, event);
}
}, _this.formatWeekNumber = function (startOfWeek) {
if (_this.props.formatWeekNumber) {
return _this.props.formatWeekNumber(startOfWeek);
}
return utils.getWeek(startOfWeek);
}, _this.renderDays = function () {
var startOfWeek = utils.getStartOfWeek(utils.cloneDate(_this.props.day));
var days = [];
var weekNumber = _this.formatWeekNumber(startOfWeek);
if (_this.props.showWeekNumber) {
var onClickAction = _this.props.onWeekSelect ? _this.handleWeekClick.bind(_this, startOfWeek, weekNumber) : undefined;
days.push(_react2.default.createElement(_week_number2.default, { key: 'W', weekNumber: weekNumber, onClick: onClickAction }));
}
return days.concat([0, 1, 2, 3, 4, 5, 6].map(function (offset) {
var day = utils.addDays(utils.cloneDate(startOfWeek), offset);
return _react2.default.createElement(_day2.default, {
key: offset,
day: day,
month: _this.props.month,
onClick: _this.handleDayClick.bind(_this, day),
onMouseEnter: _this.handleDayMouseEnter.bind(_this, day),
minDate: _this.props.minDate,
maxDate: _this.props.maxDate,
excludeDates: _this.props.excludeDates,
includeDates: _this.props.includeDates,
inline: _this.props.inline,
highlightDates: _this.props.highlightDates,
selectingDate: _this.props.selectingDate,
filterDate: _this.props.filterDate,
preSelection: _this.props.preSelection,
selected: _this.props.selected,
selectsStart: _this.props.selectsStart,
selectsEnd: _this.props.selectsEnd,
startDate: _this.props.startDate,
endDate: _this.props.endDate,
dayClassName: _this.props.dayClassName,
utcOffset: _this.props.utcOffset });
}));
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Week, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__week' },
this.renderDays()
);
}
}]);
return Week;
}(_react2.default.Component);
Week.propTypes = {
day: _propTypes2.default.object.isRequired,
dayClassName: _propTypes2.default.func,
endDate: _propTypes2.default.object,
excludeDates: _propTypes2.default.array,
filterDate: _propTypes2.default.func,
formatWeekNumber: _propTypes2.default.func,
highlightDates: _propTypes2.default.array,
includeDates: _propTypes2.default.array,
inline: _propTypes2.default.bool,
maxDate: _propTypes2.default.object,
minDate: _propTypes2.default.object,
month: _propTypes2.default.number,
onDayClick: _propTypes2.default.func,
onDayMouseEnter: _propTypes2.default.func,
onWeekSelect: _propTypes2.default.func,
preSelection: _propTypes2.default.object,
selected: _propTypes2.default.object,
selectingDate: _propTypes2.default.object,
selectsEnd: _propTypes2.default.bool,
selectsStart: _propTypes2.default.bool,
showWeekNumber: _propTypes2.default.bool,
startDate: _propTypes2.default.object,
utcOffset: _propTypes2.default.number
};
exports.default = Week;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var _date_utils = __webpack_require__(12);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Day = function (_React$Component) {
_inherits(Day, _React$Component);
function Day() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Day);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Day.__proto__ || Object.getPrototypeOf(Day)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) {
if (!_this.isDisabled() && _this.props.onClick) {
_this.props.onClick(event);
}
}, _this.handleMouseEnter = function (event) {
if (!_this.isDisabled() && _this.props.onMouseEnter) {
_this.props.onMouseEnter(event);
}
}, _this.isSameDay = function (other) {
return (0, _date_utils.isSameDay)(_this.props.day, other);
}, _this.isKeyboardSelected = function () {
return !_this.props.inline && !_this.isSameDay(_this.props.selected) && _this.isSameDay(_this.props.preSelection);
}, _this.isDisabled = function () {
return (0, _date_utils.isDayDisabled)(_this.props.day, _this.props);
}, _this.getHighLightedClass = function (defaultClassName) {
var _this$props = _this.props,
day = _this$props.day,
highlightDates = _this$props.highlightDates;
if (!highlightDates) {
return _defineProperty({}, defaultClassName, false);
}
var classNames = {};
for (var i = 0, len = highlightDates.length; i < len; i++) {
var obj = highlightDates[i];
if ((0, _date_utils.isMoment)(obj)) {
if ((0, _date_utils.isSameDay)(day, obj)) {
classNames[defaultClassName] = true;
}
} else if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object') {
var keys = Object.keys(obj);
var arr = obj[keys[0]];
if (typeof keys[0] === 'string' && arr.constructor === Array) {
for (var k = 0, _len2 = arr.length; k < _len2; k++) {
if ((0, _date_utils.isSameDay)(day, arr[k])) {
classNames[keys[0]] = true;
}
}
}
}
}
return classNames;
}, _this.isInRange = function () {
var _this$props2 = _this.props,
day = _this$props2.day,
startDate = _this$props2.startDate,
endDate = _this$props2.endDate;
if (!startDate || !endDate) {
return false;
}
return (0, _date_utils.isDayInRange)(day, startDate, endDate);
}, _this.isInSelectingRange = function () {
var _this$props3 = _this.props,
day = _this$props3.day,
selectsStart = _this$props3.selectsStart,
selectsEnd = _this$props3.selectsEnd,
selectingDate = _this$props3.selectingDate,
startDate = _this$props3.startDate,
endDate = _this$props3.endDate;
if (!(selectsStart || selectsEnd) || !selectingDate || _this.isDisabled()) {
return false;
}
if (selectsStart && endDate && selectingDate.isSameOrBefore(endDate)) {
return (0, _date_utils.isDayInRange)(day, selectingDate, endDate);
}
if (selectsEnd && startDate && selectingDate.isSameOrAfter(startDate)) {
return (0, _date_utils.isDayInRange)(day, startDate, selectingDate);
}
return false;
}, _this.isSelectingRangeStart = function () {
if (!_this.isInSelectingRange()) {
return false;
}
var _this$props4 = _this.props,
day = _this$props4.day,
selectingDate = _this$props4.selectingDate,
startDate = _this$props4.startDate,
selectsStart = _this$props4.selectsStart;
if (selectsStart) {
return (0, _date_utils.isSameDay)(day, selectingDate);
} else {
return (0, _date_utils.isSameDay)(day, startDate);
}
}, _this.isSelectingRangeEnd = function () {
if (!_this.isInSelectingRange()) {
return false;
}
var _this$props5 = _this.props,
day = _this$props5.day,
selectingDate = _this$props5.selectingDate,
endDate = _this$props5.endDate,
selectsEnd = _this$props5.selectsEnd;
if (selectsEnd) {
return (0, _date_utils.isSameDay)(day, selectingDate);
} else {
return (0, _date_utils.isSameDay)(day, endDate);
}
}, _this.isRangeStart = function () {
var _this$props6 = _this.props,
day = _this$props6.day,
startDate = _this$props6.startDate,
endDate = _this$props6.endDate;
if (!startDate || !endDate) {
return false;
}
return (0, _date_utils.isSameDay)(startDate, day);
}, _this.isRangeEnd = function () {
var _this$props7 = _this.props,
day = _this$props7.day,
startDate = _this$props7.startDate,
endDate = _this$props7.endDate;
if (!startDate || !endDate) {
return false;
}
return (0, _date_utils.isSameDay)(endDate, day);
}, _this.isWeekend = function () {
var weekday = (0, _date_utils.getDay)(_this.props.day);
return weekday === 0 || weekday === 6;
}, _this.isOutsideMonth = function () {
return _this.props.month !== undefined && _this.props.month !== (0, _date_utils.getMonth)(_this.props.day);
}, _this.getClassNames = function (date) {
var dayClassName = _this.props.dayClassName ? _this.props.dayClassName(date) : undefined;
return (0, _classnames2.default)('react-datepicker__day', dayClassName, 'react-datepicker__day--' + (0, _date_utils.getDayOfWeekCode)(_this.props.day), {
'react-datepicker__day--disabled': _this.isDisabled(),
'react-datepicker__day--selected': _this.isSameDay(_this.props.selected),
'react-datepicker__day--keyboard-selected': _this.isKeyboardSelected(),
'react-datepicker__day--range-start': _this.isRangeStart(),
'react-datepicker__day--range-end': _this.isRangeEnd(),
'react-datepicker__day--in-range': _this.isInRange(),
'react-datepicker__day--in-selecting-range': _this.isInSelectingRange(),
'react-datepicker__day--selecting-range-start': _this.isSelectingRangeStart(),
'react-datepicker__day--selecting-range-end': _this.isSelectingRangeEnd(),
'react-datepicker__day--today': _this.isSameDay((0, _date_utils.now)(_this.props.utcOffset)),
'react-datepicker__day--weekend': _this.isWeekend(),
'react-datepicker__day--outside-month': _this.isOutsideMonth()
}, _this.getHighLightedClass('react-datepicker__day--highlighted'));
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Day, [{
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{
className: this.getClassNames(this.props.day),
onClick: this.handleClick,
onMouseEnter: this.handleMouseEnter,
'aria-label': 'day-' + (0, _date_utils.getDate)(this.props.day),
role: 'option' },
(0, _date_utils.getDate)(this.props.day)
);
}
}]);
return Day;
}(_react2.default.Component);
Day.propTypes = {
day: _propTypes2.default.object.isRequired,
dayClassName: _propTypes2.default.func,
endDate: _propTypes2.default.object,
highlightDates: _propTypes2.default.array,
inline: _propTypes2.default.bool,
month: _propTypes2.default.number,
onClick: _propTypes2.default.func,
onMouseEnter: _propTypes2.default.func,
preSelection: _propTypes2.default.object,
selected: _propTypes2.default.object,
selectingDate: _propTypes2.default.object,
selectsEnd: _propTypes2.default.bool,
selectsStart: _propTypes2.default.bool,
startDate: _propTypes2.default.object,
utcOffset: _propTypes2.default.number
};
exports.default = Day;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var WeekNumber = function (_React$Component) {
_inherits(WeekNumber, _React$Component);
function WeekNumber() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, WeekNumber);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = WeekNumber.__proto__ || Object.getPrototypeOf(WeekNumber)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (event) {
if (_this.props.onClick) {
_this.props.onClick(event);
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(WeekNumber, [{
key: 'render',
value: function render() {
var weekNumberClasses = {
'react-datepicker__week-number': true,
'react-datepicker__week-number--clickable': !!this.props.onClick
};
return _react2.default.createElement(
'div',
{
className: (0, _classnames2.default)(weekNumberClasses),
'aria-label': 'week-' + this.props.weekNumber,
onClick: this.handleClick },
this.props.weekNumber
);
}
}]);
return WeekNumber;
}(_react2.default.Component);
WeekNumber.propTypes = {
weekNumber: _propTypes2.default.number.isRequired,
onClick: _propTypes2.default.func
};
exports.default = WeekNumber;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _date_utils = __webpack_require__(12);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Time = function (_React$Component) {
_inherits(Time, _React$Component);
function Time() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Time);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Time.__proto__ || Object.getPrototypeOf(Time)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (time) {
if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) {
return;
}
_this.props.onChange(time);
}, _this.liClasses = function (time, currH, currM) {
var classes = ['react-datepicker__time-list-item'];
if (currH === (0, _date_utils.getHour)(time) && currM === (0, _date_utils.getMinute)(time)) {
classes.push('react-datepicker__time-list-item--selected');
}
if ((_this.props.minTime || _this.props.maxTime) && (0, _date_utils.isTimeInDisabledRange)(time, _this.props) || _this.props.excludeTimes && (0, _date_utils.isTimeDisabled)(time, _this.props.excludeTimes)) {
classes.push('react-datepicker__time-list-item--disabled');
}
return classes.join(' ');
}, _this.renderTimes = function () {
var times = [];
var format = _this.props.format ? _this.props.format : 'hh:mm A';
var intervals = _this.props.intervals;
var activeTime = _this.props.selected ? _this.props.selected : (0, _date_utils.newDate)();
var currH = (0, _date_utils.getHour)(activeTime);
var currM = (0, _date_utils.getMinute)(activeTime);
var base = (0, _date_utils.getStartOfDay)((0, _date_utils.newDate)());
var multiplier = 1440 / intervals;
for (var i = 0; i < multiplier; i++) {
times.push((0, _date_utils.addMinutes)((0, _date_utils.cloneDate)(base), i * intervals));
}
return times.map(function (time, i) {
return _react2.default.createElement(
'li',
{ key: i, onClick: _this.handleClick.bind(_this, time), className: _this.liClasses(time, currH, currM) },
(0, _date_utils.formatDate)(time, format)
);
});
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Time, [{
key: 'componentDidMount',
value: function componentDidMount() {
// code to ensure selected time will always be in focus within time window when it first appears
var multiplier = 60 / this.props.intervals;
var currH = this.props.selected ? (0, _date_utils.getHour)(this.props.selected) : (0, _date_utils.getHour)((0, _date_utils.newDate)());
this.list.scrollTop = 30 * (multiplier * currH);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var height = null;
if (this.props.monthRef) {
height = this.props.monthRef.clientHeight - 39;
}
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__time-container ' + (this.props.todayButton ? 'react-datepicker__time-container--with-today-button' : '') },
_react2.default.createElement(
'div',
{ className: 'react-datepicker__header react-datepicker__header--time' },
_react2.default.createElement(
'div',
{ className: 'react-datepicker-time__header' },
'Time'
)
),
_react2.default.createElement(
'div',
{ className: 'react-datepicker__time' },
_react2.default.createElement(
'div',
{ className: 'react-datepicker__time-box' },
_react2.default.createElement(
'ul',
{ className: 'react-datepicker__time-list', ref: function ref(list) {
_this2.list = list;
}, style: height ? { height: height } : {} },
this.renderTimes.bind(this)()
)
)
)
);
}
}], [{
key: 'defaultProps',
get: function get() {
return {
intervals: 30,
onTimeChange: function onTimeChange() {},
todayButton: null
};
}
}]);
return Time;
}(_react2.default.Component);
Time.propTypes = {
format: _propTypes2.default.string,
intervals: _propTypes2.default.number,
selected: _propTypes2.default.object,
onChange: _propTypes2.default.func,
todayButton: _propTypes2.default.string,
minTime: _propTypes2.default.object,
maxTime: _propTypes2.default.object,
excludeTimes: _propTypes2.default.array,
monthRef: _propTypes2.default.object
};
exports.default = Time;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.popperPlacementPositions = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _classnames = __webpack_require__(10);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _reactPopper = __webpack_require__(22);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var popperPlacementPositions = exports.popperPlacementPositions = ['auto', 'auto-left', 'auto-right', 'bottom', 'bottom-end', 'bottom-start', 'left', 'left-end', 'left-start', 'right', 'right-end', 'right-start', 'top', 'top-end', 'top-start'];
var PopperComponent = function (_React$Component) {
_inherits(PopperComponent, _React$Component);
function PopperComponent() {
_classCallCheck(this, PopperComponent);
return _possibleConstructorReturn(this, (PopperComponent.__proto__ || Object.getPrototypeOf(PopperComponent)).apply(this, arguments));
}
_createClass(PopperComponent, [{
key: 'render',
value: function render() {
var _props = this.props,
className = _props.className,
hidePopper = _props.hidePopper,
popperComponent = _props.popperComponent,
popperModifiers = _props.popperModifiers,
popperPlacement = _props.popperPlacement,
targetComponent = _props.targetComponent;
var popper = void 0;
if (!hidePopper) {
var classes = (0, _classnames2.default)('react-datepicker-popper', className);
popper = _react2.default.createElement(
_reactPopper.Popper,
{
className: classes,
modifiers: popperModifiers,
placement: popperPlacement },
popperComponent
);
}
if (this.props.popperContainer) {
popper = _react2.default.createElement(this.props.popperContainer, {}, popper);
}
return _react2.default.createElement(
_reactPopper.Manager,
null,
_react2.default.createElement(
_reactPopper.Target,
{ className: 'react-datepicker-wrapper' },
targetComponent
),
popper
);
}
}], [{
key: 'defaultProps',
get: function get() {
return {
hidePopper: true,
popperModifiers: {
preventOverflow: {
enabled: true,
escapeWithReference: true,
boundariesElement: 'viewport'
}
},
popperPlacement: 'bottom-start'
};
}
}]);
return PopperComponent;
}(_react2.default.Component);
PopperComponent.propTypes = {
className: _propTypes2.default.string,
hidePopper: _propTypes2.default.bool,
popperComponent: _propTypes2.default.element,
popperModifiers: _propTypes2.default.object, // <datepicker/> props
popperPlacement: _propTypes2.default.oneOf(popperPlacementPositions), // <datepicker/> props
popperContainer: _propTypes2.default.func,
targetComponent: _propTypes2.default.element
};
exports.default = PopperComponent;
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Arrow = exports.Popper = exports.Target = exports.Manager = undefined;
var _Manager2 = __webpack_require__(23);
var _Manager3 = _interopRequireDefault(_Manager2);
var _Target2 = __webpack_require__(24);
var _Target3 = _interopRequireDefault(_Target2);
var _Popper2 = __webpack_require__(25);
var _Popper3 = _interopRequireDefault(_Popper2);
var _Arrow2 = __webpack_require__(27);
var _Arrow3 = _interopRequireDefault(_Arrow2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.Manager = _Manager3.default;
exports.Target = _Target3.default;
exports.Popper = _Popper3.default;
exports.Arrow = _Arrow3.default;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Manager = function (_Component) {
_inherits(Manager, _Component);
function Manager() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Manager);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Manager.__proto__ || Object.getPrototypeOf(Manager)).call.apply(_ref, [this].concat(args))), _this), _this._setTargetNode = function (node) {
_this._targetNode = node;
}, _this._getTargetNode = function () {
return _this._targetNode;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Manager, [{
key: 'getChildContext',
value: function getChildContext() {
return {
popperManager: {
setTargetNode: this._setTargetNode,
getTargetNode: this._getTargetNode
}
};
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
tag = _props.tag,
children = _props.children,
restProps = _objectWithoutProperties(_props, ['tag', 'children']);
if (tag !== false) {
return (0, _react.createElement)(tag, restProps, children);
} else {
return children;
}
}
}]);
return Manager;
}(_react.Component);
Manager.childContextTypes = {
popperManager: _propTypes2.default.object.isRequired
};
Manager.propTypes = {
tag: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.bool])
};
Manager.defaultProps = {
tag: 'div'
};
exports.default = Manager;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var Target = function Target(props, context) {
var _props$component = props.component,
component = _props$component === undefined ? 'div' : _props$component,
innerRef = props.innerRef,
children = props.children,
restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']);
var popperManager = context.popperManager;
var targetRef = function targetRef(node) {
popperManager.setTargetNode(node);
if (typeof innerRef === 'function') {
innerRef(node);
}
};
if (typeof children === 'function') {
var targetProps = { ref: targetRef };
return children({ targetProps: targetProps, restProps: restProps });
}
var componentProps = _extends({}, restProps);
if (typeof component === 'string') {
componentProps.ref = targetRef;
} else {
componentProps.innerRef = targetRef;
}
return (0, _react.createElement)(component, componentProps, children);
};
Target.contextTypes = {
popperManager: _propTypes2.default.object.isRequired
};
Target.propTypes = {
component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
innerRef: _propTypes2.default.func,
children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};
exports.default = Target;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
var _popper = __webpack_require__(26);
var _popper2 = _interopRequireDefault(_popper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var noop = function noop() {
return null;
};
var Popper = function (_Component) {
_inherits(Popper, _Component);
function Popper() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, Popper);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Popper.__proto__ || Object.getPrototypeOf(Popper)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _this._setArrowNode = function (node) {
_this._arrowNode = node;
}, _this._getTargetNode = function () {
return _this.context.popperManager.getTargetNode();
}, _this._getOffsets = function (data) {
return Object.keys(data.offsets).map(function (key) {
return data.offsets[key];
});
}, _this._isDataDirty = function (data) {
if (_this.state.data) {
return JSON.stringify(_this._getOffsets(_this.state.data)) !== JSON.stringify(_this._getOffsets(data));
} else {
return true;
}
}, _this._updateStateModifier = {
enabled: true,
order: 900,
fn: function fn(data) {
if (_this._isDataDirty(data)) {
_this.setState({ data: data });
}
return data;
}
}, _this._getPopperStyle = function () {
var data = _this.state.data;
// If Popper isn't instantiated, hide the popperElement
// to avoid flash of unstyled content
if (!_this._popper || !data) {
return {
position: 'absolute',
pointerEvents: 'none',
opacity: 0
};
}
var _data$offsets$popper = data.offsets.popper,
top = _data$offsets$popper.top,
left = _data$offsets$popper.left,
position = _data$offsets$popper.position;
return _extends({
position: position
}, data.styles);
}, _this._getPopperPlacement = function () {
return !!_this.state.data ? _this.state.data.placement : undefined;
}, _this._getPopperHide = function () {
return !!_this.state.data && _this.state.data.hide ? '' : undefined;
}, _this._getArrowStyle = function () {
if (!_this.state.data || !_this.state.data.offsets.arrow) {
return {};
} else {
var _this$state$data$offs = _this.state.data.offsets.arrow,
top = _this$state$data$offs.top,
left = _this$state$data$offs.left;
return { top: top, left: left };
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(Popper, [{
key: 'getChildContext',
value: function getChildContext() {
return {
popper: {
setArrowNode: this._setArrowNode,
getArrowStyle: this._getArrowStyle
}
};
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this._updatePopper();
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(lastProps) {
if (lastProps.placement !== this.props.placement || lastProps.eventsEnabled !== this.props.eventsEnabled) {
this._updatePopper();
}
if (this._popper && lastProps.children !== this.props.children) {
this._popper.scheduleUpdate();
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._destroyPopper();
}
}, {
key: '_updatePopper',
value: function _updatePopper() {
this._destroyPopper();
if (this._node) {
this._createPopper();
}
}
}, {
key: '_createPopper',
value: function _createPopper() {
var _props = this.props,
placement = _props.placement,
eventsEnabled = _props.eventsEnabled;
var modifiers = _extends({}, this.props.modifiers, {
applyStyle: { enabled: false },
updateState: this._updateStateModifier
});
if (this._arrowNode) {
modifiers.arrow = {
element: this._arrowNode
};
}
this._popper = new _popper2.default(this._getTargetNode(), this._node, {
placement: placement,
eventsEnabled: eventsEnabled,
modifiers: modifiers
});
// schedule an update to make sure everything gets positioned correct
// after being instantiated
this._popper.scheduleUpdate();
}
}, {
key: '_destroyPopper',
value: function _destroyPopper() {
if (this._popper) {
this._popper.destroy();
}
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
var _props2 = this.props,
component = _props2.component,
innerRef = _props2.innerRef,
placement = _props2.placement,
eventsEnabled = _props2.eventsEnabled,
modifiers = _props2.modifiers,
children = _props2.children,
restProps = _objectWithoutProperties(_props2, ['component', 'innerRef', 'placement', 'eventsEnabled', 'modifiers', 'children']);
var popperRef = function popperRef(node) {
_this2._node = node;
if (typeof innerRef === 'function') {
innerRef(node);
}
};
var popperStyle = this._getPopperStyle();
var popperPlacement = this._getPopperPlacement();
var popperHide = this._getPopperHide();
if (typeof children === 'function') {
var _popperProps;
var popperProps = (_popperProps = {
ref: popperRef,
style: popperStyle
}, _defineProperty(_popperProps, 'data-placement', popperPlacement), _defineProperty(_popperProps, 'data-x-out-of-boundaries', popperHide), _popperProps);
return children({
popperProps: popperProps,
restProps: restProps,
scheduleUpdate: this._popper && this._popper.scheduleUpdate
});
}
var componentProps = _extends({}, restProps, {
style: _extends({}, restProps.style, popperStyle),
'data-placement': popperPlacement,
'data-x-out-of-boundaries': popperHide
});
if (typeof component === 'string') {
componentProps.ref = popperRef;
} else {
componentProps.innerRef = popperRef;
}
return (0, _react.createElement)(component, componentProps, children);
}
}]);
return Popper;
}(_react.Component);
Popper.contextTypes = {
popperManager: _propTypes2.default.object.isRequired
};
Popper.childContextTypes = {
popper: _propTypes2.default.object.isRequired
};
Popper.propTypes = {
component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
innerRef: _propTypes2.default.func,
placement: _propTypes2.default.oneOf(_popper2.default.placements),
eventsEnabled: _propTypes2.default.bool,
modifiers: _propTypes2.default.object,
children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};
Popper.defaultProps = {
component: 'div',
placement: 'bottom',
eventsEnabled: true,
modifiers: {}
};
exports.default = Popper;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/**!
* @fileOverview Kickass library to create and place poppers near their reference elements.
* @version 1.12.6
* @license
* Copyright (c) 2016 Federico Zivolo and contributors
*
* 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.
*/
(function (global, factory) {
true ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Popper = factory());
}(this, (function () { 'use strict';
var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox'];
var timeoutDuration = 0;
for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) {
if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) {
timeoutDuration = 1;
break;
}
}
function microtaskDebounce(fn) {
var called = false;
return function () {
if (called) {
return;
}
called = true;
Promise.resolve().then(function () {
called = false;
fn();
});
};
}
function taskDebounce(fn) {
var scheduled = false;
return function () {
if (!scheduled) {
scheduled = true;
setTimeout(function () {
scheduled = false;
fn();
}, timeoutDuration);
}
};
}
var supportsMicroTasks = isBrowser && window.Promise;
/**
* Create a debounced version of a method, that's asynchronously deferred
* but called in the minimum time possible.
*
* @method
* @memberof Popper.Utils
* @argument {Function} fn
* @returns {Function}
*/
var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce;
/**
* Check if the given variable is a function
* @method
* @memberof Popper.Utils
* @argument {Any} functionToCheck - variable to check
* @returns {Boolean} answer to: is a function?
*/
function isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
/**
* Get CSS computed property of the given element
* @method
* @memberof Popper.Utils
* @argument {Eement} element
* @argument {String} property
*/
function getStyleComputedProperty(element, property) {
if (element.nodeType !== 1) {
return [];
}
// NOTE: 1 DOM access here
var css = window.getComputedStyle(element, null);
return property ? css[property] : css;
}
/**
* Returns the parentNode or the host of the element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} parent
*/
function getParentNode(element) {
if (element.nodeName === 'HTML') {
return element;
}
return element.parentNode || element.host;
}
/**
* Returns the scrolling parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} scroll parent
*/
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return window.document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
var _getStyleComputedProp = getStyleComputedProperty(element),
overflow = _getStyleComputedProp.overflow,
overflowX = _getStyleComputedProp.overflowX,
overflowY = _getStyleComputedProp.overflowY;
if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
/**
* Returns the offset parent of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Element} offset parent
*/
function getOffsetParent(element) {
// NOTE: 1 DOM access here
var offsetParent = element && element.offsetParent;
var nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
if (element) {
return element.ownerDocument.documentElement;
}
return window.document.documentElement;
}
// .offsetParent will return the closest TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
function isOffsetContainer(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY') {
return false;
}
return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element;
}
/**
* Finds the root node (document, shadowDOM root) of the given element
* @method
* @memberof Popper.Utils
* @argument {Element} node
* @returns {Element} root node
*/
function getRoot(node) {
if (node.parentNode !== null) {
return getRoot(node.parentNode);
}
return node;
}
/**
* Finds the offset parent common to the two provided nodes
* @method
* @memberof Popper.Utils
* @argument {Element} element1
* @argument {Element} element2
* @returns {Element} common offset parent
*/
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return window.document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
var start = order ? element1 : element2;
var end = order ? element2 : element1;
// Get common ancestor container
var range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
var commonAncestorContainer = range.commonAncestorContainer;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
var element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
/**
* Gets the scroll value of the given element in the given side (top and left)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {String} side `top` or `left`
* @returns {number} amount of scrolled pixels
*/
function getScroll(element) {
var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top';
var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft';
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
var html = element.ownerDocument.documentElement;
var scrollingElement = element.ownerDocument.scrollingElement || html;
return scrollingElement[upperSide];
}
return element[upperSide];
}
/*
* Sum or subtract the element scroll values (left and top) from a given rect object
* @method
* @memberof Popper.Utils
* @param {Object} rect - Rect object you want to change
* @param {HTMLElement} element - The element from the function reads the scroll values
* @param {Boolean} subtract - set to true if you want to subtract the scroll values
* @return {Object} rect - The modifier rect object
*/
function includeScroll(rect, element) {
var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
var modifier = subtract ? -1 : 1;
rect.top += scrollTop * modifier;
rect.bottom += scrollTop * modifier;
rect.left += scrollLeft * modifier;
rect.right += scrollLeft * modifier;
return rect;
}
/*
* Helper to detect borders of a given element
* @method
* @memberof Popper.Utils
* @param {CSSStyleDeclaration} styles
* Result of `getStyleComputedProperty` on the given element
* @param {String} axis - `x` or `y`
* @return {number} borders - The borders size of the given axis
*/
function getBordersSize(styles, axis) {
var sideA = axis === 'x' ? 'Left' : 'Top';
var sideB = sideA === 'Left' ? 'Right' : 'Bottom';
return +styles['border' + sideA + 'Width'].split('px')[0] + +styles['border' + sideB + 'Width'].split('px')[0];
}
/**
* Tells if you are running Internet Explorer 10
* @method
* @memberof Popper.Utils
* @returns {Boolean} isIE10
*/
var isIE10 = undefined;
var isIE10$1 = function () {
if (isIE10 === undefined) {
isIE10 = navigator.appVersion.indexOf('MSIE 10') !== -1;
}
return isIE10;
};
function getSize(axis, body, html, computedStyle) {
return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE10$1() ? html['offset' + axis] + computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')] + computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')] : 0);
}
function getWindowSizes() {
var body = window.document.body;
var html = window.document.documentElement;
var computedStyle = isIE10$1() && window.getComputedStyle(html);
return {
height: getSize('Height', body, html, computedStyle),
width: getSize('Width', body, html, computedStyle)
};
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
/**
* Given element offsets, generate an output similar to getBoundingClientRect
* @method
* @memberof Popper.Utils
* @argument {Object} offsets
* @returns {Object} ClientRect like output
*/
function getClientRect(offsets) {
return _extends({}, offsets, {
right: offsets.left + offsets.width,
bottom: offsets.top + offsets.height
});
}
/**
* Get bounding client rect of given element
* @method
* @memberof Popper.Utils
* @param {HTMLElement} element
* @return {Object} client rect
*/
function getBoundingClientRect(element) {
var rect = {};
// IE10 10 FIX: Please, don't ask, the element isn't
// considered in DOM in some circumstances...
// This isn't reproducible in IE10 compatibility mode of IE11
if (isIE10$1()) {
try {
rect = element.getBoundingClientRect();
var scrollTop = getScroll(element, 'top');
var scrollLeft = getScroll(element, 'left');
rect.top += scrollTop;
rect.left += scrollLeft;
rect.bottom += scrollTop;
rect.right += scrollLeft;
} catch (err) {}
} else {
rect = element.getBoundingClientRect();
}
var result = {
left: rect.left,
top: rect.top,
width: rect.right - rect.left,
height: rect.bottom - rect.top
};
// subtract scrollbar size from sizes
var sizes = element.nodeName === 'HTML' ? getWindowSizes() : {};
var width = sizes.width || element.clientWidth || result.right - result.left;
var height = sizes.height || element.clientHeight || result.bottom - result.top;
var horizScrollbar = element.offsetWidth - width;
var vertScrollbar = element.offsetHeight - height;
// if an hypothetical scrollbar is detected, we must be sure it's not a `border`
// we make this check conditional for performance reasons
if (horizScrollbar || vertScrollbar) {
var styles = getStyleComputedProperty(element);
horizScrollbar -= getBordersSize(styles, 'x');
vertScrollbar -= getBordersSize(styles, 'y');
result.width -= horizScrollbar;
result.height -= vertScrollbar;
}
return getClientRect(result);
}
function getOffsetRectRelativeToArbitraryNode(children, parent) {
var isIE10 = isIE10$1();
var isHTML = parent.nodeName === 'HTML';
var childrenRect = getBoundingClientRect(children);
var parentRect = getBoundingClientRect(parent);
var scrollParent = getScrollParent(children);
var styles = getStyleComputedProperty(parent);
var borderTopWidth = +styles.borderTopWidth.split('px')[0];
var borderLeftWidth = +styles.borderLeftWidth.split('px')[0];
var offsets = getClientRect({
top: childrenRect.top - parentRect.top - borderTopWidth,
left: childrenRect.left - parentRect.left - borderLeftWidth,
width: childrenRect.width,
height: childrenRect.height
});
offsets.marginTop = 0;
offsets.marginLeft = 0;
// Subtract margins of documentElement in case it's being used as parent
// we do this only on HTML because it's the only element that behaves
// differently when margins are applied to it. The margins are included in
// the box of the documentElement, in the other cases not.
if (!isIE10 && isHTML) {
var marginTop = +styles.marginTop.split('px')[0];
var marginLeft = +styles.marginLeft.split('px')[0];
offsets.top -= borderTopWidth - marginTop;
offsets.bottom -= borderTopWidth - marginTop;
offsets.left -= borderLeftWidth - marginLeft;
offsets.right -= borderLeftWidth - marginLeft;
// Attach marginTop and marginLeft because in some circumstances we may need them
offsets.marginTop = marginTop;
offsets.marginLeft = marginLeft;
}
if (isIE10 ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') {
offsets = includeScroll(offsets, parent);
}
return offsets;
}
function getViewportOffsetRectRelativeToArtbitraryNode(element) {
var html = element.ownerDocument.documentElement;
var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html);
var width = Math.max(html.clientWidth, window.innerWidth || 0);
var height = Math.max(html.clientHeight, window.innerHeight || 0);
var scrollTop = getScroll(html);
var scrollLeft = getScroll(html, 'left');
var offset = {
top: scrollTop - relativeOffset.top + relativeOffset.marginTop,
left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft,
width: width,
height: height
};
return getClientRect(offset);
}
/**
* Check if the given element is fixed or is inside a fixed parent
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @argument {Element} customContainer
* @returns {Boolean} answer to "isFixed?"
*/
function isFixed(element) {
var nodeName = element.nodeName;
if (nodeName === 'BODY' || nodeName === 'HTML') {
return false;
}
if (getStyleComputedProperty(element, 'position') === 'fixed') {
return true;
}
return isFixed(getParentNode(element));
}
/**
* Computed the boundaries limits and return them
* @method
* @memberof Popper.Utils
* @param {HTMLElement} popper
* @param {HTMLElement} reference
* @param {number} padding
* @param {HTMLElement} boundariesElement - Element used to define the boundaries
* @returns {Object} Coordinates of the boundaries
*/
function getBoundaries(popper, reference, padding, boundariesElement) {
// NOTE: 1 DOM access here
var boundaries = { top: 0, left: 0 };
var offsetParent = findCommonOffsetParent(popper, reference);
// Handle viewport case
if (boundariesElement === 'viewport') {
boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent);
} else {
// Handle other cases based on DOM element used as boundaries
var boundariesNode = void 0;
if (boundariesElement === 'scrollParent') {
boundariesNode = getScrollParent(getParentNode(popper));
if (boundariesNode.nodeName === 'BODY') {
boundariesNode = popper.ownerDocument.documentElement;
}
} else if (boundariesElement === 'window') {
boundariesNode = popper.ownerDocument.documentElement;
} else {
boundariesNode = boundariesElement;
}
var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent);
// In case of HTML, we need a different computation
if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) {
var _getWindowSizes = getWindowSizes(),
height = _getWindowSizes.height,
width = _getWindowSizes.width;
boundaries.top += offsets.top - offsets.marginTop;
boundaries.bottom = height + offsets.top;
boundaries.left += offsets.left - offsets.marginLeft;
boundaries.right = width + offsets.left;
} else {
// for all the other DOM elements, this one is good
boundaries = offsets;
}
}
// Add paddings
boundaries.left += padding;
boundaries.top += padding;
boundaries.right -= padding;
boundaries.bottom -= padding;
return boundaries;
}
function getArea(_ref) {
var width = _ref.width,
height = _ref.height;
return width * height;
}
/**
* Utility used to transform the `auto` placement to the placement with more
* available space.
* @method
* @memberof Popper.Utils
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) {
var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
if (placement.indexOf('auto') === -1) {
return placement;
}
var boundaries = getBoundaries(popper, reference, padding, boundariesElement);
var rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
var sortedAreas = Object.keys(rects).map(function (key) {
return _extends({
key: key
}, rects[key], {
area: getArea(rects[key])
});
}).sort(function (a, b) {
return b.area - a.area;
});
var filteredAreas = sortedAreas.filter(function (_ref2) {
var width = _ref2.width,
height = _ref2.height;
return width >= popper.clientWidth && height >= popper.clientHeight;
});
var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
var variation = placement.split('-')[1];
return computedPlacement + (variation ? '-' + variation : '');
}
/**
* Get offsets to the reference element
* @method
* @memberof Popper.Utils
* @param {Object} state
* @param {Element} popper - the popper element
* @param {Element} reference - the reference element (the popper will be relative to this)
* @returns {Object} An object containing the offsets which will be applied to the popper
*/
function getReferenceOffsets(state, popper, reference) {
var commonOffsetParent = findCommonOffsetParent(popper, reference);
return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent);
}
/**
* Get the outer sizes of the given element (offset size + margins)
* @method
* @memberof Popper.Utils
* @argument {Element} element
* @returns {Object} object containing width and height properties
*/
function getOuterSizes(element) {
var styles = window.getComputedStyle(element);
var x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom);
var y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight);
var result = {
width: element.offsetWidth + y,
height: element.offsetHeight + x
};
return result;
}
/**
* Get the opposite placement of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement
* @returns {String} flipped placement
*/
function getOppositePlacement(placement) {
var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, function (matched) {
return hash[matched];
});
}
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
var popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
var popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
var isHoriz = ['right', 'left'].indexOf(placement) !== -1;
var mainSide = isHoriz ? 'top' : 'left';
var secondarySide = isHoriz ? 'left' : 'top';
var measurement = isHoriz ? 'height' : 'width';
var secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
/**
* Mimics the `find` method of Array
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function find(arr, check) {
// use native find if supported
if (Array.prototype.find) {
return arr.find(check);
}
// use `filter` to obtain the same behavior of `find`
return arr.filter(check)[0];
}
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
function findIndex(arr, prop, value) {
// use native findIndex if supported
if (Array.prototype.findIndex) {
return arr.findIndex(function (cur) {
return cur[prop] === value;
});
}
// use `find` + `indexOf` if `findIndex` isn't supported
var match = find(arr, function (obj) {
return obj[prop] === value;
});
return arr.indexOf(match);
}
/**
* Loop trough the list of modifiers and run them in order,
* each of them will then edit the data object.
* @method
* @memberof Popper.Utils
* @param {dataObject} data
* @param {Array} modifiers
* @param {String} ends - Optional modifier name used as stopper
* @returns {dataObject}
*/
function runModifiers(modifiers, data, ends) {
var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends));
modifiersToRun.forEach(function (modifier) {
if (modifier['function']) {
// eslint-disable-line dot-notation
console.warn('`modifier.function` is deprecated, use `modifier.fn`!');
}
var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation
if (modifier.enabled && isFunction(fn)) {
// Add properties to offsets to make them a complete clientRect object
// we do this before each modifier to make sure the previous one doesn't
// mess with these values
data.offsets.popper = getClientRect(data.offsets.popper);
data.offsets.reference = getClientRect(data.offsets.reference);
data = fn(data, modifier);
}
});
return data;
}
/**
* Updates the position of the popper, computing the new offsets and applying
* the new style.<br />
* Prefer `scheduleUpdate` over `update` because of performance reasons.
* @method
* @memberof Popper
*/
function update() {
// if popper is destroyed, don't perform any further update
if (this.state.isDestroyed) {
return;
}
var data = {
instance: this,
styles: {},
arrowStyles: {},
attributes: {},
flipped: false,
offsets: {}
};
// compute reference element offsets
data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding);
// store the computed placement inside `originalPlacement`
data.originalPlacement = data.placement;
// compute the popper offsets
data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement);
data.offsets.popper.position = 'absolute';
// run the modifiers
data = runModifiers(this.modifiers, data);
// the first `update` will call `onCreate` callback
// the other ones will call `onUpdate` callback
if (!this.state.isCreated) {
this.state.isCreated = true;
this.options.onCreate(data);
} else {
this.options.onUpdate(data);
}
}
/**
* Helper used to know if the given modifier is enabled.
* @method
* @memberof Popper.Utils
* @returns {Boolean}
*/
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(function (_ref) {
var name = _ref.name,
enabled = _ref.enabled;
return enabled && name === modifierName;
});
}
/**
* Get the prefixed supported property name
* @method
* @memberof Popper.Utils
* @argument {String} property (camelCase)
* @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
*/
function getSupportedPropertyName(property) {
var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
var upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (var i = 0; i < prefixes.length - 1; i++) {
var prefix = prefixes[i];
var toCheck = prefix ? '' + prefix + upperProp : property;
if (typeof window.document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
/**
* Destroy the popper
* @method
* @memberof Popper
*/
function destroy() {
this.state.isDestroyed = true;
// touch DOM only if `applyStyle` modifier is enabled
if (isModifierEnabled(this.modifiers, 'applyStyle')) {
this.popper.removeAttribute('x-placement');
this.popper.style.left = '';
this.popper.style.position = '';
this.popper.style.top = '';
this.popper.style[getSupportedPropertyName('transform')] = '';
}
this.disableEventListeners();
// remove the popper if user explicity asked for the deletion on destroy
// do not use `remove` because IE11 doesn't support it
if (this.options.removeOnDestroy) {
this.popper.parentNode.removeChild(this.popper);
}
return this;
}
/**
* Get the window associated with the element
* @argument {Element} element
* @returns {Window}
*/
function getWindow(element) {
var ownerDocument = element.ownerDocument;
return ownerDocument ? ownerDocument.defaultView : window;
}
function attachToScrollParents(scrollParent, event, callback, scrollParents) {
var isBody = scrollParent.nodeName === 'BODY';
var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent;
target.addEventListener(event, callback, { passive: true });
if (!isBody) {
attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents);
}
scrollParents.push(target);
}
/**
* Setup needed event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function setupEventListeners(reference, options, state, updateBound) {
// Resize event listener on window
state.updateBound = updateBound;
getWindow(reference).addEventListener('resize', state.updateBound, { passive: true });
// Scroll event listener on scroll parents
var scrollElement = getScrollParent(reference);
attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents);
state.scrollElement = scrollElement;
state.eventsEnabled = true;
return state;
}
/**
* It will add resize/scroll events and start recalculating
* position of the popper element when they are triggered.
* @method
* @memberof Popper
*/
function enableEventListeners() {
if (!this.state.eventsEnabled) {
this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate);
}
}
/**
* Remove event listeners used to update the popper position
* @method
* @memberof Popper.Utils
* @private
*/
function removeEventListeners(reference, state) {
// Remove resize event listener on window
getWindow(reference).removeEventListener('resize', state.updateBound);
// Remove scroll event listener on scroll parents
state.scrollParents.forEach(function (target) {
target.removeEventListener('scroll', state.updateBound);
});
// Reset state
state.updateBound = null;
state.scrollParents = [];
state.scrollElement = null;
state.eventsEnabled = false;
return state;
}
/**
* It will remove resize/scroll events and won't recalculate popper position
* when they are triggered. It also won't trigger onUpdate callback anymore,
* unless you call `update` method manually.
* @method
* @memberof Popper
*/
function disableEventListeners() {
if (this.state.eventsEnabled) {
window.cancelAnimationFrame(this.scheduleUpdate);
this.state = removeEventListeners(this.reference, this.state);
}
}
/**
* Tells if a given input is a number
* @method
* @memberof Popper.Utils
* @param {*} input to check
* @return {Boolean}
*/
function isNumeric(n) {
return n !== '' && !isNaN(parseFloat(n)) && isFinite(n);
}
/**
* Set the style to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the style to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setStyles(element, styles) {
Object.keys(styles).forEach(function (prop) {
var unit = '';
// add unit if the value is numeric and is one of the following
if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) {
unit = 'px';
}
element.style[prop] = styles[prop] + unit;
});
}
/**
* Set the attributes to the given popper
* @method
* @memberof Popper.Utils
* @argument {Element} element - Element to apply the attributes to
* @argument {Object} styles
* Object with a list of properties and values which will be applied to the element
*/
function setAttributes(element, attributes) {
Object.keys(attributes).forEach(function (prop) {
var value = attributes[prop];
if (value !== false) {
element.setAttribute(prop, attributes[prop]);
} else {
element.removeAttribute(prop);
}
});
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} data.styles - List of style properties - values to apply to popper element
* @argument {Object} data.attributes - List of attribute properties - values to apply to popper element
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The same data object
*/
function applyStyle(data) {
// any property present in `data.styles` will be applied to the popper,
// in this way we can make the 3rd party modifiers add custom styles to it
// Be aware, modifiers could override the properties defined in the previous
// lines of this modifier!
setStyles(data.instance.popper, data.styles);
// any property present in `data.attributes` will be applied to the popper,
// they will be set as HTML attributes of the element
setAttributes(data.instance.popper, data.attributes);
// if arrowElement is defined and arrowStyles has some properties
if (data.arrowElement && Object.keys(data.arrowStyles).length) {
setStyles(data.arrowElement, data.arrowStyles);
}
return data;
}
/**
* Set the x-placement attribute before everything else because it could be used
* to add margins to the popper margins needs to be calculated to get the
* correct popper offsets.
* @method
* @memberof Popper.modifiers
* @param {HTMLElement} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Popper.js options
*/
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
var referenceOffsets = getReferenceOffsets(state, popper, reference);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: 'absolute' });
return options;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function computeStyle(data, options) {
var x = options.x,
y = options.y;
var popper = data.offsets.popper;
// Remove this legacy support in Popper.js v2
var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'applyStyle';
}).gpuAcceleration;
if (legacyGpuAccelerationOption !== undefined) {
console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!');
}
var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration;
var offsetParent = getOffsetParent(data.instance.popper);
var offsetParentRect = getBoundingClientRect(offsetParent);
// Styles
var styles = {
position: popper.position
};
// floor sides to avoid blurry text
var offsets = {
left: Math.floor(popper.left),
top: Math.floor(popper.top),
bottom: Math.floor(popper.bottom),
right: Math.floor(popper.right)
};
var sideA = x === 'bottom' ? 'top' : 'bottom';
var sideB = y === 'right' ? 'left' : 'right';
// if gpuAcceleration is set to `true` and transform is supported,
// we use `translate3d` to apply the position to the popper we
// automatically use the supported prefixed version if needed
var prefixedProperty = getSupportedPropertyName('transform');
// now, let's make a step back and look at this code closely (wtf?)
// If the content of the popper grows once it's been positioned, it
// may happen that the popper gets misplaced because of the new content
// overflowing its reference element
// To avoid this problem, we provide two options (x and y), which allow
// the consumer to define the offset origin.
// If we position a popper on top of a reference element, we can set
// `x` to `top` to make the popper grow towards its top instead of
// its bottom.
var left = void 0,
top = void 0;
if (sideA === 'bottom') {
top = -offsetParentRect.height + offsets.bottom;
} else {
top = offsets.top;
}
if (sideB === 'right') {
left = -offsetParentRect.width + offsets.right;
} else {
left = offsets.left;
}
if (gpuAcceleration && prefixedProperty) {
styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)';
styles[sideA] = 0;
styles[sideB] = 0;
styles.willChange = 'transform';
} else {
// othwerise, we use the standard `top`, `left`, `bottom` and `right` properties
var invertTop = sideA === 'bottom' ? -1 : 1;
var invertLeft = sideB === 'right' ? -1 : 1;
styles[sideA] = top * invertTop;
styles[sideB] = left * invertLeft;
styles.willChange = sideA + ', ' + sideB;
}
// Attributes
var attributes = {
'x-placement': data.placement
};
// Update `data` attributes, styles and arrowStyles
data.attributes = _extends({}, attributes, data.attributes);
data.styles = _extends({}, styles, data.styles);
data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles);
return data;
}
/**
* Helper used to know if the given modifier depends from another one.<br />
* It checks if the needed modifier is listed and enabled.
* @method
* @memberof Popper.Utils
* @param {Array} modifiers - list of modifiers
* @param {String} requestingName - name of requesting modifier
* @param {String} requestedName - name of requested modifier
* @returns {Boolean}
*/
function isModifierRequired(modifiers, requestingName, requestedName) {
var requesting = find(modifiers, function (_ref) {
var name = _ref.name;
return name === requestingName;
});
var isRequired = !!requesting && modifiers.some(function (modifier) {
return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order;
});
if (!isRequired) {
var _requesting = '`' + requestingName + '`';
var requested = '`' + requestedName + '`';
console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!');
}
return isRequired;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function arrow(data, options) {
// arrow depends on keepTogether in order to work
if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) {
return data;
}
var arrowElement = options.element;
// if arrowElement is a string, suppose it's a CSS selector
if (typeof arrowElement === 'string') {
arrowElement = data.instance.popper.querySelector(arrowElement);
// if arrowElement is not found, don't run the modifier
if (!arrowElement) {
return data;
}
} else {
// if the arrowElement isn't a query selector we must check that the
// provided DOM node is child of its popper node
if (!data.instance.popper.contains(arrowElement)) {
console.warn('WARNING: `arrow.element` must be child of its popper element!');
return data;
}
}
var placement = data.placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isVertical = ['left', 'right'].indexOf(placement) !== -1;
var len = isVertical ? 'height' : 'width';
var sideCapitalized = isVertical ? 'Top' : 'Left';
var side = sideCapitalized.toLowerCase();
var altSide = isVertical ? 'left' : 'top';
var opSide = isVertical ? 'bottom' : 'right';
var arrowElementSize = getOuterSizes(arrowElement)[len];
//
// extends keepTogether behavior making sure the popper and its
// reference have enough pixels in conjuction
//
// top/left side
if (reference[opSide] - arrowElementSize < popper[side]) {
data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize);
}
// bottom/right side
if (reference[side] + arrowElementSize > popper[opSide]) {
data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide];
}
// compute center of the popper
var center = reference[side] + reference[len] / 2 - arrowElementSize / 2;
// Compute the sideValue using the updated popper offsets
// take popper margin in account because we don't have this info available
var popperMarginSide = getStyleComputedProperty(data.instance.popper, 'margin' + sideCapitalized).replace('px', '');
var sideValue = center - getClientRect(data.offsets.popper)[side] - popperMarginSide;
// prevent arrowElement from being placed not contiguously to its popper
sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0);
data.arrowElement = arrowElement;
data.offsets.arrow = {};
data.offsets.arrow[side] = Math.round(sideValue);
data.offsets.arrow[altSide] = ''; // make sure to unset any eventual altSide value from the DOM node
return data;
}
/**
* Get the opposite placement variation of the given one
* @method
* @memberof Popper.Utils
* @argument {String} placement variation
* @returns {String} flipped placement variation
*/
function getOppositeVariation(variation) {
if (variation === 'end') {
return 'start';
} else if (variation === 'start') {
return 'end';
}
return variation;
}
/**
* List of accepted placements to use as values of the `placement` option.<br />
* Valid placements are:
* - `auto`
* - `top`
* - `right`
* - `bottom`
* - `left`
*
* Each placement can have a variation from this list:
* - `-start`
* - `-end`
*
* Variations are interpreted easily if you think of them as the left to right
* written languages. Horizontally (`top` and `bottom`), `start` is left and `end`
* is right.<br />
* Vertically (`left` and `right`), `start` is top and `end` is bottom.
*
* Some valid examples are:
* - `top-end` (on top of reference, right aligned)
* - `right-start` (on right of reference, top aligned)
* - `bottom` (on bottom, centered)
* - `auto-right` (on the side with more space available, alignment depends by placement)
*
* @static
* @type {Array}
* @enum {String}
* @readonly
* @method placements
* @memberof Popper
*/
var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start'];
// Get rid of `auto` `auto-start` and `auto-end`
var validPlacements = placements.slice(3);
/**
* Given an initial placement, returns all the subsequent placements
* clockwise (or counter-clockwise).
*
* @method
* @memberof Popper.Utils
* @argument {String} placement - A valid placement (it accepts variations)
* @argument {Boolean} counter - Set to true to walk the placements counterclockwise
* @returns {Array} placements including their variations
*/
function clockwise(placement) {
var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var index = validPlacements.indexOf(placement);
var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index));
return counter ? arr.reverse() : arr;
}
var BEHAVIORS = {
FLIP: 'flip',
CLOCKWISE: 'clockwise',
COUNTERCLOCKWISE: 'counterclockwise'
};
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function flip(data, options) {
// if `inner` modifier is enabled, we can't use the `flip` modifier
if (isModifierEnabled(data.instance.modifiers, 'inner')) {
return data;
}
if (data.flipped && data.placement === data.originalPlacement) {
// seems like flip is trying to loop, probably there's not enough space on any of the flippable sides
return data;
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement);
var placement = data.placement.split('-')[0];
var placementOpposite = getOppositePlacement(placement);
var variation = data.placement.split('-')[1] || '';
var flipOrder = [];
switch (options.behavior) {
case BEHAVIORS.FLIP:
flipOrder = [placement, placementOpposite];
break;
case BEHAVIORS.CLOCKWISE:
flipOrder = clockwise(placement);
break;
case BEHAVIORS.COUNTERCLOCKWISE:
flipOrder = clockwise(placement, true);
break;
default:
flipOrder = options.behavior;
}
flipOrder.forEach(function (step, index) {
if (placement !== step || flipOrder.length === index + 1) {
return data;
}
placement = data.placement.split('-')[0];
placementOpposite = getOppositePlacement(placement);
var popperOffsets = data.offsets.popper;
var refOffsets = data.offsets.reference;
// using floor because the reference offsets may contain decimals we are not going to consider here
var floor = Math.floor;
var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom);
var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left);
var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right);
var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top);
var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom);
var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom;
// flip the variation if required
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom);
if (overlapsRef || overflowsBoundaries || flippedVariation) {
// this boolean to detect any flip loop
data.flipped = true;
if (overlapsRef || overflowsBoundaries) {
placement = flipOrder[index + 1];
}
if (flippedVariation) {
variation = getOppositeVariation(variation);
}
data.placement = placement + (variation ? '-' + variation : '');
// this object contains `position`, we want to preserve it along with
// any additional property we may add in the future
data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement));
data = runModifiers(data.instance.modifiers, data, 'flip');
}
});
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function keepTogether(data) {
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var placement = data.placement.split('-')[0];
var floor = Math.floor;
var isVertical = ['top', 'bottom'].indexOf(placement) !== -1;
var side = isVertical ? 'right' : 'bottom';
var opSide = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
if (popper[side] < floor(reference[opSide])) {
data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement];
}
if (popper[opSide] > floor(reference[side])) {
data.offsets.popper[opSide] = floor(reference[side]);
}
return data;
}
/**
* Converts a string containing value + unit into a px value number
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} str - Value + unit string
* @argument {String} measurement - `height` or `width`
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @returns {Number|String}
* Value in pixels, or original string if no values were extracted
*/
function toValue(str, measurement, popperOffsets, referenceOffsets) {
// separate value from unit
var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/);
var value = +split[1];
var unit = split[2];
// If it's not a number it's an operator, I guess
if (!value) {
return str;
}
if (unit.indexOf('%') === 0) {
var element = void 0;
switch (unit) {
case '%p':
element = popperOffsets;
break;
case '%':
case '%r':
default:
element = referenceOffsets;
}
var rect = getClientRect(element);
return rect[measurement] / 100 * value;
} else if (unit === 'vh' || unit === 'vw') {
// if is a vh or vw, we calculate the size based on the viewport
var size = void 0;
if (unit === 'vh') {
size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
} else {
size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
}
return size / 100 * value;
} else {
// if is an explicit pixel unit, we get rid of the unit and keep the value
// if is an implicit unit, it's px, and we return just the value
return value;
}
}
/**
* Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
* @function
* @memberof {modifiers~offset}
* @private
* @argument {String} offset
* @argument {Object} popperOffsets
* @argument {Object} referenceOffsets
* @argument {String} basePlacement
* @returns {Array} a two cells array with x and y offsets in numbers
*/
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
var offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
var fragments = offset.split(/(\+|\-)/).map(function (frag) {
return frag.trim();
});
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
var divider = fragments.indexOf(find(fragments, function (frag) {
return frag.search(/,|\s/) !== -1;
}));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
var splitRegex = /\s*,\s*|\s+/;
var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map(function (op, index) {
// Most of the units rely on the orientation of the popper
var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
var mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce(function (a, b) {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(function (str) {
return toValue(str, measurement, popperOffsets, referenceOffsets);
});
});
// Loop trough the offsets arrays and execute the operations
ops.forEach(function (op, index) {
op.forEach(function (frag, index2) {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @argument {Number|String} options.offset=0
* The offset value as described in the modifier description
* @returns {Object} The data object, properly modified
*/
function offset(data, _ref) {
var offset = _ref.offset;
var placement = data.placement,
_data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var basePlacement = placement.split('-')[0];
var offsets = void 0;
if (isNumeric(+offset)) {
offsets = [+offset, 0];
} else {
offsets = parseOffset(offset, popper, reference, basePlacement);
}
if (basePlacement === 'left') {
popper.top += offsets[0];
popper.left -= offsets[1];
} else if (basePlacement === 'right') {
popper.top += offsets[0];
popper.left += offsets[1];
} else if (basePlacement === 'top') {
popper.left += offsets[0];
popper.top -= offsets[1];
} else if (basePlacement === 'bottom') {
popper.left += offsets[0];
popper.top += offsets[1];
}
data.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function preventOverflow(data, options) {
var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper);
// If offsetParent is the reference element, we really want to
// go one step up and use the next offsetParent as reference to
// avoid to make this modifier completely useless and look like broken
if (data.instance.reference === boundariesElement) {
boundariesElement = getOffsetParent(boundariesElement);
}
var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement);
options.boundaries = boundaries;
var order = options.priority;
var popper = data.offsets.popper;
var check = {
primary: function primary(placement) {
var value = popper[placement];
if (popper[placement] < boundaries[placement] && !options.escapeWithReference) {
value = Math.max(popper[placement], boundaries[placement]);
}
return defineProperty({}, placement, value);
},
secondary: function secondary(placement) {
var mainSide = placement === 'right' ? 'left' : 'top';
var value = popper[mainSide];
if (popper[placement] > boundaries[placement] && !options.escapeWithReference) {
value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height));
}
return defineProperty({}, mainSide, value);
}
};
order.forEach(function (placement) {
var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary';
popper = _extends({}, popper, check[side](placement));
});
data.offsets.popper = popper;
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function shift(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var shiftvariation = placement.split('-')[1];
// if shift shiftvariation is specified, run the modifier
if (shiftvariation) {
var _data$offsets = data.offsets,
reference = _data$offsets.reference,
popper = _data$offsets.popper;
var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1;
var side = isVertical ? 'left' : 'top';
var measurement = isVertical ? 'width' : 'height';
var shiftOffsets = {
start: defineProperty({}, side, reference[side]),
end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement])
};
data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]);
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by update method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function hide(data) {
if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) {
return data;
}
var refRect = data.offsets.reference;
var bound = find(data.instance.modifiers, function (modifier) {
return modifier.name === 'preventOverflow';
}).boundaries;
if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === true) {
return data;
}
data.hide = true;
data.attributes['x-out-of-boundaries'] = '';
} else {
// Avoid unnecessary DOM access if visibility hasn't changed
if (data.hide === false) {
return data;
}
data.hide = false;
data.attributes['x-out-of-boundaries'] = false;
}
return data;
}
/**
* @function
* @memberof Modifiers
* @argument {Object} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {Object} The data object, properly modified
*/
function inner(data) {
var placement = data.placement;
var basePlacement = placement.split('-')[0];
var _data$offsets = data.offsets,
popper = _data$offsets.popper,
reference = _data$offsets.reference;
var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1;
var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1;
popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0);
data.placement = getOppositePlacement(placement);
data.offsets.popper = getClientRect(popper);
return data;
}
/**
* Modifier function, each modifier can have a function of this type assigned
* to its `fn` property.<br />
* These functions will be called on each update, this means that you must
* make sure they are performant enough to avoid performance bottlenecks.
*
* @function ModifierFn
* @argument {dataObject} data - The data object generated by `update` method
* @argument {Object} options - Modifiers configuration and options
* @returns {dataObject} The data object, properly modified
*/
/**
* Modifiers are plugins used to alter the behavior of your poppers.<br />
* Popper.js uses a set of 9 modifiers to provide all the basic functionalities
* needed by the library.
*
* Usually you don't want to override the `order`, `fn` and `onLoad` props.
* All the other properties are configurations that could be tweaked.
* @namespace modifiers
*/
var modifiers = {
/**
* Modifier used to shift the popper on the start or end of its reference
* element.<br />
* It will read the variation of the `placement` property.<br />
* It can be one either `-end` or `-start`.
* @memberof modifiers
* @inner
*/
shift: {
/** @prop {number} order=100 - Index used to define the order of execution */
order: 100,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: shift
},
/**
* The `offset` modifier can shift your popper on both its axis.
*
* It accepts the following units:
* - `px` or unitless, interpreted as pixels
* - `%` or `%r`, percentage relative to the length of the reference element
* - `%p`, percentage relative to the length of the popper element
* - `vw`, CSS viewport width unit
* - `vh`, CSS viewport height unit
*
* For length is intended the main axis relative to the placement of the popper.<br />
* This means that if the placement is `top` or `bottom`, the length will be the
* `width`. In case of `left` or `right`, it will be the height.
*
* You can provide a single value (as `Number` or `String`), or a pair of values
* as `String` divided by a comma or one (or more) white spaces.<br />
* The latter is a deprecated method because it leads to confusion and will be
* removed in v2.<br />
* Additionally, it accepts additions and subtractions between different units.
* Note that multiplications and divisions aren't supported.
*
* Valid examples are:
* ```
* 10
* '10%'
* '10, 10'
* '10%, 10'
* '10 + 10%'
* '10 - 5vh + 3%'
* '-10px + 5vh, 5px - 6%'
* ```
* > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap
* > with their reference element, unfortunately, you will have to disable the `flip` modifier.
* > More on this [reading this issue](https://github.com/FezVrasta/popper.js/issues/373)
*
* @memberof modifiers
* @inner
*/
offset: {
/** @prop {number} order=200 - Index used to define the order of execution */
order: 200,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: offset,
/** @prop {Number|String} offset=0
* The offset value as described in the modifier description
*/
offset: 0
},
/**
* Modifier used to prevent the popper from being positioned outside the boundary.
*
* An scenario exists where the reference itself is not within the boundaries.<br />
* We can say it has "escaped the boundaries" — or just "escaped".<br />
* In this case we need to decide whether the popper should either:
*
* - detach from the reference and remain "trapped" in the boundaries, or
* - if it should ignore the boundary and "escape with its reference"
*
* When `escapeWithReference` is set to`true` and reference is completely
* outside its boundaries, the popper will overflow (or completely leave)
* the boundaries in order to remain attached to the edge of the reference.
*
* @memberof modifiers
* @inner
*/
preventOverflow: {
/** @prop {number} order=300 - Index used to define the order of execution */
order: 300,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: preventOverflow,
/**
* @prop {Array} [priority=['left','right','top','bottom']]
* Popper will try to prevent overflow following these priorities by default,
* then, it could overflow on the left and on top of the `boundariesElement`
*/
priority: ['left', 'right', 'top', 'bottom'],
/**
* @prop {number} padding=5
* Amount of pixel used to define a minimum distance between the boundaries
* and the popper this makes sure the popper has always a little padding
* between the edges of its container
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='scrollParent'
* Boundaries used by the modifier, can be `scrollParent`, `window`,
* `viewport` or any DOM element.
*/
boundariesElement: 'scrollParent'
},
/**
* Modifier used to make sure the reference and its popper stay near eachothers
* without leaving any gap between the two. Expecially useful when the arrow is
* enabled and you want to assure it to point to its reference element.
* It cares only about the first axis, you can still have poppers with margin
* between the popper and its reference element.
* @memberof modifiers
* @inner
*/
keepTogether: {
/** @prop {number} order=400 - Index used to define the order of execution */
order: 400,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: keepTogether
},
/**
* This modifier is used to move the `arrowElement` of the popper to make
* sure it is positioned between the reference element and its popper element.
* It will read the outer size of the `arrowElement` node to detect how many
* pixels of conjuction are needed.
*
* It has no effect if no `arrowElement` is provided.
* @memberof modifiers
* @inner
*/
arrow: {
/** @prop {number} order=500 - Index used to define the order of execution */
order: 500,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: arrow,
/** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */
element: '[x-arrow]'
},
/**
* Modifier used to flip the popper's placement when it starts to overlap its
* reference element.
*
* Requires the `preventOverflow` modifier before it in order to work.
*
* **NOTE:** this modifier will interrupt the current update cycle and will
* restart it if it detects the need to flip the placement.
* @memberof modifiers
* @inner
*/
flip: {
/** @prop {number} order=600 - Index used to define the order of execution */
order: 600,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: flip,
/**
* @prop {String|Array} behavior='flip'
* The behavior used to change the popper's placement. It can be one of
* `flip`, `clockwise`, `counterclockwise` or an array with a list of valid
* placements (with optional variations).
*/
behavior: 'flip',
/**
* @prop {number} padding=5
* The popper will flip if it hits the edges of the `boundariesElement`
*/
padding: 5,
/**
* @prop {String|HTMLElement} boundariesElement='viewport'
* The element which will define the boundaries of the popper position,
* the popper will never be placed outside of the defined boundaries
* (except if keepTogether is enabled)
*/
boundariesElement: 'viewport'
},
/**
* Modifier used to make the popper flow toward the inner of the reference element.
* By default, when this modifier is disabled, the popper will be placed outside
* the reference element.
* @memberof modifiers
* @inner
*/
inner: {
/** @prop {number} order=700 - Index used to define the order of execution */
order: 700,
/** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */
enabled: false,
/** @prop {ModifierFn} */
fn: inner
},
/**
* Modifier used to hide the popper when its reference element is outside of the
* popper boundaries. It will set a `x-out-of-boundaries` attribute which can
* be used to hide with a CSS selector the popper when its reference is
* out of boundaries.
*
* Requires the `preventOverflow` modifier before it in order to work.
* @memberof modifiers
* @inner
*/
hide: {
/** @prop {number} order=800 - Index used to define the order of execution */
order: 800,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: hide
},
/**
* Computes the style that will be applied to the popper element to gets
* properly positioned.
*
* Note that this modifier will not touch the DOM, it just prepares the styles
* so that `applyStyle` modifier can apply it. This separation is useful
* in case you need to replace `applyStyle` with a custom implementation.
*
* This modifier has `850` as `order` value to maintain backward compatibility
* with previous versions of Popper.js. Expect the modifiers ordering method
* to change in future major versions of the library.
*
* @memberof modifiers
* @inner
*/
computeStyle: {
/** @prop {number} order=850 - Index used to define the order of execution */
order: 850,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: computeStyle,
/**
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: true,
/**
* @prop {string} [x='bottom']
* Where to anchor the X axis (`bottom` or `top`). AKA X offset origin.
* Change this if your popper should grow in a direction different from `bottom`
*/
x: 'bottom',
/**
* @prop {string} [x='left']
* Where to anchor the Y axis (`left` or `right`). AKA Y offset origin.
* Change this if your popper should grow in a direction different from `right`
*/
y: 'right'
},
/**
* Applies the computed styles to the popper element.
*
* All the DOM manipulations are limited to this modifier. This is useful in case
* you want to integrate Popper.js inside a framework or view library and you
* want to delegate all the DOM manipulations to it.
*
* Note that if you disable this modifier, you must make sure the popper element
* has its position set to `absolute` before Popper.js can do its work!
*
* Just disable this modifier and define you own to achieve the desired effect.
*
* @memberof modifiers
* @inner
*/
applyStyle: {
/** @prop {number} order=900 - Index used to define the order of execution */
order: 900,
/** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */
enabled: true,
/** @prop {ModifierFn} */
fn: applyStyle,
/** @prop {Function} */
onLoad: applyStyleOnLoad,
/**
* @deprecated since version 1.10.0, the property moved to `computeStyle` modifier
* @prop {Boolean} gpuAcceleration=true
* If true, it uses the CSS 3d transformation to position the popper.
* Otherwise, it will use the `top` and `left` properties.
*/
gpuAcceleration: undefined
}
};
/**
* The `dataObject` is an object containing all the informations used by Popper.js
* this object get passed to modifiers and to the `onCreate` and `onUpdate` callbacks.
* @name dataObject
* @property {Object} data.instance The Popper.js instance
* @property {String} data.placement Placement applied to popper
* @property {String} data.originalPlacement Placement originally defined on init
* @property {Boolean} data.flipped True if popper has been flipped by flip modifier
* @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper.
* @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier
* @property {Object} data.styles Any CSS property defined here will be applied to the popper, it expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow, it expects the JavaScript nomenclature (eg. `marginBottom`)
* @property {Object} data.boundaries Offsets of the popper boundaries
* @property {Object} data.offsets The measurements of popper, reference and arrow elements.
* @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values
* @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0
*/
/**
* Default options provided to Popper.js constructor.<br />
* These can be overriden using the `options` argument of Popper.js.<br />
* To override an option, simply pass as 3rd argument an object with the same
* structure of this object, example:
* ```
* new Popper(ref, pop, {
* modifiers: {
* preventOverflow: { enabled: false }
* }
* })
* ```
* @type {Object}
* @static
* @memberof Popper
*/
var Defaults = {
/**
* Popper's placement
* @prop {Popper.placements} placement='bottom'
*/
placement: 'bottom',
/**
* Whether events (resize, scroll) are initially enabled
* @prop {Boolean} eventsEnabled=true
*/
eventsEnabled: true,
/**
* Set to true if you want to automatically remove the popper when
* you call the `destroy` method.
* @prop {Boolean} removeOnDestroy=false
*/
removeOnDestroy: false,
/**
* Callback called when the popper is created.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onCreate}
*/
onCreate: function onCreate() {},
/**
* Callback called when the popper is updated, this callback is not called
* on the initialization/creation of the popper, but only on subsequent
* updates.<br />
* By default, is set to no-op.<br />
* Access Popper.js instance with `data.instance`.
* @prop {onUpdate}
*/
onUpdate: function onUpdate() {},
/**
* List of modifiers used to modify the offsets before they are applied to the popper.
* They provide most of the functionalities of Popper.js
* @prop {modifiers}
*/
modifiers: modifiers
};
/**
* @callback onCreate
* @param {dataObject} data
*/
/**
* @callback onUpdate
* @param {dataObject} data
*/
// Utils
// Methods
var Popper = function () {
/**
* Create a new Popper.js instance
* @class Popper
* @param {HTMLElement|referenceObject} reference - The reference element used to position the popper
* @param {HTMLElement} popper - The HTML element used as popper.
* @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults)
* @return {Object} instance - The generated Popper.js instance
*/
function Popper(reference, popper) {
var _this = this;
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
classCallCheck(this, Popper);
this.scheduleUpdate = function () {
return requestAnimationFrame(_this.update);
};
// make update() debounced, so that it only runs at most once-per-tick
this.update = debounce(this.update.bind(this));
// with {} we create a new object with the options inside it
this.options = _extends({}, Popper.Defaults, options);
// init state
this.state = {
isDestroyed: false,
isCreated: false,
scrollParents: []
};
// get reference and popper elements (allow jQuery wrappers)
this.reference = reference && reference.jquery ? reference[0] : reference;
this.popper = popper && popper.jquery ? popper[0] : popper;
// Deep merge modifiers options
this.options.modifiers = {};
Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) {
_this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {});
});
// Refactoring modifiers' list (Object => Array)
this.modifiers = Object.keys(this.options.modifiers).map(function (name) {
return _extends({
name: name
}, _this.options.modifiers[name]);
})
// sort the modifiers by order
.sort(function (a, b) {
return a.order - b.order;
});
// modifiers have the ability to execute arbitrary code when Popper.js get inited
// such code is executed in the same order of its modifier
// they could add new properties to their options configuration
// BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`!
this.modifiers.forEach(function (modifierOptions) {
if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) {
modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state);
}
});
// fire the first update to position the popper in the right place
this.update();
var eventsEnabled = this.options.eventsEnabled;
if (eventsEnabled) {
// setup event listeners, they will take care of update the position in specific situations
this.enableEventListeners();
}
this.state.eventsEnabled = eventsEnabled;
}
// We can't use class properties because they don't get listed in the
// class prototype and break stuff like Sinon stubs
createClass(Popper, [{
key: 'update',
value: function update$$1() {
return update.call(this);
}
}, {
key: 'destroy',
value: function destroy$$1() {
return destroy.call(this);
}
}, {
key: 'enableEventListeners',
value: function enableEventListeners$$1() {
return enableEventListeners.call(this);
}
}, {
key: 'disableEventListeners',
value: function disableEventListeners$$1() {
return disableEventListeners.call(this);
}
/**
* Schedule an update, it will run on the next UI update available
* @method scheduleUpdate
* @memberof Popper
*/
/**
* Collection of utilities useful when writing custom modifiers.
* Starting from version 1.7, this method is available only if you
* include `popper-utils.js` before `popper.js`.
*
* **DEPRECATION**: This way to access PopperUtils is deprecated
* and will be removed in v2! Use the PopperUtils module directly instead.
* Due to the high instability of the methods contained in Utils, we can't
* guarantee them to follow semver. Use them at your own risk!
* @static
* @private
* @type {Object}
* @deprecated since version 1.8
* @member Utils
* @memberof Popper
*/
}]);
return Popper;
}();
/**
* The `referenceObject` is an object that provides an interface compatible with Popper.js
* and lets you use it as replacement of a real DOM node.<br />
* You can use this method to position a popper relatively to a set of coordinates
* in case you don't have a DOM node to use as reference.
*
* ```
* new Popper(referenceObject, popperNode);
* ```
*
* NB: This feature isn't supported in Internet Explorer 10
* @name referenceObject
* @property {Function} data.getBoundingClientRect
* A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method.
* @property {number} data.clientWidth
* An ES6 getter that will return the width of the virtual reference element.
* @property {number} data.clientHeight
* An ES6 getter that will return the height of the virtual reference element.
*/
Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils;
Popper.placements = placements;
Popper.Defaults = Defaults;
return Popper;
})));
//# sourceMappingURL=popper.js.map
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(3);
var _react2 = _interopRequireDefault(_react);
var _propTypes = __webpack_require__(4);
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var Arrow = function Arrow(props, context) {
var _props$component = props.component,
component = _props$component === undefined ? 'span' : _props$component,
innerRef = props.innerRef,
children = props.children,
restProps = _objectWithoutProperties(props, ['component', 'innerRef', 'children']);
var popper = context.popper;
var arrowRef = function arrowRef(node) {
popper.setArrowNode(node);
if (typeof innerRef === 'function') {
innerRef(node);
}
};
var arrowStyle = popper.getArrowStyle();
if (typeof children === 'function') {
var arrowProps = {
ref: arrowRef,
style: arrowStyle
};
return children({ arrowProps: arrowProps, restProps: restProps });
}
var componentProps = _extends({}, restProps, {
style: _extends({}, arrowStyle, restProps.style)
});
if (typeof component === 'string') {
componentProps.ref = arrowRef;
} else {
componentProps.innerRef = arrowRef;
}
return (0, _react.createElement)(component, componentProps, children);
};
Arrow.contextTypes = {
popper: _propTypes2.default.object.isRequired
};
Arrow.propTypes = {
component: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]),
innerRef: _propTypes2.default.func,
children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func])
};
exports.default = Arrow;
/***/ })
/******/ ])
});
; | tholu/cdnjs | ajax/libs/react-datepicker/0.59.0/react-datepicker.js | JavaScript | mit | 229,566 |
// { dg-options "-std=gnu++0x" }
// { dg-do compile }
// Copyright (C) 2007-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
//
// This library 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 this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
#include <unordered_set>
using namespace std;
template class unordered_multiset<int, hash<int>, equal_to<int>, allocator<char>>;
| Xilinx/gcc | libstdc++-v3/testsuite/23_containers/unordered_multiset/requirements/explicit_instantiation/3.cc | C++ | gpl-2.0 | 953 |
<?php
/**
* OG behavior handler.
*/
class OgBehaviorHandler extends EntityReference_BehaviorHandler_Abstract {
/**
* Implements EntityReference_BehaviorHandler_Abstract::access().
*/
public function access($field, $instance) {
return $field['settings']['handler'] == 'og' || strpos($field['settings']['handler'], 'og_') === 0;
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::load().
*/
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {
// Get the OG memberships from the field.
$field_name = $field['field_name'];
$target_type = $field['settings']['target_type'];
foreach ($entities as $entity) {
$wrapper = entity_metadata_wrapper($entity_type, $entity);
if (empty($wrapper->{$field_name})) {
// If the entity belongs to a bundle that was deleted, return early.
continue;
}
$id = $wrapper->getIdentifier();
$items[$id] = array();
$gids = og_get_entity_groups($entity_type, $entity, array(OG_STATE_ACTIVE), $field_name);
if (empty($gids[$target_type])) {
continue;
}
foreach ($gids[$target_type] as $gid) {
$items[$id][] = array(
'target_id' => $gid,
);
}
}
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::insert().
*/
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
$items = array();
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::access().
*/
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
$items = array();
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::Delete()
*
* CRUD memberships from field, or if entity is marked for deleteing,
* delete all the OG membership related to it.
*
* @see og_entity_delete().
*/
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!empty($entity->skip_og_membership)) {
return;
}
if (!empty($entity->delete_og_membership)) {
// Delete all OG memberships related to this entity.
$og_memberships = array();
foreach (og_get_entity_groups($entity_type, $entity) as $group_type => $ids) {
$og_memberships = array_merge($og_memberships, array_keys($ids));
}
if ($og_memberships) {
og_membership_delete_multiple($og_memberships);
}
}
else {
$this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items);
}
}
/**
* Create, update or delete OG membership based on field values.
*/
public function OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, &$items) {
if (!user_access('administer group') && !field_access('edit', $field, $entity_type, $entity)) {
// User has no access to field.
return;
}
if (!$diff = $this->groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)) {
return;
}
$field_name = $field['field_name'];
$group_type = $field['settings']['target_type'];
$diff += array('insert' => array(), 'delete' => array());
// Delete first, so we don't trigger cardinality errors.
if ($diff['delete']) {
og_membership_delete_multiple($diff['delete']);
}
if (!$diff['insert']) {
return;
}
// Prepare an array with the membership state, if it was provided in the widget.
$states = array();
foreach ($items as $item) {
$gid = $item['target_id'];
if (empty($item['state']) || !in_array($gid, $diff['insert'])) {
// State isn't provided, or not an "insert" operation.
continue;
}
$states[$gid] = $item['state'];
}
foreach ($diff['insert'] as $gid) {
$values = array(
'entity_type' => $entity_type,
'entity' => $entity,
'field_name' => $field_name,
);
if (!empty($states[$gid])) {
$values['state'] = $states[$gid];
}
og_group($group_type, $gid, $values);
}
}
/**
* Get the difference in group audience for a saved field.
*
* @return
* Array with all the differences, or an empty array if none found.
*/
public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items) {
$return = FALSE;
$field_name = $field['field_name'];
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$og_memberships = $wrapper->{$field_name . '__og_membership'}->value();
$new_memberships = array();
foreach ($items as $item) {
$new_memberships[$item['target_id']] = TRUE;
}
foreach ($og_memberships as $og_membership) {
$gid = $og_membership->gid;
if (empty($new_memberships[$gid])) {
// Membership was deleted.
if ($og_membership->entity_type == 'user') {
// Make sure this is not the group manager, if exists.
$group = entity_load_single($og_membership->group_type, $og_membership->gid);
if (!empty($group->uid) && $group->uid == $og_membership->etid) {
continue;
}
}
$return['delete'][] = $og_membership->id;
unset($new_memberships[$gid]);
}
else {
// Existing membership.
unset($new_memberships[$gid]);
}
}
if ($new_memberships) {
// New memberships.
$return['insert'] = array_keys($new_memberships);
}
return $return;
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::views_data_alter().
*/
public function views_data_alter(&$data, $field) {
// We need to override the default EntityReference table settings when OG
// behavior is being used.
if (og_is_group_audience_field($field['field_name'])) {
$entity_types = array_keys($field['bundles']);
// We need to join the base table for the entities
// that this field is attached to.
foreach ($entity_types as $entity_type) {
$entity_info = entity_get_info($entity_type);
$data['og_membership'] = array(
'table' => array(
'join' => array(
$entity_info['base table'] => array(
// Join entity base table on its id field with left_field.
'left_field' => $entity_info['entity keys']['id'],
'field' => 'etid',
'extra' => array(
0 => array(
'field' => 'entity_type',
'value' => $entity_type,
),
),
),
),
),
// Copy the original config from the table definition.
$field['field_name'] => $data['field_data_' . $field['field_name']][$field['field_name']],
$field['field_name'] . '_target_id' => $data['field_data_' . $field['field_name']][$field['field_name'] . '_target_id'],
);
// Change config with settings from og_membership table.
foreach (array('filter', 'argument', 'sort') as $op) {
$data['og_membership'][$field['field_name'] . '_target_id'][$op]['field'] = 'gid';
$data['og_membership'][$field['field_name'] . '_target_id'][$op]['table'] = 'og_membership';
unset($data['og_membership'][$field['field_name'] . '_target_id'][$op]['additional fields']);
}
}
// Get rid of the original table configs.
unset($data['field_data_' . $field['field_name']]);
unset($data['field_revision_' . $field['field_name']]);
}
}
/**
* Implements EntityReference_BehaviorHandler_Abstract::validate().
*
* Re-build $errors array to be keyed correctly by "default" and "admin" field
* modes.
*
* @todo: Try to get the correct delta so we can highlight the invalid
* reference.
*
* @see entityreference_field_validate().
*/
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
$new_errors = array();
$values = array('default' => array(), 'admin' => array());
// If the widget type name starts with 'og_' we suppose it is separated
// into an admin and default part.
if (strpos($instance['widget']['type'], 'og_') === 0) {
foreach ($items as $item) {
$values[$item['field_mode']][] = $item['target_id'];
}
}
else {
foreach ($items as $item) {
$values['default'][] = $item['target_id'];
}
}
$field_name = $field['field_name'];
foreach ($values as $field_mode => $ids) {
if (!$ids) {
continue;
}
if ($field_mode == 'admin' && !user_access('administer group')) {
// No need to validate the admin, as the user has no access to it.
continue;
}
$instance['field_mode'] = $field_mode;
$valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids);
if ($invalid_entities = array_diff($ids, $valid_ids)) {
foreach ($invalid_entities as $id) {
$new_errors[$field_mode][] = array(
'error' => 'og_invalid_entity',
'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
);
}
}
}
if ($new_errors) {
og_field_widget_register_errors($field_name, $new_errors);
}
// Errors for this field now handled, removing from the referenced array.
unset($errors[$field_name]);
}
}
| johnlaine1/installer | sites/all/modules/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php | PHP | gpl-2.0 | 9,888 |
// 2005-12-20 Paolo Carlini <pcarlini@suse.de>
// Copyright (C) 2005-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library 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 this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 23.2.1.3 deque::swap
#include <deque>
#include <testsuite_hooks.h>
#include <testsuite_allocator.h>
// uneq_allocator as a non-empty allocator.
void
test01()
{
bool test __attribute__((unused)) = true;
using namespace std;
typedef __gnu_test::uneq_allocator<char> my_alloc;
typedef deque<char, my_alloc> my_deque;
const char title01[] = "Rivers of sand";
const char title02[] = "Concret PH";
const char title03[] = "Sonatas and Interludes for Prepared Piano";
const char title04[] = "never as tired as when i'm waking up";
const size_t N1 = sizeof(title01);
const size_t N2 = sizeof(title02);
const size_t N3 = sizeof(title03);
const size_t N4 = sizeof(title04);
my_deque::size_type size01, size02;
my_alloc alloc01(1);
my_deque deq01(alloc01);
size01 = deq01.size();
my_deque deq02(alloc01);
size02 = deq02.size();
deq01.swap(deq02);
VERIFY( deq01.size() == size02 );
VERIFY( deq01.empty() );
VERIFY( deq02.size() == size01 );
VERIFY( deq02.empty() );
my_deque deq03(alloc01);
size01 = deq03.size();
my_deque deq04(title02, title02 + N2, alloc01);
size02 = deq04.size();
deq03.swap(deq04);
VERIFY( deq03.size() == size02 );
VERIFY( equal(deq03.begin(), deq03.end(), title02) );
VERIFY( deq04.size() == size01 );
VERIFY( deq04.empty() );
my_deque deq05(title01, title01 + N1, alloc01);
size01 = deq05.size();
my_deque deq06(title02, title02 + N2, alloc01);
size02 = deq06.size();
deq05.swap(deq06);
VERIFY( deq05.size() == size02 );
VERIFY( equal(deq05.begin(), deq05.end(), title02) );
VERIFY( deq06.size() == size01 );
VERIFY( equal(deq06.begin(), deq06.end(), title01) );
my_deque deq07(title01, title01 + N1, alloc01);
size01 = deq07.size();
my_deque deq08(title03, title03 + N3, alloc01);
size02 = deq08.size();
deq07.swap(deq08);
VERIFY( deq07.size() == size02 );
VERIFY( equal(deq07.begin(), deq07.end(), title03) );
VERIFY( deq08.size() == size01 );
VERIFY( equal(deq08.begin(), deq08.end(), title01) );
my_deque deq09(title03, title03 + N3, alloc01);
size01 = deq09.size();
my_deque deq10(title04, title04 + N4, alloc01);
size02 = deq10.size();
deq09.swap(deq10);
VERIFY( deq09.size() == size02 );
VERIFY( equal(deq09.begin(), deq09.end(), title04) );
VERIFY( deq10.size() == size01 );
VERIFY( equal(deq10.begin(), deq10.end(), title03) );
my_deque deq11(title04, title04 + N4, alloc01);
size01 = deq11.size();
my_deque deq12(title01, title01 + N1, alloc01);
size02 = deq12.size();
deq11.swap(deq12);
VERIFY( deq11.size() == size02 );
VERIFY( equal(deq11.begin(), deq11.end(), title01) );
VERIFY( deq12.size() == size01 );
VERIFY( equal(deq12.begin(), deq12.end(), title04) );
my_deque deq13(title03, title03 + N3, alloc01);
size01 = deq13.size();
my_deque deq14(title03, title03 + N3, alloc01);
size02 = deq14.size();
deq13.swap(deq14);
VERIFY( deq13.size() == size02 );
VERIFY( equal(deq13.begin(), deq13.end(), title03) );
VERIFY( deq14.size() == size01 );
VERIFY( equal(deq14.begin(), deq14.end(), title03) );
}
int main()
{
test01();
return 0;
}
| skristiansson/eco32-gcc | libstdc++-v3/testsuite/23_containers/deque/modifiers/swap/2.cc | C++ | gpl-2.0 | 3,966 |
<?php
require_once($CFG->libdir.'/simpletest/testportfoliolib.php');
require_once($CFG->dirroot.'/portfolio/download/lib.php');
/*
* TODO: The portfolio unit tests were obselete and did not work.
* They have been commented out so that they do not break the
* unit tests in Moodle 2.
*
* At some point:
* 1. These tests should be audited to see which ones were valuable.
* 2. The useful ones should be rewritten using the current standards
* for writing test cases.
*
* This might be left until Moodle 2.1 when the test case framework
* is due to change.
Mock::generate('boxclient', 'mock_boxclient');
Mock::generatePartial('portfolio_plugin_download', 'mock_downloadplugin', array('ensure_ticket', 'ensure_account_tree'));
*/
class testPortfolioPluginDownload extends portfoliolib_test {
public static $includecoverage = array('lib/portfoliolib.php', 'portfolio/download/lib.php');
public function setUp() {
parent::setUp();
// $this->plugin = new mock_boxnetplugin($this);
// $this->plugin->boxclient = new mock_boxclient();
}
public function tearDown() {
parent::tearDown();
}
}
| dhamma-dev/SEA | web/portfolio/download/simpletest/testportfolioplugindownload.php | PHP | gpl-3.0 | 1,151 |
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2012 Live Networks, Inc. All rights reserved.
// RTP sink for VP8 video
// C++ header
#ifndef _VP8_VIDEO_RTP_SINK_HH
#define _VP8_VIDEO_RTP_SINK_HH
#ifndef _VIDEO_RTP_SINK_HH
#include "VideoRTPSink.hh"
#endif
class VP8VideoRTPSink: public VideoRTPSink {
public:
static VP8VideoRTPSink* createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat);
protected:
VP8VideoRTPSink(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat);
// called only by createNew()
virtual ~VP8VideoRTPSink();
private: // redefined virtual functions:
virtual void doSpecialFrameHandling(unsigned fragmentationOffset,
unsigned char* frameStart,
unsigned numBytesInFrame,
struct timeval framePresentationTime,
unsigned numRemainingBytes);
virtual
Boolean frameCanAppearAfterPacketStart(unsigned char const* frameStart,
unsigned numBytesInFrame) const;
virtual unsigned specialHeaderSize() const;
};
#endif
| hungld87/live555-for-win32 | liveMedia/include/VP8VideoRTPSink.hh | C++ | lgpl-2.1 | 1,917 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.dashclock.phone;
import com.google.android.apps.dashclock.LogUtils;
import com.google.android.apps.dashclock.api.DashClockExtension;
import com.google.android.apps.dashclock.api.ExtensionData;
import net.nurik.roman.dashclock.R;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.text.TextUtils;
import java.util.HashSet;
import java.util.Set;
import static com.google.android.apps.dashclock.LogUtils.LOGD;
import static com.google.android.apps.dashclock.LogUtils.LOGE;
import static com.google.android.apps.dashclock.LogUtils.LOGW;
/**
* Unread SMS and MMS's extension.
*/
public class SmsExtension extends DashClockExtension {
private static final String TAG = LogUtils.makeLogTag(SmsExtension.class);
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
if (!isReconnect) {
addWatchContentUris(new String[]{
TelephonyProviderConstants.MmsSms.CONTENT_URI.toString(),
});
}
}
@Override
protected void onUpdateData(int reason) {
long lastUnreadThreadId = 0;
Set<Long> unreadThreadIds = new HashSet<Long>();
Set<String> unreadThreadParticipantNames = new HashSet<String>();
boolean showingAllConversationParticipants = false;
Cursor cursor = tryOpenSimpleThreadsCursor();
if (cursor != null) {
while (cursor.moveToNext()) {
if (cursor.getInt(SimpleThreadsQuery.READ) == 0) {
long threadId = cursor.getLong(SimpleThreadsQuery._ID);
unreadThreadIds.add(threadId);
lastUnreadThreadId = threadId;
// Some devices will fail on tryOpenMmsSmsCursor below, so
// store a list of participants on unread threads as a fallback.
String recipientIdsStr = cursor.getString(SimpleThreadsQuery.RECIPIENT_IDS);
if (!TextUtils.isEmpty(recipientIdsStr)) {
String[] recipientIds = TextUtils.split(recipientIdsStr, " ");
for (String recipientId : recipientIds) {
Cursor canonAddrCursor = tryOpenCanonicalAddressCursorById(
Long.parseLong(recipientId));
if (canonAddrCursor == null) {
continue;
}
if (canonAddrCursor.moveToFirst()) {
String address = canonAddrCursor.getString(
CanonicalAddressQuery.ADDRESS);
String displayName = getDisplayNameForContact(0, address);
if (!TextUtils.isEmpty(displayName)) {
unreadThreadParticipantNames.add(displayName);
}
}
canonAddrCursor.close();
}
}
}
}
cursor.close();
LOGD(TAG, "Unread thread IDs: [" + TextUtils.join(", ", unreadThreadIds) + "]");
}
int unreadConversations = 0;
StringBuilder names = new StringBuilder();
cursor = tryOpenMmsSmsCursor();
if (cursor != null) {
// Most devices will hit this code path.
while (cursor.moveToNext()) {
// Get display name. SMS's are easy; MMS's not so much.
long id = cursor.getLong(MmsSmsQuery._ID);
long contactId = cursor.getLong(MmsSmsQuery.PERSON);
String address = cursor.getString(MmsSmsQuery.ADDRESS);
long threadId = cursor.getLong(MmsSmsQuery.THREAD_ID);
if (unreadThreadIds != null && !unreadThreadIds.contains(threadId)) {
// We have the list of all thread IDs (same as what the messaging app uses), and
// this supposedly unread message's thread isn't in the list. This message is
// likely an orphaned message whose thread was deleted. Not skipping it is
// likely the cause of http://code.google.com/p/dashclock/issues/detail?id=8
LOGD(TAG, "Skipping probably orphaned message " + id + " with thread ID "
+ threadId);
continue;
}
++unreadConversations;
lastUnreadThreadId = threadId;
if (contactId == 0 && TextUtils.isEmpty(address) && id != 0) {
// Try MMS addr query
Cursor addrCursor = tryOpenMmsAddrCursor(id);
if (addrCursor != null) {
if (addrCursor.moveToFirst()) {
contactId = addrCursor.getLong(MmsAddrQuery.CONTACT_ID);
address = addrCursor.getString(MmsAddrQuery.ADDRESS);
}
addrCursor.close();
}
}
String displayName = getDisplayNameForContact(contactId, address);
if (names.length() > 0) {
names.append(", ");
}
names.append(displayName);
}
cursor.close();
} else {
// In case the cursor is null (some Samsung devices like the Galaxy S4), use the
// fall back on the list of participants in unread threads.
unreadConversations = unreadThreadIds.size();
names.append(TextUtils.join(", ", unreadThreadParticipantNames));
showingAllConversationParticipants = true;
}
PackageManager pm = getPackageManager();
Intent clickIntent = null;
if (unreadConversations == 1 && lastUnreadThreadId > 0) {
clickIntent = new Intent(Intent.ACTION_VIEW,
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI.buildUpon()
.appendPath(Long.toString(lastUnreadThreadId)).build());
}
// If the default SMS app doesn't support ACTION_VIEW on the conversation URI,
// or if there are multiple unread conversations, try opening the app landing screen
// by implicit intent.
if (clickIntent == null || pm.resolveActivity(clickIntent, 0) == null) {
clickIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
Intent.CATEGORY_APP_MESSAGING);
// If the default SMS app doesn't support CATEGORY_APP_MESSAGING, try KitKat's
// new API to get the default package (if the API is available).
if (pm.resolveActivity(clickIntent, 0) == null) {
clickIntent = tryGetKitKatDefaultSmsActivity();
}
}
publishUpdate(new ExtensionData()
.visible(unreadConversations > 0)
.icon(R.drawable.ic_extension_sms)
.status(Integer.toString(unreadConversations))
.expandedTitle(
getResources().getQuantityString(
R.plurals.sms_title_template, unreadConversations,
unreadConversations))
.expandedBody(getString(showingAllConversationParticipants
? R.string.sms_body_all_participants_template
: R.string.sms_body_template,
names.toString()))
.clickIntent(clickIntent));
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private Intent tryGetKitKatDefaultSmsActivity() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String smsPackage = Telephony.Sms.getDefaultSmsPackage(this);
if (TextUtils.isEmpty(smsPackage)) {
return null;
}
return new Intent()
.setAction(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setPackage(smsPackage);
}
return null;
}
/**
* Returns the display name for the contact with the given ID and/or the given address
* (phone number). One or both parameters should be provided.
*/
private String getDisplayNameForContact(long contactId, String address) {
String displayName = address;
if (contactId > 0) {
Cursor contactCursor = tryOpenContactsCursorById(contactId);
if (contactCursor != null) {
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(RawContactsQuery.DISPLAY_NAME);
} else {
contactId = 0;
}
contactCursor.close();
}
}
if (contactId <= 0) {
Cursor contactCursor = tryOpenContactsCursorByAddress(address);
if (contactCursor != null) {
if (contactCursor.moveToFirst()) {
displayName = contactCursor.getString(ContactsQuery.DISPLAY_NAME);
}
contactCursor.close();
}
}
return displayName;
}
private Cursor tryOpenMmsSmsCursor() {
try {
return getContentResolver().query(
TelephonyProviderConstants.MmsSms.CONTENT_CONVERSATIONS_URI,
MmsSmsQuery.PROJECTION,
TelephonyProviderConstants.Mms.READ + "=0 AND "
+ TelephonyProviderConstants.Mms.THREAD_ID + "!=0 AND ("
+ TelephonyProviderConstants.Mms.MESSAGE_BOX + "="
+ TelephonyProviderConstants.Mms.MESSAGE_BOX_INBOX + " OR "
+ TelephonyProviderConstants.Sms.TYPE + "="
+ TelephonyProviderConstants.Sms.MESSAGE_TYPE_INBOX + ")",
null,
null);
} catch (Exception e) {
// Catch all exceptions because the SMS provider is crashy
// From developer console: "SQLiteException: table spam_filter already exists"
LOGE(TAG, "Error accessing conversations cursor in SMS/MMS provider", e);
return null;
}
}
private Cursor tryOpenSimpleThreadsCursor() {
try {
return getContentResolver().query(
TelephonyProviderConstants.Threads.CONTENT_URI
.buildUpon()
.appendQueryParameter("simple", "true")
.build(),
SimpleThreadsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
LOGW(TAG, "Error accessing simple SMS threads cursor", e);
return null;
}
}
private Cursor tryOpenCanonicalAddressCursorById(long id) {
try {
return getContentResolver().query(
TelephonyProviderConstants.CanonicalAddresses.CONTENT_URI.buildUpon()
.build(),
CanonicalAddressQuery.PROJECTION,
TelephonyProviderConstants.CanonicalAddresses._ID + "=?",
new String[]{Long.toString(id)},
null);
} catch (Exception e) {
LOGE(TAG, "Error accessing canonical addresses cursor", e);
return null;
}
}
private Cursor tryOpenMmsAddrCursor(long mmsMsgId) {
try {
return getContentResolver().query(
TelephonyProviderConstants.Mms.CONTENT_URI.buildUpon()
.appendPath(Long.toString(mmsMsgId))
.appendPath("addr")
.build(),
MmsAddrQuery.PROJECTION,
TelephonyProviderConstants.Mms.Addr.MSG_ID + "=?",
new String[]{Long.toString(mmsMsgId)},
null);
} catch (Exception e) {
// Catch all exceptions because the SMS provider is crashy
// From developer console: "SQLiteException: table spam_filter already exists"
LOGE(TAG, "Error accessing MMS addresses cursor", e);
return null;
}
}
private Cursor tryOpenContactsCursorById(long contactId) {
try {
return getContentResolver().query(
ContactsContract.RawContacts.CONTENT_URI.buildUpon()
.appendPath(Long.toString(contactId))
.build(),
RawContactsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
LOGE(TAG, "Error accessing contacts provider", e);
return null;
}
}
private Cursor tryOpenContactsCursorByAddress(String phoneNumber) {
try {
return getContentResolver().query(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI.buildUpon()
.appendPath(Uri.encode(phoneNumber)).build(),
ContactsQuery.PROJECTION,
null,
null,
null);
} catch (Exception e) {
// Can be called by the content provider (from Google Play crash/ANR console)
// java.lang.IllegalArgumentException: URI: content://com.android.contacts/phone_lookup/
LOGW(TAG, "Error looking up contact name", e);
return null;
}
}
private interface SimpleThreadsQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Threads._ID,
TelephonyProviderConstants.Threads.READ,
TelephonyProviderConstants.Threads.RECIPIENT_IDS,
};
int _ID = 0;
int READ = 1;
int RECIPIENT_IDS = 2;
}
private interface CanonicalAddressQuery {
String[] PROJECTION = {
TelephonyProviderConstants.CanonicalAddresses._ID,
TelephonyProviderConstants.CanonicalAddresses.ADDRESS,
};
int _ID = 0;
int ADDRESS = 1;
}
private interface MmsSmsQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Sms._ID,
TelephonyProviderConstants.Sms.ADDRESS,
TelephonyProviderConstants.Sms.PERSON,
TelephonyProviderConstants.Sms.THREAD_ID,
};
int _ID = 0;
int ADDRESS = 1;
int PERSON = 2;
int THREAD_ID = 3;
}
private interface MmsAddrQuery {
String[] PROJECTION = {
TelephonyProviderConstants.Mms.Addr.ADDRESS,
TelephonyProviderConstants.Mms.Addr.CONTACT_ID,
};
int ADDRESS = 0;
int CONTACT_ID = 1;
}
private interface RawContactsQuery {
String[] PROJECTION = {
ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY,
};
int DISPLAY_NAME = 0;
}
private interface ContactsQuery {
String[] PROJECTION = {
ContactsContract.Contacts.DISPLAY_NAME,
};
int DISPLAY_NAME = 0;
}
}
| ITVlab/neodash | module-dashclock/src/main/java/com/google/android/apps/dashclock/phone/SmsExtension.java | Java | apache-2.0 | 16,299 |
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util;
import com.facebook.buck.log.Logger;
import java.io.IOException;
import java.io.InputStream;
public class ThriftWatcher {
private static final Logger LOG = Logger.get(ThriftWatcher.class);
private ThriftWatcher() {
}
/**
* @return true if "thrift --version" can be executed successfully
*/
public static boolean isThriftAvailable() throws InterruptedException {
try {
LOG.debug("Checking if Thrift is available..");
InputStream output = new ProcessBuilder("thrift", "-version").start().getInputStream();
byte[] bytes = new byte[7];
output.read(bytes);
boolean available = (new String(bytes)).equals("Thrift ");
LOG.debug("Thrift available: %s", available);
return available;
} catch (IOException e) {
return false; // Could not execute thrift.
}
}
}
| mread/buck | src/com/facebook/buck/util/ThriftWatcher.java | Java | apache-2.0 | 1,473 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.netty4.http;
import java.util.Map;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.camel.AsyncEndpoint;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.PollingConsumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.netty4.NettyConfiguration;
import org.apache.camel.component.netty4.NettyEndpoint;
import org.apache.camel.http.common.cookie.CookieHandler;
import org.apache.camel.impl.SynchronousDelegateProducer;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.spi.HeaderFilterStrategyAware;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Netty HTTP server and client using the Netty 4.x library.
*/
@UriEndpoint(firstVersion = "2.14.0", scheme = "netty4-http", extendsScheme = "netty4", title = "Netty4 HTTP",
syntax = "netty4-http:protocol:host:port/path", consumerClass = NettyHttpConsumer.class, label = "http", lenientProperties = true,
excludeProperties = "textline,delimiter,autoAppendDelimiter,decoderMaxLineLength,encoding,allowDefaultCodec,udpConnectionlessSending,networkInterface"
+ ",clientMode,reconnect,reconnectInterval,useByteBuf,udpByteArrayCodec,broadcast")
public class NettyHttpEndpoint extends NettyEndpoint implements AsyncEndpoint, HeaderFilterStrategyAware {
private static final Logger LOG = LoggerFactory.getLogger(NettyHttpEndpoint.class);
@UriParam
private NettyHttpConfiguration configuration;
@UriParam(label = "advanced", name = "configuration", javaType = "org.apache.camel.component.netty4.http.NettyHttpConfiguration",
description = "To use a custom configured NettyHttpConfiguration for configuring this endpoint.")
private Object httpConfiguration; // to include in component docs as NettyHttpConfiguration is a @UriParams class
@UriParam(label = "advanced")
private NettyHttpBinding nettyHttpBinding;
@UriParam(label = "advanced")
private HeaderFilterStrategy headerFilterStrategy;
@UriParam(label = "consumer,advanced")
private boolean traceEnabled;
@UriParam(label = "consumer,advanced")
private String httpMethodRestrict;
@UriParam(label = "consumer,advanced")
private NettySharedHttpServer nettySharedHttpServer;
@UriParam(label = "consumer,security")
private NettyHttpSecurityConfiguration securityConfiguration;
@UriParam(label = "consumer,security", prefix = "securityConfiguration.", multiValue = true)
private Map<String, Object> securityOptions; // to include in component docs
@UriParam(label = "producer")
private CookieHandler cookieHandler;
public NettyHttpEndpoint(String endpointUri, NettyHttpComponent component, NettyConfiguration configuration) {
super(endpointUri, component, configuration);
}
@Override
public NettyHttpComponent getComponent() {
return (NettyHttpComponent) super.getComponent();
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
NettyHttpConsumer answer = new NettyHttpConsumer(this, processor, getConfiguration());
configureConsumer(answer);
if (nettySharedHttpServer != null) {
answer.setNettyServerBootstrapFactory(nettySharedHttpServer.getServerBootstrapFactory());
LOG.info("NettyHttpConsumer: {} is using NettySharedHttpServer on port: {}", answer, nettySharedHttpServer.getPort());
} else {
// reuse pipeline factory for the same address
HttpServerBootstrapFactory factory = getComponent().getOrCreateHttpNettyServerBootstrapFactory(answer);
// force using our server bootstrap factory
answer.setNettyServerBootstrapFactory(factory);
LOG.debug("Created NettyHttpConsumer: {} using HttpServerBootstrapFactory: {}", answer, factory);
}
return answer;
}
@Override
public Producer createProducer() throws Exception {
Producer answer = new NettyHttpProducer(this, getConfiguration());
if (isSynchronous()) {
return new SynchronousDelegateProducer(answer);
} else {
return answer;
}
}
@Override
public PollingConsumer createPollingConsumer() throws Exception {
throw new UnsupportedOperationException("This component does not support polling consumer");
}
@Override
public Exchange createExchange(ChannelHandlerContext ctx, Object message) throws Exception {
Exchange exchange = createExchange();
FullHttpRequest request = (FullHttpRequest) message;
Message in = getNettyHttpBinding().toCamelMessage(request, exchange, getConfiguration());
exchange.setIn(in);
// setup the common message headers
updateMessageHeader(in, ctx);
// honor the character encoding
String contentType = in.getHeader(Exchange.CONTENT_TYPE, String.class);
String charset = NettyHttpHelper.getCharsetFromContentType(contentType);
if (charset != null) {
exchange.setProperty(Exchange.CHARSET_NAME, charset);
in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
}
return exchange;
}
@Override
public boolean isLenientProperties() {
// true to allow dynamic URI options to be configured and passed to external system for eg. the HttpProducer
return true;
}
@Override
public void setConfiguration(NettyConfiguration configuration) {
super.setConfiguration(configuration);
this.configuration = (NettyHttpConfiguration) configuration;
}
@Override
public NettyHttpConfiguration getConfiguration() {
return (NettyHttpConfiguration) super.getConfiguration();
}
public NettyHttpBinding getNettyHttpBinding() {
return nettyHttpBinding;
}
/**
* To use a custom org.apache.camel.component.netty4.http.NettyHttpBinding for binding to/from Netty and Camel Message API.
*/
public void setNettyHttpBinding(NettyHttpBinding nettyHttpBinding) {
this.nettyHttpBinding = nettyHttpBinding;
}
public HeaderFilterStrategy getHeaderFilterStrategy() {
return headerFilterStrategy;
}
/**
* To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter headers.
*/
public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) {
this.headerFilterStrategy = headerFilterStrategy;
getNettyHttpBinding().setHeaderFilterStrategy(headerFilterStrategy);
}
public boolean isTraceEnabled() {
return traceEnabled;
}
/**
* Specifies whether to enable HTTP TRACE for this Netty HTTP consumer. By default TRACE is turned off.
*/
public void setTraceEnabled(boolean traceEnabled) {
this.traceEnabled = traceEnabled;
}
public String getHttpMethodRestrict() {
return httpMethodRestrict;
}
/**
* To disable HTTP methods on the Netty HTTP consumer. You can specify multiple separated by comma.
*/
public void setHttpMethodRestrict(String httpMethodRestrict) {
this.httpMethodRestrict = httpMethodRestrict;
}
public NettySharedHttpServer getNettySharedHttpServer() {
return nettySharedHttpServer;
}
/**
* To use a shared Netty HTTP server. See Netty HTTP Server Example for more details.
*/
public void setNettySharedHttpServer(NettySharedHttpServer nettySharedHttpServer) {
this.nettySharedHttpServer = nettySharedHttpServer;
}
public NettyHttpSecurityConfiguration getSecurityConfiguration() {
return securityConfiguration;
}
/**
* Refers to a org.apache.camel.component.netty4.http.NettyHttpSecurityConfiguration for configuring secure web resources.
*/
public void setSecurityConfiguration(NettyHttpSecurityConfiguration securityConfiguration) {
this.securityConfiguration = securityConfiguration;
}
public Map<String, Object> getSecurityOptions() {
return securityOptions;
}
/**
* To configure NettyHttpSecurityConfiguration using key/value pairs from the map
*/
public void setSecurityOptions(Map<String, Object> securityOptions) {
this.securityOptions = securityOptions;
}
public CookieHandler getCookieHandler() {
return cookieHandler;
}
/**
* Configure a cookie handler to maintain a HTTP session
*/
public void setCookieHandler(CookieHandler cookieHandler) {
this.cookieHandler = cookieHandler;
}
@Override
protected void doStart() throws Exception {
super.doStart();
ObjectHelper.notNull(nettyHttpBinding, "nettyHttpBinding", this);
ObjectHelper.notNull(headerFilterStrategy, "headerFilterStrategy", this);
if (securityConfiguration != null) {
ObjectHelper.notEmpty(securityConfiguration.getRealm(), "realm", securityConfiguration);
ObjectHelper.notEmpty(securityConfiguration.getConstraint(), "restricted", securityConfiguration);
if (securityConfiguration.getSecurityAuthenticator() == null) {
// setup default JAAS authenticator if none was configured
JAASSecurityAuthenticator jaas = new JAASSecurityAuthenticator();
jaas.setName(securityConfiguration.getRealm());
LOG.info("No SecurityAuthenticator configured, using JAASSecurityAuthenticator as authenticator: {}", jaas);
securityConfiguration.setSecurityAuthenticator(jaas);
}
}
}
}
| curso007/camel | components/camel-netty4-http/src/main/java/org/apache/camel/component/netty4/http/NettyHttpEndpoint.java | Java | apache-2.0 | 10,739 |
function getElements(className) {
return Array.from(document.getElementsByClassName(className));
}
window.onload = function() {
// Force a reflow before any changes.
document.body.clientWidth;
getElements('remove').forEach(function(e) {
e.remove();
});
getElements('remove-after').forEach(function(e) {
e.parentNode.removeChild(e.nextSibling);
});
};
| nwjs/chromium.src | third_party/blink/web_tests/external/wpt/css/css-ruby/support/ruby-dynamic-removal.js | JavaScript | bsd-3-clause | 374 |
// { dg-do assemble { target fpic } }
// { dg-options "-O0 -fpic" }
// Origin: Jakub Jelinek <jakub@redhat.com>
struct bar {
bar() {}
double x[3];
};
static bar y[4];
void foo(int z)
{
bar w;
y[z] = w;
}
| shaotuanchen/sunflower_exp | tools/source/gcc-4.2.4/gcc/testsuite/g++.old-deja/g++.other/local-alloc1.C | C++ | bsd-3-clause | 215 |
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
'use strict';
( function() {
var template = '<img alt="" src="" />',
templateBlock = new CKEDITOR.template(
'<figure class="{captionedClass}">' +
template +
'<figcaption>{captionPlaceholder}</figcaption>' +
'</figure>' ),
alignmentsObj = { left: 0, center: 1, right: 2 },
regexPercent = /^\s*(\d+\%)\s*$/i;
CKEDITOR.plugins.add( 'image2', {
// jscs:disable maximumLineLength
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
requires: 'widget,dialog',
icons: 'image',
hidpi: true,
onLoad: function() {
CKEDITOR.addCss(
'.cke_image_nocaption{' +
// This is to remove unwanted space so resize
// wrapper is displayed property.
'line-height:0' +
'}' +
'.cke_editable.cke_image_sw, .cke_editable.cke_image_sw *{cursor:sw-resize !important}' +
'.cke_editable.cke_image_se, .cke_editable.cke_image_se *{cursor:se-resize !important}' +
'.cke_image_resizer{' +
'display:none;' +
'position:absolute;' +
'width:10px;' +
'height:10px;' +
'bottom:-5px;' +
'right:-5px;' +
'background:#000;' +
'outline:1px solid #fff;' +
// Prevent drag handler from being misplaced (#11207).
'line-height:0;' +
'cursor:se-resize;' +
'}' +
'.cke_image_resizer_wrapper{' +
'position:relative;' +
'display:inline-block;' +
'line-height:0;' +
'}' +
// Bottom-left corner style of the resizer.
'.cke_image_resizer.cke_image_resizer_left{' +
'right:auto;' +
'left:-5px;' +
'cursor:sw-resize;' +
'}' +
'.cke_widget_wrapper:hover .cke_image_resizer,' +
'.cke_image_resizer.cke_image_resizing{' +
'display:block' +
'}' +
// Expand widget wrapper when linked inline image.
'.cke_widget_wrapper>a{' +
'display:inline-block' +
'}' );
},
init: function( editor ) {
// Adapts configuration from original image plugin. Should be removed
// when we'll rename image2 to image.
var config = editor.config,
lang = editor.lang.image2,
image = widgetDef( editor );
// Since filebrowser plugin discovers config properties by dialog (plugin?)
// names (sic!), this hack will be necessary as long as Image2 is not named
// Image. And since Image2 will never be Image, for sure some filebrowser logic
// got to be refined.
config.filebrowserImage2BrowseUrl = config.filebrowserImageBrowseUrl;
config.filebrowserImage2UploadUrl = config.filebrowserImageUploadUrl;
// Add custom elementspath names to widget definition.
image.pathName = lang.pathName;
image.editables.caption.pathName = lang.pathNameCaption;
// Register the widget.
editor.widgets.add( 'image', image );
// Add toolbar button for this plugin.
editor.ui.addButton && editor.ui.addButton( 'Image', {
label: editor.lang.common.image,
command: 'image',
toolbar: 'insert,10'
} );
// Register context menu option for editing widget.
if ( editor.contextMenu ) {
editor.addMenuGroup( 'image', 10 );
editor.addMenuItem( 'image', {
label: lang.menu,
command: 'image',
group: 'image'
} );
}
CKEDITOR.dialog.add( 'image2', this.path + 'dialogs/image2.js' );
},
afterInit: function( editor ) {
// Integrate with align commands (justify plugin).
var align = { left: 1, right: 1, center: 1, block: 1 },
integrate = alignCommandIntegrator( editor );
for ( var value in align )
integrate( value );
// Integrate with link commands (link plugin).
linkCommandIntegrator( editor );
}
} );
// Wiget states (forms) depending on alignment and configuration.
//
// Non-captioned widget (inline styles)
// ┌──────┬───────────────────────────────┬─────────────────────────────┐
// │Align │Internal form │Data │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │none │<wrapper> │<img /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │left │<wrapper style=”float:left”> │<img style=”float:left” /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │center│<wrapper> │<p style=”text-align:center”>│
// │ │ <p style=”text-align:center”> │ <img /> │
// │ │ <img /> │</p> │
// │ │ </p> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │right │<wrapper style=”float:right”> │<img style=”float:right” /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// └──────┴───────────────────────────────┴─────────────────────────────┘
//
// Non-captioned widget (config.image2_alignClasses defined)
// ┌──────┬───────────────────────────────┬─────────────────────────────┐
// │Align │Internal form │Data │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │none │<wrapper> │<img /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │left │<wrapper class=”left”> │<img class=”left” /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │center│<wrapper> │<p class=”center”> │
// │ │ <p class=”center”> │ <img /> │
// │ │ <img /> │</p> │
// │ │ </p> │ │
// │ │</wrapper> │ │
// ├──────┼───────────────────────────────┼─────────────────────────────┤
// │right │<wrapper class=”right”> │<img class=”right” /> │
// │ │ <img /> │ │
// │ │</wrapper> │ │
// └──────┴───────────────────────────────┴─────────────────────────────┘
//
// Captioned widget (inline styles)
// ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐
// │Align │Internal form │Data │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │none │<wrapper> │<figure /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │left │<wrapper style=”float:left”> │<figure style=”float:left” /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │center│<wrapper style=”text-align:center”> │<div style=”text-align:center”> │
// │ │ <figure style=”display:inline-block” />│ <figure style=”display:inline-block” />│
// │ │</wrapper> │</p> │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │right │<wrapper style=”float:right”> │<figure style=”float:right” /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// └──────┴────────────────────────────────────────┴────────────────────────────────────────┘
//
// Captioned widget (config.image2_alignClasses defined)
// ┌──────┬────────────────────────────────────────┬────────────────────────────────────────┐
// │Align │Internal form │Data │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │none │<wrapper> │<figure /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │left │<wrapper class=”left”> │<figure class=”left” /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │center│<wrapper class=”center”> │<div class=”center”> │
// │ │ <figure /> │ <figure /> │
// │ │</wrapper> │</p> │
// ├──────┼────────────────────────────────────────┼────────────────────────────────────────┤
// │right │<wrapper class=”right”> │<figure class=”right” /> │
// │ │ <figure /> │ │
// │ │</wrapper> │ │
// └──────┴────────────────────────────────────────┴────────────────────────────────────────┘
//
// @param {CKEDITOR.editor}
// @returns {Object}
function widgetDef( editor ) {
var alignClasses = editor.config.image2_alignClasses,
captionedClass = editor.config.image2_captionedClass;
function deflate() {
if ( this.deflated )
return;
// Remember whether widget was focused before destroyed.
if ( editor.widgets.focused == this.widget )
this.focused = true;
editor.widgets.destroy( this.widget );
// Mark widget was destroyed.
this.deflated = true;
}
function inflate() {
var editable = editor.editable(),
doc = editor.document;
// Create a new widget. This widget will be either captioned
// non-captioned, block or inline according to what is the
// new state of the widget.
if ( this.deflated ) {
this.widget = editor.widgets.initOn( this.element, 'image', this.widget.data );
// Once widget was re-created, it may become an inline element without
// block wrapper (i.e. when unaligned, end not captioned). Let's do some
// sort of autoparagraphing here (#10853).
if ( this.widget.inline && !( new CKEDITOR.dom.elementPath( this.widget.wrapper, editable ).block ) ) {
var block = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div' );
block.replace( this.widget.wrapper );
this.widget.wrapper.move( block );
}
// The focus must be transferred from the old one (destroyed)
// to the new one (just created).
if ( this.focused ) {
this.widget.focus();
delete this.focused;
}
delete this.deflated;
}
// If now widget was destroyed just update wrapper's alignment.
// According to the new state.
else {
setWrapperAlign( this.widget, alignClasses );
}
}
return {
allowedContent: getWidgetAllowedContent( editor ),
requiredContent: 'img[src,alt]',
features: getWidgetFeatures( editor ),
styleableElements: 'img figure',
// This widget converts style-driven dimensions to attributes.
contentTransformations: [
[ 'img[width]: sizeToAttribute' ]
],
// This widget has an editable caption.
editables: {
caption: {
selector: 'figcaption',
allowedContent: 'br em strong sub sup u s; a[!href]'
}
},
parts: {
image: 'img',
caption: 'figcaption'
// parts#link defined in widget#init
},
// The name of this widget's dialog.
dialog: 'image2',
// Template of the widget: plain image.
template: template,
data: function() {
var features = this.features;
// Image can't be captioned when figcaption is disallowed (#11004).
if ( this.data.hasCaption && !editor.filter.checkFeature( features.caption ) )
this.data.hasCaption = false;
// Image can't be aligned when floating is disallowed (#11004).
if ( this.data.align != 'none' && !editor.filter.checkFeature( features.align ) )
this.data.align = 'none';
// Convert the internal form of the widget from the old state to the new one.
this.shiftState( {
widget: this,
element: this.element,
oldData: this.oldData,
newData: this.data,
deflate: deflate,
inflate: inflate
} );
// Update widget.parts.link since it will not auto-update unless widget
// is destroyed and re-inited.
if ( !this.data.link ) {
if ( this.parts.link )
delete this.parts.link;
} else {
if ( !this.parts.link )
this.parts.link = this.parts.image.getParent();
}
this.parts.image.setAttributes( {
src: this.data.src,
// This internal is required by the editor.
'data-cke-saved-src': this.data.src,
alt: this.data.alt
} );
// If shifting non-captioned -> captioned, remove classes
// related to styles from <img/>.
if ( this.oldData && !this.oldData.hasCaption && this.data.hasCaption ) {
for ( var c in this.data.classes )
this.parts.image.removeClass( c );
}
// Set dimensions of the image according to gathered data.
// Do it only when the attributes are allowed (#11004).
if ( editor.filter.checkFeature( features.dimension ) )
setDimensions( this );
// Cache current data.
this.oldData = CKEDITOR.tools.extend( {}, this.data );
},
init: function() {
var helpers = CKEDITOR.plugins.image2,
image = this.parts.image,
data = {
hasCaption: !!this.parts.caption,
src: image.getAttribute( 'src' ),
alt: image.getAttribute( 'alt' ) || '',
width: image.getAttribute( 'width' ) || '',
height: image.getAttribute( 'height' ) || '',
// Lock ratio is on by default (#10833).
lock: this.ready ? helpers.checkHasNaturalRatio( image ) : true
};
// If we used 'a' in widget#parts definition, it could happen that
// selected element is a child of widget.parts#caption. Since there's no clever
// way to solve it with CSS selectors, it's done like that. (#11783).
var link = image.getAscendant( 'a' );
if ( link && this.wrapper.contains( link ) )
this.parts.link = link;
// Depending on configuration, read style/class from element and
// then remove it. Removed style/class will be set on wrapper in #data listener.
// Note: Center alignment is detected during upcast, so only left/right cases
// are checked below.
if ( !data.align ) {
var alignElement = data.hasCaption ? this.element : image;
// Read the initial left/right alignment from the class set on element.
if ( alignClasses ) {
if ( alignElement.hasClass( alignClasses[ 0 ] ) ) {
data.align = 'left';
} else if ( alignElement.hasClass( alignClasses[ 2 ] ) ) {
data.align = 'right';
}
if ( data.align ) {
alignElement.removeClass( alignClasses[ alignmentsObj[ data.align ] ] );
} else {
data.align = 'none';
}
}
// Read initial float style from figure/image and then remove it.
else {
data.align = alignElement.getStyle( 'float' ) || 'none';
alignElement.removeStyle( 'float' );
}
}
// Update data.link object with attributes if the link has been discovered.
if ( editor.plugins.link && this.parts.link ) {
data.link = CKEDITOR.plugins.link.parseLinkAttributes( editor, this.parts.link );
// Get rid of cke_widget_* classes in data. Otherwise
// they might appear in link dialog.
var advanced = data.link.advanced;
if ( advanced && advanced.advCSSClasses ) {
advanced.advCSSClasses = CKEDITOR.tools.trim( advanced.advCSSClasses.replace( /cke_\S+/, '' ) );
}
}
// Get rid of extra vertical space when there's no caption.
// It will improve the look of the resizer.
this.wrapper[ ( data.hasCaption ? 'remove' : 'add' ) + 'Class' ]( 'cke_image_nocaption' );
this.setData( data );
// Setup dynamic image resizing with mouse.
// Don't initialize resizer when dimensions are disallowed (#11004).
if ( editor.filter.checkFeature( this.features.dimension ) && editor.config.image2_disableResizer !== true )
setupResizer( this );
this.shiftState = helpers.stateShifter( this.editor );
// Add widget editing option to its context menu.
this.on( 'contextMenu', function( evt ) {
evt.data.image = CKEDITOR.TRISTATE_OFF;
// Integrate context menu items for link.
// Note that widget may be wrapped in a link, which
// does not belong to that widget (#11814).
if ( this.parts.link || this.wrapper.getAscendant( 'a' ) )
evt.data.link = evt.data.unlink = CKEDITOR.TRISTATE_OFF;
} );
// Pass the reference to this widget to the dialog.
this.on( 'dialog', function( evt ) {
evt.data.widget = this;
}, this );
},
// Overrides default method to handle internal mutability of Image2.
// @see CKEDITOR.plugins.widget#addClass
addClass: function( className ) {
getStyleableElement( this ).addClass( className );
},
// Overrides default method to handle internal mutability of Image2.
// @see CKEDITOR.plugins.widget#hasClass
hasClass: function( className ) {
return getStyleableElement( this ).hasClass( className );
},
// Overrides default method to handle internal mutability of Image2.
// @see CKEDITOR.plugins.widget#removeClass
removeClass: function( className ) {
getStyleableElement( this ).removeClass( className );
},
// Overrides default method to handle internal mutability of Image2.
// @see CKEDITOR.plugins.widget#getClasses
getClasses: ( function() {
var classRegex = new RegExp( '^(' + [].concat( captionedClass, alignClasses ).join( '|' ) + ')$' );
return function() {
var classes = this.repository.parseElementClasses( getStyleableElement( this ).getAttribute( 'class' ) );
// Neither config.image2_captionedClass nor config.image2_alignClasses
// do not belong to style classes.
for ( var c in classes ) {
if ( classRegex.test( c ) )
delete classes[ c ];
}
return classes;
};
} )(),
upcast: upcastWidgetElement( editor ),
downcast: downcastWidgetElement( editor )
};
}
CKEDITOR.plugins.image2 = {
stateShifter: function( editor ) {
// Tag name used for centering non-captioned widgets.
var doc = editor.document,
alignClasses = editor.config.image2_alignClasses,
captionedClass = editor.config.image2_captionedClass,
editable = editor.editable(),
// The order that stateActions get executed. It matters!
shiftables = [ 'hasCaption', 'align', 'link' ];
// Atomic procedures, one per state variable.
var stateActions = {
align: function( shift, oldValue, newValue ) {
var el = shift.element;
// Alignment changed.
if ( shift.changed.align ) {
// No caption in the new state.
if ( !shift.newData.hasCaption ) {
// Changed to "center" (non-captioned).
if ( newValue == 'center' ) {
shift.deflate();
shift.element = wrapInCentering( editor, el );
}
// Changed to "non-center" from "center" while caption removed.
if ( !shift.changed.hasCaption && oldValue == 'center' && newValue != 'center' ) {
shift.deflate();
shift.element = unwrapFromCentering( el );
}
}
}
// Alignment remains and "center" removed caption.
else if ( newValue == 'center' && shift.changed.hasCaption && !shift.newData.hasCaption ) {
shift.deflate();
shift.element = wrapInCentering( editor, el );
}
// Finally set display for figure.
if ( !alignClasses && el.is( 'figure' ) ) {
if ( newValue == 'center' )
el.setStyle( 'display', 'inline-block' );
else
el.removeStyle( 'display' );
}
},
hasCaption: function( shift, oldValue, newValue ) {
// This action is for real state change only.
if ( !shift.changed.hasCaption )
return;
// Get <img/> or <a><img/></a> from widget. Note that widget element might itself
// be what we're looking for. Also element can be <p style="text-align:center"><a>...</a></p>.
var imageOrLink;
if ( shift.element.is( { img: 1, a: 1 } ) )
imageOrLink = shift.element;
else
imageOrLink = shift.element.findOne( 'a,img' );
// Switching hasCaption always destroys the widget.
shift.deflate();
// There was no caption, but the caption is to be added.
if ( newValue ) {
// Create new <figure> from widget template.
var figure = CKEDITOR.dom.element.createFromHtml( templateBlock.output( {
captionedClass: captionedClass,
captionPlaceholder: editor.lang.image2.captionPlaceholder
} ), doc );
// Replace element with <figure>.
replaceSafely( figure, shift.element );
// Use old <img/> or <a><img/></a> instead of the one from the template,
// so we won't lose additional attributes.
imageOrLink.replace( figure.findOne( 'img' ) );
// Update widget's element.
shift.element = figure;
}
// The caption was present, but now it's to be removed.
else {
// Unwrap <img/> or <a><img/></a> from figure.
imageOrLink.replace( shift.element );
// Update widget's element.
shift.element = imageOrLink;
}
},
link: function( shift, oldValue, newValue ) {
if ( shift.changed.link ) {
var img = shift.element.is( 'img' ) ?
shift.element : shift.element.findOne( 'img' ),
link = shift.element.is( 'a' ) ?
shift.element : shift.element.findOne( 'a' ),
// Why deflate:
// If element is <img/>, it will be wrapped into <a>,
// which becomes a new widget.element.
// If element is <a><img/></a>, it will be unlinked
// so <img/> becomes a new widget.element.
needsDeflate = ( shift.element.is( 'a' ) && !newValue ) || ( shift.element.is( 'img' ) && newValue ),
newEl;
if ( needsDeflate )
shift.deflate();
// If unlinked the image, returned element is <img>.
if ( !newValue )
newEl = unwrapFromLink( link );
else {
// If linked the image, returned element is <a>.
if ( !oldValue )
newEl = wrapInLink( img, shift.newData.link );
// Set and remove all attributes associated with this state.
var attributes = CKEDITOR.plugins.link.getLinkAttributes( editor, newValue );
if ( !CKEDITOR.tools.isEmpty( attributes.set ) )
( newEl || link ).setAttributes( attributes.set );
if ( attributes.removed.length )
( newEl || link ).removeAttributes( attributes.removed );
}
if ( needsDeflate )
shift.element = newEl;
}
}
};
function wrapInCentering( editor, element ) {
var attribsAndStyles = {};
if ( alignClasses )
attribsAndStyles.attributes = { 'class': alignClasses[ 1 ] };
else
attribsAndStyles.styles = { 'text-align': 'center' };
// There's no gentle way to center inline element with CSS, so create p/div
// that wraps widget contents and does the trick either with style or class.
var center = doc.createElement(
editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div', attribsAndStyles );
// Replace element with centering wrapper.
replaceSafely( center, element );
element.move( center );
return center;
}
function unwrapFromCentering( element ) {
var imageOrLink = element.findOne( 'a,img' );
imageOrLink.replace( element );
return imageOrLink;
}
// Wraps <img/> -> <a><img/></a>.
// Returns reference to <a>.
//
// @param {CKEDITOR.dom.element} img
// @param {Object} linkData
// @returns {CKEDITOR.dom.element}
function wrapInLink( img, linkData ) {
var link = doc.createElement( 'a', {
attributes: {
href: linkData.url
}
} );
link.replace( img );
img.move( link );
return link;
}
// De-wraps <a><img/></a> -> <img/>.
// Returns the reference to <img/>
//
// @param {CKEDITOR.dom.element} link
// @returns {CKEDITOR.dom.element}
function unwrapFromLink( link ) {
var img = link.findOne( 'img' );
img.replace( link );
return img;
}
function replaceSafely( replacing, replaced ) {
if ( replaced.getParent() ) {
var range = editor.createRange();
range.moveToPosition( replaced, CKEDITOR.POSITION_BEFORE_START );
// Remove old element. Do it before insertion to avoid a case when
// element is moved from 'replaced' element before it, what creates
// a tricky case which insertElementIntorRange does not handle.
replaced.remove();
editable.insertElementIntoRange( replacing, range );
}
else {
replacing.replace( replaced );
}
}
return function( shift ) {
var name, i;
shift.changed = {};
for ( i = 0; i < shiftables.length; i++ ) {
name = shiftables[ i ];
shift.changed[ name ] = shift.oldData ?
shift.oldData[ name ] !== shift.newData[ name ] : false;
}
// Iterate over possible state variables.
for ( i = 0; i < shiftables.length; i++ ) {
name = shiftables[ i ];
stateActions[ name ]( shift,
shift.oldData ? shift.oldData[ name ] : null,
shift.newData[ name ] );
}
shift.inflate();
};
},
// Checks whether current ratio of the image match the natural one.
// by comparing dimensions.
// @param {CKEDITOR.dom.element} image
// @returns {Boolean}
checkHasNaturalRatio: function( image ) {
var $ = image.$,
natural = this.getNatural( image );
// The reason for two alternative comparisons is that the rounding can come from
// both dimensions, e.g. there are two cases:
// 1. height is computed as a rounded relation of the real height and the value of width,
// 2. width is computed as a rounded relation of the real width and the value of heigh.
return Math.round( $.clientWidth / natural.width * natural.height ) == $.clientHeight ||
Math.round( $.clientHeight / natural.height * natural.width ) == $.clientWidth;
},
// Returns natural dimensions of the image. For modern browsers
// it uses natural(Width|Height) for old ones (IE8), creates
// a new image and reads dimensions.
// @param {CKEDITOR.dom.element} image
// @returns {Object}
getNatural: function( image ) {
var dimensions;
if ( image.$.naturalWidth ) {
dimensions = {
width: image.$.naturalWidth,
height: image.$.naturalHeight
};
} else {
var img = new Image();
img.src = image.getAttribute( 'src' );
dimensions = {
width: img.width,
height: img.height
};
}
return dimensions;
}
};
function setWrapperAlign( widget, alignClasses ) {
var wrapper = widget.wrapper,
align = widget.data.align,
hasCaption = widget.data.hasCaption;
if ( alignClasses ) {
// Remove all align classes first.
for ( var i = 3; i--; )
wrapper.removeClass( alignClasses[ i ] );
if ( align == 'center' ) {
// Avoid touching non-captioned, centered widgets because
// they have the class set on the element instead of wrapper:
//
// <div class="cke_widget_wrapper">
// <p class="center-class">
// <img />
// </p>
// </div>
if ( hasCaption ) {
wrapper.addClass( alignClasses[ 1 ] );
}
} else if ( align != 'none' ) {
wrapper.addClass( alignClasses[ alignmentsObj[ align ] ] );
}
} else {
if ( align == 'center' ) {
if ( hasCaption )
wrapper.setStyle( 'text-align', 'center' );
else
wrapper.removeStyle( 'text-align' );
wrapper.removeStyle( 'float' );
}
else {
if ( align == 'none' )
wrapper.removeStyle( 'float' );
else
wrapper.setStyle( 'float', align );
wrapper.removeStyle( 'text-align' );
}
}
}
// Returns a function that creates widgets from all <img> and
// <figure class="{config.image2_captionedClass}"> elements.
//
// @param {CKEDITOR.editor} editor
// @returns {Function}
function upcastWidgetElement( editor ) {
var isCenterWrapper = centerWrapperChecker( editor ),
captionedClass = editor.config.image2_captionedClass;
// @param {CKEDITOR.htmlParser.element} el
// @param {Object} data
return function( el, data ) {
var dimensions = { width: 1, height: 1 },
name = el.name,
image;
// #11110 Don't initialize on pasted fake objects.
if ( el.attributes[ 'data-cke-realelement' ] )
return;
// If a center wrapper is found, there are 3 possible cases:
//
// 1. <div style="text-align:center"><figure>...</figure></div>.
// In this case centering is done with a class set on widget.wrapper.
// Simply replace centering wrapper with figure (it's no longer necessary).
//
// 2. <p style="text-align:center"><img/></p>.
// Nothing to do here: <p> remains for styling purposes.
//
// 3. <div style="text-align:center"><img/></div>.
// Nothing to do here (2.) but that case is only possible in enterMode different
// than ENTER_P.
if ( isCenterWrapper( el ) ) {
if ( name == 'div' ) {
var figure = el.getFirst( 'figure' );
// Case #1.
if ( figure ) {
el.replaceWith( figure );
el = figure;
}
}
// Cases #2 and #3 (handled transparently)
// If there's a centering wrapper, save it in data.
data.align = 'center';
// Image can be wrapped in link <a><img/></a>.
image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' );
}
// No center wrapper has been found.
else if ( name == 'figure' && el.hasClass( captionedClass ) ) {
image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' );
// Upcast linked image like <a><img/></a>.
} else if ( isLinkedOrStandaloneImage( el ) ) {
image = el.name == 'a' ? el.children[ 0 ] : el;
}
if ( !image )
return;
// If there's an image, then cool, we got a widget.
// Now just remove dimension attributes expressed with %.
for ( var d in dimensions ) {
var dimension = image.attributes[ d ];
if ( dimension && dimension.match( regexPercent ) )
delete image.attributes[ d ];
}
return el;
};
}
// Returns a function which transforms the widget to the external format
// according to the current configuration.
//
// @param {CKEDITOR.editor}
function downcastWidgetElement( editor ) {
var alignClasses = editor.config.image2_alignClasses;
// @param {CKEDITOR.htmlParser.element} el
return function( el ) {
// In case of <a><img/></a>, <img/> is the element to hold
// inline styles or classes (image2_alignClasses).
var attrsHolder = el.name == 'a' ? el.getFirst() : el,
attrs = attrsHolder.attributes,
align = this.data.align;
// De-wrap the image from resize handle wrapper.
// Only block widgets have one.
if ( !this.inline ) {
var resizeWrapper = el.getFirst( 'span' );
if ( resizeWrapper )
resizeWrapper.replaceWith( resizeWrapper.getFirst( { img: 1, a: 1 } ) );
}
if ( align && align != 'none' ) {
var styles = CKEDITOR.tools.parseCssText( attrs.style || '' );
// When the widget is captioned (<figure>) and internally centering is done
// with widget's wrapper style/class, in the external data representation,
// <figure> must be wrapped with an element holding an style/class:
//
// <div style="text-align:center">
// <figure class="image" style="display:inline-block">...</figure>
// </div>
// or
// <div class="some-center-class">
// <figure class="image">...</figure>
// </div>
//
if ( align == 'center' && el.name == 'figure' ) {
el = el.wrapWith( new CKEDITOR.htmlParser.element( 'div',
alignClasses ? { 'class': alignClasses[ 1 ] } : { style: 'text-align:center' } ) );
}
// If left/right, add float style to the downcasted element.
else if ( align in { left: 1, right: 1 } ) {
if ( alignClasses )
attrsHolder.addClass( alignClasses[ alignmentsObj[ align ] ] );
else
styles[ 'float' ] = align;
}
// Update element styles.
if ( !alignClasses && !CKEDITOR.tools.isEmpty( styles ) )
attrs.style = CKEDITOR.tools.writeCssText( styles );
}
return el;
};
}
// Returns a function that checks if an element is a centering wrapper.
//
// @param {CKEDITOR.editor} editor
// @returns {Function}
function centerWrapperChecker( editor ) {
var captionedClass = editor.config.image2_captionedClass,
alignClasses = editor.config.image2_alignClasses,
validChildren = { figure: 1, a: 1, img: 1 };
return function( el ) {
// Wrapper must be either <div> or <p>.
if ( !( el.name in { div: 1, p: 1 } ) )
return false;
var children = el.children;
// Centering wrapper can have only one child.
if ( children.length !== 1 )
return false;
var child = children[ 0 ];
// Only <figure> or <img /> can be first (only) child of centering wrapper,
// regardless of its type.
if ( !( child.name in validChildren ) )
return false;
// If centering wrapper is <p>, only <img /> can be the child.
// <p style="text-align:center"><img /></p>
if ( el.name == 'p' ) {
if ( !isLinkedOrStandaloneImage( child ) )
return false;
}
// Centering <div> can hold <img/> or <figure>, depending on enterMode.
else {
// If a <figure> is the first (only) child, it must have a class.
// <div style="text-align:center"><figure>...</figure><div>
if ( child.name == 'figure' ) {
if ( !child.hasClass( captionedClass ) )
return false;
} else {
// Centering <div> can hold <img/> or <a><img/></a> only when enterMode
// is ENTER_(BR|DIV).
// <div style="text-align:center"><img /></div>
// <div style="text-align:center"><a><img /></a></div>
if ( editor.enterMode == CKEDITOR.ENTER_P )
return false;
// Regardless of enterMode, a child which is not <figure> must be
// either <img/> or <a><img/></a>.
if ( !isLinkedOrStandaloneImage( child ) )
return false;
}
}
// Centering wrapper got to be... centering. If image2_alignClasses are defined,
// check for centering class. Otherwise, check the style.
if ( alignClasses ? el.hasClass( alignClasses[ 1 ] ) :
CKEDITOR.tools.parseCssText( el.attributes.style || '', true )[ 'text-align' ] == 'center' )
return true;
return false;
};
}
// Checks whether element is <img/> or <a><img/></a>.
//
// @param {CKEDITOR.htmlParser.element}
function isLinkedOrStandaloneImage( el ) {
if ( el.name == 'img' )
return true;
else if ( el.name == 'a' )
return el.children.length == 1 && el.getFirst( 'img' );
return false;
}
// Sets width and height of the widget image according to current widget data.
//
// @param {CKEDITOR.plugins.widget} widget
function setDimensions( widget ) {
var data = widget.data,
dimensions = { width: data.width, height: data.height },
image = widget.parts.image;
for ( var d in dimensions ) {
if ( dimensions[ d ] )
image.setAttribute( d, dimensions[ d ] );
else
image.removeAttribute( d );
}
}
// Defines all features related to drag-driven image resizing.
//
// @param {CKEDITOR.plugins.widget} widget
function setupResizer( widget ) {
var editor = widget.editor,
editable = editor.editable(),
doc = editor.document,
// Store the resizer in a widget for testing (#11004).
resizer = widget.resizer = doc.createElement( 'span' );
resizer.addClass( 'cke_image_resizer' );
resizer.setAttribute( 'title', editor.lang.image2.resizer );
resizer.append( new CKEDITOR.dom.text( '\u200b', doc ) );
// Inline widgets don't need a resizer wrapper as an image spans the entire widget.
if ( !widget.inline ) {
var imageOrLink = widget.parts.link || widget.parts.image,
oldResizeWrapper = imageOrLink.getParent(),
resizeWrapper = doc.createElement( 'span' );
resizeWrapper.addClass( 'cke_image_resizer_wrapper' );
resizeWrapper.append( imageOrLink );
resizeWrapper.append( resizer );
widget.element.append( resizeWrapper, true );
// Remove the old wrapper which could came from e.g. pasted HTML
// and which could be corrupted (e.g. resizer span has been lost).
if ( oldResizeWrapper.is( 'span' ) )
oldResizeWrapper.remove();
} else {
widget.wrapper.append( resizer );
}
// Calculate values of size variables and mouse offsets.
resizer.on( 'mousedown', function( evt ) {
var image = widget.parts.image,
// "factor" can be either 1 or -1. I.e.: For right-aligned images, we need to
// subtract the difference to get proper width, etc. Without "factor",
// resizer starts working the opposite way.
factor = widget.data.align == 'right' ? -1 : 1,
// The x-coordinate of the mouse relative to the screen
// when button gets pressed.
startX = evt.data.$.screenX,
startY = evt.data.$.screenY,
// The initial dimensions and aspect ratio of the image.
startWidth = image.$.clientWidth,
startHeight = image.$.clientHeight,
ratio = startWidth / startHeight,
listeners = [],
// A class applied to editable during resizing.
cursorClass = 'cke_image_s' + ( !~factor ? 'w' : 'e' ),
nativeEvt, newWidth, newHeight, updateData,
moveDiffX, moveDiffY, moveRatio;
// Save the undo snapshot first: before resizing.
editor.fire( 'saveSnapshot' );
// Mousemove listeners are removed on mouseup.
attachToDocuments( 'mousemove', onMouseMove, listeners );
// Clean up the mousemove listener. Update widget data if valid.
attachToDocuments( 'mouseup', onMouseUp, listeners );
// The entire editable will have the special cursor while resizing goes on.
editable.addClass( cursorClass );
// This is to always keep the resizer element visible while resizing.
resizer.addClass( 'cke_image_resizing' );
// Attaches an event to a global document if inline editor.
// Additionally, if classic (`iframe`-based) editor, also attaches the same event to `iframe`'s document.
function attachToDocuments( name, callback, collection ) {
var globalDoc = CKEDITOR.document,
listeners = [];
if ( !doc.equals( globalDoc ) )
listeners.push( globalDoc.on( name, callback ) );
listeners.push( doc.on( name, callback ) );
if ( collection ) {
for ( var i = listeners.length; i--; )
collection.push( listeners.pop() );
}
}
// Calculate with first, and then adjust height, preserving ratio.
function adjustToX() {
newWidth = startWidth + factor * moveDiffX;
newHeight = Math.round( newWidth / ratio );
}
// Calculate height first, and then adjust width, preserving ratio.
function adjustToY() {
newHeight = startHeight - moveDiffY;
newWidth = Math.round( newHeight * ratio );
}
// This is how variables refer to the geometry.
// Note: x corresponds to moveOffset, this is the position of mouse
// Note: o corresponds to [startX, startY].
//
// +--------------+--------------+
// | | |
// | I | II |
// | | |
// +------------- o -------------+ _ _ _
// | | | ^
// | VI | III | | moveDiffY
// | | x _ _ _ _ _ v
// +--------------+---------|----+
// | |
// <------->
// moveDiffX
function onMouseMove( evt ) {
nativeEvt = evt.data.$;
// This is how far the mouse is from the point the button was pressed.
moveDiffX = nativeEvt.screenX - startX;
moveDiffY = startY - nativeEvt.screenY;
// This is the aspect ratio of the move difference.
moveRatio = Math.abs( moveDiffX / moveDiffY );
// Left, center or none-aligned widget.
if ( factor == 1 ) {
if ( moveDiffX <= 0 ) {
// Case: IV.
if ( moveDiffY <= 0 )
adjustToX();
// Case: I.
else {
if ( moveRatio >= ratio )
adjustToX();
else
adjustToY();
}
} else {
// Case: III.
if ( moveDiffY <= 0 ) {
if ( moveRatio >= ratio )
adjustToY();
else
adjustToX();
}
// Case: II.
else {
adjustToY();
}
}
}
// Right-aligned widget. It mirrors behaviours, so I becomes II,
// IV becomes III and vice-versa.
else {
if ( moveDiffX <= 0 ) {
// Case: IV.
if ( moveDiffY <= 0 ) {
if ( moveRatio >= ratio )
adjustToY();
else
adjustToX();
}
// Case: I.
else {
adjustToY();
}
} else {
// Case: III.
if ( moveDiffY <= 0 )
adjustToX();
// Case: II.
else {
if ( moveRatio >= ratio ) {
adjustToX();
} else {
adjustToY();
}
}
}
}
// Don't update attributes if less than 10.
// This is to prevent images to visually disappear.
if ( newWidth >= 15 && newHeight >= 15 ) {
image.setAttributes( { width: newWidth, height: newHeight } );
updateData = true;
} else {
updateData = false;
}
}
function onMouseUp() {
var l;
while ( ( l = listeners.pop() ) )
l.removeListener();
// Restore default cursor by removing special class.
editable.removeClass( cursorClass );
// This is to bring back the regular behaviour of the resizer.
resizer.removeClass( 'cke_image_resizing' );
if ( updateData ) {
widget.setData( { width: newWidth, height: newHeight } );
// Save another undo snapshot: after resizing.
editor.fire( 'saveSnapshot' );
}
// Don't update data twice or more.
updateData = false;
}
} );
// Change the position of the widget resizer when data changes.
widget.on( 'data', function() {
resizer[ widget.data.align == 'right' ? 'addClass' : 'removeClass' ]( 'cke_image_resizer_left' );
} );
}
// Integrates widget alignment setting with justify
// plugin's commands (execution and refreshment).
// @param {CKEDITOR.editor} editor
// @param {String} value 'left', 'right', 'center' or 'block'
function alignCommandIntegrator( editor ) {
var execCallbacks = [],
enabled;
return function( value ) {
var command = editor.getCommand( 'justify' + value );
// Most likely, the justify plugin isn't loaded.
if ( !command )
return;
// This command will be manually refreshed along with
// other commands after exec.
execCallbacks.push( function() {
command.refresh( editor, editor.elementPath() );
} );
if ( value in { right: 1, left: 1, center: 1 } ) {
command.on( 'exec', function( evt ) {
var widget = getFocusedWidget( editor );
if ( widget ) {
widget.setData( 'align', value );
// Once the widget changed its align, all the align commands
// must be refreshed: the event is to be cancelled.
for ( var i = execCallbacks.length; i--; )
execCallbacks[ i ]();
evt.cancel();
}
} );
}
command.on( 'refresh', function( evt ) {
var widget = getFocusedWidget( editor ),
allowed = { right: 1, left: 1, center: 1 };
if ( !widget )
return;
// Cache "enabled" on first use. This is because filter#checkFeature may
// not be available during plugin's afterInit in the future — a moment when
// alignCommandIntegrator is called.
if ( enabled === undefined )
enabled = editor.filter.checkFeature( editor.widgets.registered.image.features.align );
// Don't allow justify commands when widget alignment is disabled (#11004).
if ( !enabled )
this.setState( CKEDITOR.TRISTATE_DISABLED );
else {
this.setState(
( widget.data.align == value ) ? (
CKEDITOR.TRISTATE_ON
) : (
( value in allowed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED
)
);
}
evt.cancel();
} );
};
}
function linkCommandIntegrator( editor ) {
// Nothing to integrate with if link is not loaded.
if ( !editor.plugins.link )
return;
CKEDITOR.on( 'dialogDefinition', function( evt ) {
var dialog = evt.data;
if ( dialog.name == 'link' ) {
var def = dialog.definition;
var onShow = def.onShow,
onOk = def.onOk;
def.onShow = function() {
var widget = getFocusedWidget( editor );
// Widget cannot be enclosed in a link, i.e.
// <a>foo<inline widget/>bar</a>
if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) )
this.setupContent( widget.data.link || {} );
else
onShow.apply( this, arguments );
};
// Set widget data if linking the widget using
// link dialog (instead of default action).
// State shifter handles data change and takes
// care of internal DOM structure of linked widget.
def.onOk = function() {
var widget = getFocusedWidget( editor );
// Widget cannot be enclosed in a link, i.e.
// <a>foo<inline widget/>bar</a>
if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) {
var data = {};
// Collect data from fields.
this.commitContent( data );
// Set collected data to widget.
widget.setData( 'link', data );
} else {
onOk.apply( this, arguments );
}
};
}
} );
// Overwrite default behaviour of unlink command.
editor.getCommand( 'unlink' ).on( 'exec', function( evt ) {
var widget = getFocusedWidget( editor );
// Override unlink only when link truly belongs to the widget.
// If wrapped inline widget in a link, let default unlink work (#11814).
if ( !widget || !widget.parts.link )
return;
widget.setData( 'link', null );
// Selection (which is fake) may not change if unlinked image in focused widget,
// i.e. if captioned image. Let's refresh command state manually here.
this.refresh( editor, editor.elementPath() );
evt.cancel();
} );
// Overwrite default refresh of unlink command.
editor.getCommand( 'unlink' ).on( 'refresh', function( evt ) {
var widget = getFocusedWidget( editor );
if ( !widget )
return;
// Note that widget may be wrapped in a link, which
// does not belong to that widget (#11814).
this.setState( widget.data.link || widget.wrapper.getAscendant( 'a' ) ?
CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED );
evt.cancel();
} );
}
// Returns the focused widget, if of the type specific for this plugin.
// If no widget is focused, `null` is returned.
//
// @param {CKEDITOR.editor}
// @returns {CKEDITOR.plugins.widget}
function getFocusedWidget( editor ) {
var widget = editor.widgets.focused;
if ( widget && widget.name == 'image' )
return widget;
return null;
}
// Returns a set of widget allowedContent rules, depending
// on configurations like config#image2_alignClasses or
// config#image2_captionedClass.
//
// @param {CKEDITOR.editor}
// @returns {Object}
function getWidgetAllowedContent( editor ) {
var alignClasses = editor.config.image2_alignClasses,
rules = {
// Widget may need <div> or <p> centering wrapper.
div: {
match: centerWrapperChecker( editor )
},
p: {
match: centerWrapperChecker( editor )
},
img: {
attributes: '!src,alt,width,height'
},
figure: {
classes: '!' + editor.config.image2_captionedClass
},
figcaption: true
};
if ( alignClasses ) {
// Centering class from the config.
rules.div.classes = alignClasses[ 1 ];
rules.p.classes = rules.div.classes;
// Left/right classes from the config.
rules.img.classes = alignClasses[ 0 ] + ',' + alignClasses[ 2 ];
rules.figure.classes += ',' + rules.img.classes;
} else {
// Centering with text-align.
rules.div.styles = 'text-align';
rules.p.styles = 'text-align';
rules.img.styles = 'float';
rules.figure.styles = 'float,display';
}
return rules;
}
// Returns a set of widget feature rules, depending
// on editor configuration. Note that the following may not cover
// all the possible cases since requiredContent supports a single
// tag only.
//
// @param {CKEDITOR.editor}
// @returns {Object}
function getWidgetFeatures( editor ) {
var alignClasses = editor.config.image2_alignClasses,
features = {
dimension: {
requiredContent: 'img[width,height]'
},
align: {
requiredContent: 'img' +
( alignClasses ? '(' + alignClasses[ 0 ] + ')' : '{float}' )
},
caption: {
requiredContent: 'figcaption'
}
};
return features;
}
// Returns element which is styled, considering current
// state of the widget.
//
// @see CKEDITOR.plugins.widget#applyStyle
// @param {CKEDITOR.plugins.widget} widget
// @returns {CKEDITOR.dom.element}
function getStyleableElement( widget ) {
return widget.data.hasCaption ? widget.element : widget.parts.image;
}
} )();
/**
* A CSS class applied to the `<figure>` element of a captioned image.
*
* // Changes the class to "captionedImage".
* config.image2_captionedClass = 'captionedImage';
*
* @cfg {String} [image2_captionedClass='image']
* @member CKEDITOR.config
*/
CKEDITOR.config.image2_captionedClass = 'image';
/**
* Determines whether dimension inputs should be automatically filled when the image URL changes in the Enhanced Image
* plugin dialog window.
*
* config.image2_prefillDimensions = false;
*
* @since 4.5
* @cfg {Boolean} [image2_prefillDimensions=true]
* @member CKEDITOR.config
*/
/**
* Disables the image resizer. By default the resizer is enabled.
*
* config.image2_disableResizer = true;
*
* @since 4.5
* @cfg {Boolean} [image2_disableResizer=false]
* @member CKEDITOR.config
*/
/**
* CSS classes applied to aligned images. Useful to take control over the way
* the images are aligned, i.e. to customize output HTML and integrate external stylesheets.
*
* Classes should be defined in an array of three elements, containing left, center, and right
* alignment classes, respectively. For example:
*
* config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ];
*
* **Note**: Once this configuration option is set, the plugin will no longer produce inline
* styles for alignment. It means that e.g. the following HTML will be produced:
*
* <img alt="My image" class="custom-center-class" src="foo.png" />
*
* instead of:
*
* <img alt="My image" style="float:left" src="foo.png" />
*
* **Note**: Once this configuration option is set, corresponding style definitions
* must be supplied to the editor:
*
* * For [classic editor](#!/guide/dev_framed) it can be done by defining additional
* styles in the {@link CKEDITOR.config#contentsCss stylesheets loaded by the editor}. The same
* styles must be provided on the target page where the content will be loaded.
* * For [inline editor](#!/guide/dev_inline) the styles can be defined directly
* with `<style> ... <style>` or `<link href="..." rel="stylesheet">`, i.e. within the `<head>`
* of the page.
*
* For example, considering the following configuration:
*
* config.image2_alignClasses = [ 'align-left', 'align-center', 'align-right' ];
*
* CSS rules can be defined as follows:
*
* .align-left {
* float: left;
* }
*
* .align-right {
* float: right;
* }
*
* .align-center {
* text-align: center;
* }
*
* .align-center > figure {
* display: inline-block;
* }
*
* @since 4.4
* @cfg {String[]} [image2_alignClasses=null]
* @member CKEDITOR.config
*/
| quepasso/dashboard | web/bundles/ivoryckeditor/plugins/image2/plugin.js | JavaScript | mit | 58,206 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Ldap
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Ldap_Filter_Abstract
*/
#require_once 'Zend/Ldap/Filter/Abstract.php';
/**
* @see Zend_Ldap_Filter_String
*/
#require_once 'Zend/Ldap/Filter/String.php';
/**
* Zend_Ldap_Filter_Logical provides a base implementation for a grouping filter.
*
* @category Zend
* @package Zend_Ldap
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Ldap_Filter_Logical extends Zend_Ldap_Filter_Abstract
{
const TYPE_AND = '&';
const TYPE_OR = '|';
/**
* All the sub-filters for this grouping filter.
*
* @var array
*/
private $_subfilters;
/**
* The grouping symbol.
*
* @var string
*/
private $_symbol;
/**
* Creates a new grouping filter.
*
* @param array $subfilters
* @param string $symbol
*/
protected function __construct(array $subfilters, $symbol)
{
foreach ($subfilters as $key => $s) {
if (is_string($s)) $subfilters[$key] = new Zend_Ldap_Filter_String($s);
else if (!($s instanceof Zend_Ldap_Filter_Abstract)) {
/**
* @see Zend_Ldap_Filter_Exception
*/
#require_once 'Zend/Ldap/Filter/Exception.php';
throw new Zend_Ldap_Filter_Exception('Only strings or Zend_Ldap_Filter_Abstract allowed.');
}
}
$this->_subfilters = $subfilters;
$this->_symbol = $symbol;
}
/**
* Adds a filter to this grouping filter.
*
* @param Zend_Ldap_Filter_Abstract $filter
* @return Zend_Ldap_Filter_Logical
*/
public function addFilter(Zend_Ldap_Filter_Abstract $filter)
{
$new = clone $this;
$new->_subfilters[] = $filter;
return $new;
}
/**
* Returns a string representation of the filter.
*
* @return string
*/
public function toString()
{
$return = '(' . $this->_symbol;
foreach ($this->_subfilters as $sub) $return .= $sub->toString();
$return .= ')';
return $return;
}
}
| hansbonini/cloud9-magento | www/lib/Zend/Ldap/Filter/Logical.php | PHP | mit | 2,952 |
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Office365Api.Graph.Simple.MailAndFiles.Helpers;
using Office365Api.Graph.Simple.MailAndFiles.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace Office365Api.Graph.Simple.MailAndFiles.Controllers
{
public class HomeController : Controller
{
// The URL that auth should redirect to after a successful login.
Uri loginRedirectUri => new Uri(Url.Action(nameof(Authorize), "Home", null, Request.Url.Scheme));
// The URL to redirect to after a logout.
Uri logoutRedirectUri => new Uri(Url.Action(nameof(Index), "Home", null, Request.Url.Scheme));
public ActionResult Index()
{
// Let's get the user details from the session, stored when user was signed in.
if (Session[Helpers.SessionKeys.Login.UserInfo] != null)
{
ViewBag.Name = (Session[Helpers.SessionKeys.Login.UserInfo] as UserInformation).Name;
}
return View();
}
public ActionResult Logout()
{
Session.Clear();
return Redirect(Settings.LogoutAuthority + logoutRedirectUri.ToString());
}
public ActionResult Login()
{
if (string.IsNullOrEmpty(Settings.ClientId) || string.IsNullOrEmpty(Settings.ClientSecret))
{
ViewBag.Message = "Please set your client ID and client secret in the Web.config file";
return View();
}
var authContext = new AuthenticationContext(Settings.AzureADAuthority);
// Generate the parameterized URL for Azure login.
Uri authUri = authContext.GetAuthorizationRequestURL(
Settings.O365UnifiedAPIResource,
Settings.ClientId,
loginRedirectUri,
UserIdentifier.AnyUser,
null);
// Redirect the browser to the login page, then come back to the Authorize method below.
return Redirect(authUri.ToString());
}
public async Task<ActionResult> Authorize()
{
var authContext = new AuthenticationContext(Settings.AzureADAuthority);
// Get the token.
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
Request.Params["code"], // the auth 'code' parameter from the Azure redirect.
loginRedirectUri, // same redirectUri as used before in Login method.
new ClientCredential(Settings.ClientId, Settings.ClientSecret), // use the client ID and secret to establish app identity.
Settings.O365UnifiedAPIResource);
// Save the token in the session.
Session[SessionKeys.Login.AccessToken] = authResult.AccessToken;
// Get info about the current logged in user.
Session[SessionKeys.Login.UserInfo] = await GraphHelper.GetUserInfoAsync(authResult.AccessToken);
return RedirectToAction(nameof(Index), "PersonalData");
}
}
} | yagoto/PnP | Samples/MicrosoftGraph.Office365.Simple.MailAndFiles/Office365Api.Graph.Simple.MailAndFiles/Controllers/HomeController.cs | C# | mit | 3,267 |
from random import shuffle
def bogosort(arr):
while not sorted(arr) == arr:
shuffle(arr)
return arr | warreee/Algorithm-Implementations | Bogosort/Python/jcla1/bogosort.py | Python | mit | 116 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
**
** Purpose: The exception class used when there is insufficient execution stack
** to allow most Framework methods to execute.
**
**
=============================================================================*/
namespace System {
using System;
using System.Runtime.Serialization;
[Serializable]
public sealed class InsufficientExecutionStackException : SystemException
{
public InsufficientExecutionStackException()
: base(Environment.GetResourceString("Arg_InsufficientExecutionStackException"))
{
SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
}
public InsufficientExecutionStackException(String message)
: base(message)
{
SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
}
public InsufficientExecutionStackException(String message, Exception innerException)
: base(message, innerException)
{
SetErrorCode(__HResults.COR_E_INSUFFICIENTEXECUTIONSTACK);
}
private InsufficientExecutionStackException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
| bartonjs/coreclr | src/mscorlib/src/System/InsufficientExecutionStackException.cs | C# | mit | 1,547 |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
//
// Copyright (c) 2009 INESC Porto
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation;
//
// This program 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 this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Author: Pedro Fortuna <pedro.fortuna@inescporto.pt> <pedro.fortuna@gmail.com>
//
#include "ns3/histogram.h"
#include "ns3/test.h"
using namespace ns3;
/**
* \ingroup flow-monitor
* \defgroup flow-monitor-test FlowMonitor module tests
*/
/**
* \ingroup flow-monitor-test
* \ingroup tests
*
* \brief FlowMonitor Histogram Test
*/
class HistogramTestCase : public ns3::TestCase {
private:
public:
HistogramTestCase ();
virtual void DoRun (void);
};
HistogramTestCase::HistogramTestCase ()
: ns3::TestCase ("Histogram")
{
}
void
HistogramTestCase::DoRun (void)
{
Histogram h0 (3.5);
// Testing floating-point bin widths
{
for (int i=1; i <= 10; i++)
{
h0.AddValue (3.4);
}
for (int i=1; i <= 5; i++)
{
h0.AddValue (3.6);
}
NS_TEST_EXPECT_MSG_EQ_TOL (h0.GetBinWidth (0), 3.5, 1e-6, "");
NS_TEST_EXPECT_MSG_EQ (h0.GetNBins (), 2, "");
NS_TEST_EXPECT_MSG_EQ_TOL (h0.GetBinStart (1), 3.5, 1e-6, "");
NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (0), 10, "");
NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (1), 5, "");
}
{
// Testing bin expansion
h0.AddValue (74.3);
NS_TEST_EXPECT_MSG_EQ (h0.GetNBins (), 22, "");
NS_TEST_EXPECT_MSG_EQ (h0.GetBinCount (21), 1, "");
}
}
/**
* \ingroup flow-monitor-test
* \ingroup tests
*
* \brief FlowMonitor Histogram TestSuite
*/
class HistogramTestSuite : public TestSuite
{
public:
HistogramTestSuite ();
};
HistogramTestSuite::HistogramTestSuite ()
: TestSuite ("histogram", UNIT)
{
AddTestCase (new HistogramTestCase, TestCase::QUICK);
}
static HistogramTestSuite g_HistogramTestSuite; //!< Static variable for test initialization
| Viyom/Implementation-of-TCP-Delayed-Congestion-Response--DCR--in-ns-3 | src/flow-monitor/test/histogram-test-suite.cc | C++ | gpl-2.0 | 2,452 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once '../../../config.php';
require_once $CFG->dirroot.'/grade/export/lib.php';
require_once 'grade_export_ods.php';
$id = required_param('id', PARAM_INT); // course id
$groupid = optional_param('groupid', 0, PARAM_INT);
$itemids = required_param('itemids', PARAM_RAW);
$export_feedback = optional_param('export_feedback', 0, PARAM_BOOL);
$updatedgradesonly = optional_param('updatedgradesonly', false, PARAM_BOOL);
$displaytype = optional_param('displaytype', $CFG->grade_export_displaytype, PARAM_INT);
$decimalpoints = optional_param('decimalpoints', $CFG->grade_export_decimalpoints, PARAM_INT);
if (!$course = $DB->get_record('course', array('id'=>$id))) {
print_error('nocourseid');
}
require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $id);
require_capability('moodle/grade:export', $context);
require_capability('gradeexport/ods:view', $context);
if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
if (!groups_is_member($groupid, $USER->id)) {
print_error('cannotaccessgroup', 'grades');
}
}
// print all the exported data here
$export = new grade_export_ods($course, $groupid, $itemids, $export_feedback, $updatedgradesonly, $displaytype, $decimalpoints);
$export->print_grades();
| dhamma-dev/SEA | web/grade/export/ods/export.php | PHP | gpl-3.0 | 2,057 |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.cloudformation.model;
/**
* Resource Status
*/
public enum ResourceStatus {
CREATE_IN_PROGRESS("CREATE_IN_PROGRESS"),
CREATE_FAILED("CREATE_FAILED"),
CREATE_COMPLETE("CREATE_COMPLETE"),
DELETE_IN_PROGRESS("DELETE_IN_PROGRESS"),
DELETE_FAILED("DELETE_FAILED"),
DELETE_COMPLETE("DELETE_COMPLETE"),
DELETE_SKIPPED("DELETE_SKIPPED"),
UPDATE_IN_PROGRESS("UPDATE_IN_PROGRESS"),
UPDATE_FAILED("UPDATE_FAILED"),
UPDATE_COMPLETE("UPDATE_COMPLETE");
private String value;
private ResourceStatus(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return ResourceStatus corresponding to the value
*/
public static ResourceStatus fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
} else if ("CREATE_IN_PROGRESS".equals(value)) {
return ResourceStatus.CREATE_IN_PROGRESS;
} else if ("CREATE_FAILED".equals(value)) {
return ResourceStatus.CREATE_FAILED;
} else if ("CREATE_COMPLETE".equals(value)) {
return ResourceStatus.CREATE_COMPLETE;
} else if ("DELETE_IN_PROGRESS".equals(value)) {
return ResourceStatus.DELETE_IN_PROGRESS;
} else if ("DELETE_FAILED".equals(value)) {
return ResourceStatus.DELETE_FAILED;
} else if ("DELETE_COMPLETE".equals(value)) {
return ResourceStatus.DELETE_COMPLETE;
} else if ("DELETE_SKIPPED".equals(value)) {
return ResourceStatus.DELETE_SKIPPED;
} else if ("UPDATE_IN_PROGRESS".equals(value)) {
return ResourceStatus.UPDATE_IN_PROGRESS;
} else if ("UPDATE_FAILED".equals(value)) {
return ResourceStatus.UPDATE_FAILED;
} else if ("UPDATE_COMPLETE".equals(value)) {
return ResourceStatus.UPDATE_COMPLETE;
} else {
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
}
| xuzha/aws-sdk-java | aws-java-sdk-cloudformation/src/main/java/com/amazonaws/services/cloudformation/model/ResourceStatus.java | Java | apache-2.0 | 2,846 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.optimization.general;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well44497b;
import org.apache.commons.math3.util.MathUtils;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.distribution.RealDistribution;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.geometry.euclidean.twod.Vector2D;
/**
* Factory for generating a cloud of points that approximate a circle.
*/
public class RandomCirclePointGenerator {
/** RNG for the x-coordinate of the center. */
private final RealDistribution cX;
/** RNG for the y-coordinate of the center. */
private final RealDistribution cY;
/** RNG for the parametric position of the point. */
private final RealDistribution tP;
/** Radius of the circle. */
private final double radius;
/**
* @param x Abscissa of the circle center.
* @param y Ordinate of the circle center.
* @param radius Radius of the circle.
* @param xSigma Error on the x-coordinate of the circumference points.
* @param ySigma Error on the y-coordinate of the circumference points.
* @param seed RNG seed.
*/
public RandomCirclePointGenerator(double x,
double y,
double radius,
double xSigma,
double ySigma,
long seed) {
final RandomGenerator rng = new Well44497b(seed);
this.radius = radius;
cX = new NormalDistribution(rng, x, xSigma,
NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
cY = new NormalDistribution(rng, y, ySigma,
NormalDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
tP = new UniformRealDistribution(rng, 0, MathUtils.TWO_PI,
UniformRealDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY);
}
/**
* Point generator.
*
* @param n Number of points to create.
* @return the cloud of {@code n} points.
*/
public Vector2D[] generate(int n) {
final Vector2D[] cloud = new Vector2D[n];
for (int i = 0; i < n; i++) {
cloud[i] = create();
}
return cloud;
}
/**
* Create one point.
*
* @return a point.
*/
private Vector2D create() {
final double t = tP.sample();
final double pX = cX.sample() + radius * FastMath.cos(t);
final double pY = cY.sample() + radius * FastMath.sin(t);
return new Vector2D(pX, pY);
}
}
| tknandu/CommonsMath_Modifed | math (trunk)/src/test/java/org/apache/commons/math3/optimization/general/RandomCirclePointGenerator.java | Java | apache-2.0 | 3,637 |
# Copyright 2011 James McCauley
# Copyright 2008 (C) Nicira, Inc.
#
# This file is part of POX.
#
# POX 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.
#
# POX 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 POX. If not, see <http://www.gnu.org/licenses/>.
# This file is derived from the packet library in NOX, which was
# developed by Nicira, Inc.
#======================================================================
#
# UDP Header Format
#
# 0 7 8 15 16 23 24 31
# +--------+--------+--------+--------+
# | Source | Destination |
# | Port | Port |
# +--------+--------+--------+--------+
# | | |
# | Length | Checksum |
# +--------+--------+--------+--------+
# |
# | data octets ...
# +---------------- ...
#======================================================================
import struct
from packet_utils import *
from dhcp import *
from dns import *
from rip import *
from packet_base import packet_base
# We grab ipv4 later to prevent cyclic dependency
#_ipv4 = None
class udp(packet_base):
"UDP packet struct"
MIN_LEN = 8
def __init__(self, raw=None, prev=None, **kw):
#global _ipv4
#if not _ipv4:
# from ipv4 import ipv4
# _ipv4 = ipv4
packet_base.__init__(self)
self.prev = prev
self.srcport = 0
self.dstport = 0
self.len = 8
self.csum = 0
if raw is not None:
self.parse(raw)
self._init(kw)
def __str__(self):
s = '[UDP %s>%s l:%s c:%02x]' % (self.srcport, self.dstport,
self.len, self.csum)
return s
def parse(self, raw):
assert isinstance(raw, bytes)
self.raw = raw
dlen = len(raw)
if dlen < udp.MIN_LEN:
self.msg('(udp parse) warning UDP packet data too short to parse header: data len %u' % dlen)
return
(self.srcport, self.dstport, self.len, self.csum) \
= struct.unpack('!HHHH', raw[:udp.MIN_LEN])
self.hdr_len = udp.MIN_LEN
self.payload_len = self.len - self.hdr_len
self.parsed = True
if self.len < udp.MIN_LEN:
self.msg('(udp parse) warning invalid UDP len %u' % self.len)
return
if (self.dstport == dhcp.SERVER_PORT
or self.dstport == dhcp.CLIENT_PORT):
self.next = dhcp(raw=raw[udp.MIN_LEN:],prev=self)
elif (self.dstport == dns.SERVER_PORT
or self.srcport == dns.SERVER_PORT):
self.next = dns(raw=raw[udp.MIN_LEN:],prev=self)
elif ( (self.dstport == rip.RIP_PORT
or self.srcport == rip.RIP_PORT) ):
# and isinstance(self.prev, _ipv4)
# and self.prev.dstip == rip.RIP2_ADDRESS ):
self.next = rip(raw=raw[udp.MIN_LEN:],prev=self)
elif dlen < self.len:
self.msg('(udp parse) warning UDP packet data shorter than UDP len: %u < %u' % (dlen, self.len))
return
else:
self.payload = raw[udp.MIN_LEN:]
def hdr(self, payload):
self.len = len(payload) + udp.MIN_LEN
self.csum = self.checksum()
return struct.pack('!HHHH', self.srcport, self.dstport, self.len, self.csum)
def checksum(self, unparsed=False):
"""
Calculates the checksum.
If unparsed, calculates it on the raw, unparsed data. This is
useful for validating that it is correct on an incoming packet.
"""
if self.prev.__class__.__name__ != 'ipv4':
self.msg('packet not in ipv4, cannot calculate checksum ' +
'over psuedo-header' )
return 0
if unparsed:
payload_len = len(self.raw)
payload = self.raw
else:
if isinstance(self.next, packet_base):
payload = self.next.pack()
elif self.next is None:
payload = bytes()
else:
payload = self.next
payload_len = udp.MIN_LEN + len(payload)
ippacket = struct.pack('!IIBBH', self.prev.srcip.toUnsigned(),
self.prev.dstip.toUnsigned(),
0,
self.prev.protocol,
payload_len)
if not unparsed:
myhdr = struct.pack('!HHHH', self.srcport, self.dstport,
payload_len, 0)
payload = myhdr + payload
r = checksum(ippacket + payload, 0, 9)
return 0xffff if r == 0 else r
| srijanmishra/RouteFlow | pox/pox/lib/packet/udp.py | Python | apache-2.0 | 5,386 |
cask "air-connect" do
version "2.0.1,26526"
sha256 "e8f93fbcb626241f9cbe0f934cf9dada319f3f80399ec83558aa696988575b2a"
url "https://www.avatron.com/updates/software/airconnect_mac/acmac#{version.before_comma.no_dots}.zip"
name "Air Connect"
homepage "https://avatron.com/get-air-connect/"
livecheck do
url "https://avatron.com/updates/software/airconnect_mac/appcast.xml"
strategy :sparkle
end
app "Air Connect.app"
end
| stephenwade/homebrew-cask | Casks/air-connect.rb | Ruby | bsd-2-clause | 446 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/hwid_checker.h"
#include <cstdio>
#include "base/chromeos/chromeos_version.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "chrome/browser/chromeos/system/statistics_provider.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/chromeos_switches.h"
#include "third_party/re2/re2/re2.h"
#include "third_party/zlib/zlib.h"
namespace {
unsigned CalculateCRC32(const std::string& data) {
return static_cast<unsigned>(crc32(
0,
reinterpret_cast<const Bytef*>(data.c_str()),
data.length()));
}
std::string CalculateHWIDv2Checksum(const std::string& data) {
unsigned crc32 = CalculateCRC32(data);
// We take four least significant decimal digits of CRC-32.
char checksum[5];
int snprintf_result =
snprintf(checksum, 5, "%04u", crc32 % 10000);
LOG_ASSERT(snprintf_result == 4);
return checksum;
}
bool IsCorrectHWIDv2(const std::string& hwid) {
std::string body;
std::string checksum;
if (!RE2::FullMatch(hwid, "([\\s\\S]*) (\\d{4})", &body, &checksum))
return false;
return CalculateHWIDv2Checksum(body) == checksum;
}
bool IsExceptionalHWID(const std::string& hwid) {
return RE2::PartialMatch(hwid, "^(SPRING [A-D])|(FALCO A)");
}
std::string CalculateExceptionalHWIDChecksum(const std::string& data) {
static const char base32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
unsigned crc32 = CalculateCRC32(data);
// We take 10 least significant bits of CRC-32 and encode them in 2 characters
// using Base32 alphabet.
std::string checksum;
checksum += base32_alphabet[(crc32 >> 5) & 0x1f];
checksum += base32_alphabet[crc32 & 0x1f];
return checksum;
}
bool IsCorrectExceptionalHWID(const std::string& hwid) {
if (!IsExceptionalHWID(hwid))
return false;
std::string bom;
if (!RE2::FullMatch(hwid, "[A-Z0-9]+ ((?:[A-Z2-7]{4}-)*[A-Z2-7]{1,4})", &bom))
return false;
if (bom.length() < 2)
return false;
std::string hwid_without_dashes;
RemoveChars(hwid, "-", &hwid_without_dashes);
LOG_ASSERT(hwid_without_dashes.length() >= 2);
std::string not_checksum =
hwid_without_dashes.substr(0, hwid_without_dashes.length() - 2);
std::string checksum =
hwid_without_dashes.substr(hwid_without_dashes.length() - 2);
return CalculateExceptionalHWIDChecksum(not_checksum) == checksum;
}
std::string CalculateHWIDv3Checksum(const std::string& data) {
static const char base8_alphabet[] = "23456789";
static const char base32_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
unsigned crc32 = CalculateCRC32(data);
// We take 8 least significant bits of CRC-32 and encode them in 2 characters.
std::string checksum;
checksum += base8_alphabet[(crc32 >> 5) & 0x7];
checksum += base32_alphabet[crc32 & 0x1f];
return checksum;
}
bool IsCorrectHWIDv3(const std::string& hwid) {
if (IsExceptionalHWID(hwid))
return false;
std::string regex =
"([A-Z0-9]+ (?:[A-Z2-7][2-9][A-Z2-7]-)*[A-Z2-7])([2-9][A-Z2-7])";
std::string not_checksum, checksum;
if (!RE2::FullMatch(hwid, regex, ¬_checksum, &checksum))
return false;
RemoveChars(not_checksum, "-", ¬_checksum);
return CalculateHWIDv3Checksum(not_checksum) == checksum;
}
} // anonymous namespace
namespace chromeos {
bool IsHWIDCorrect(const std::string& hwid) {
return IsCorrectHWIDv2(hwid) || IsCorrectExceptionalHWID(hwid) ||
IsCorrectHWIDv3(hwid);
}
bool IsMachineHWIDCorrect() {
#if !defined(GOOGLE_CHROME_BUILD)
return true;
#endif
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
if (cmd_line->HasSwitch(::switches::kTestType) ||
cmd_line->HasSwitch(chromeos::switches::kSkipHWIDCheck))
return true;
if (!base::chromeos::IsRunningOnChromeOS())
return true;
std::string hwid;
chromeos::system::StatisticsProvider* stats =
chromeos::system::StatisticsProvider::GetInstance();
if (!stats->GetMachineStatistic(chromeos::system::kHardwareClass, &hwid)) {
LOG(ERROR) << "Couldn't get machine statistic 'hardware_class'.";
return false;
}
if (!chromeos::IsHWIDCorrect(hwid)) {
LOG(ERROR) << "Machine has malformed HWID '" << hwid << "'.";
return false;
}
return true;
}
} // namespace chromeos
| windyuuy/opera | chromium/src/chrome/browser/chromeos/login/hwid_checker.cc | C++ | bsd-3-clause | 4,448 |
export { VolumeMuteFilled16 as default } from "../../";
| markogresak/DefinitelyTyped | types/carbon__icons-react/es/volume--mute--filled/16.d.ts | TypeScript | mit | 56 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using Tests.ExpressionCompiler;
namespace Tests.ExpressionCompiler
{
public interface I
{
void M();
}
public class C : IEquatable<C>, I
{
void I.M()
{
}
public override bool Equals(object o)
{
return o is C && Equals((C)o);
}
public bool Equals(C c)
{
return c != null;
}
public override int GetHashCode()
{
return 0;
}
}
public class D : C, IEquatable<D>
{
public int Val;
public string S;
public D()
{
}
public D(int val)
: this(val, "")
{
}
public D(int val, string s)
{
Val = val;
S = s;
}
public override bool Equals(object o)
{
return o is D && Equals((D)o);
}
public bool Equals(D d)
{
return d != null && d.Val == Val;
}
public override int GetHashCode()
{
return Val;
}
}
public enum E
{
A = 1,
B = 2
}
public enum El : long
{
A,
B,
C
}
public struct S : IEquatable<S>
{
public override bool Equals(object o)
{
return (o is S) && Equals((S)o);
}
public bool Equals(S other)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
public struct Sp : IEquatable<Sp>
{
public Sp(int i, double d)
{
I = i;
D = d;
}
public int I;
public double D;
public override bool Equals(object o)
{
return (o is Sp) && Equals((Sp)o);
}
public bool Equals(Sp other)
{
return other.I == I && other.D.Equals(D);
}
public override int GetHashCode()
{
return I.GetHashCode() ^ D.GetHashCode();
}
}
public struct Ss : IEquatable<Ss>
{
public Ss(S s)
{
Val = s;
}
public S Val;
public override bool Equals(object o)
{
return (o is Ss) && Equals((Ss)o);
}
public bool Equals(Ss other)
{
return other.Val.Equals(Val);
}
public override int GetHashCode()
{
return Val.GetHashCode();
}
}
public struct Sc : IEquatable<Sc>
{
public Sc(string s)
{
S = s;
}
public string S;
public override bool Equals(object o)
{
return (o is Sc) && Equals((Sc)o);
}
public bool Equals(Sc other)
{
return other.S == S;
}
public override int GetHashCode()
{
return S.GetHashCode();
}
}
public struct Scs : IEquatable<Scs>
{
public Scs(string s, S val)
{
S = s;
Val = val;
}
public string S;
public S Val;
public override bool Equals(object o)
{
return (o is Scs) && Equals((Scs)o);
}
public bool Equals(Scs other)
{
return other.S == S && other.Val.Equals(Val);
}
public override int GetHashCode()
{
return S.GetHashCode() ^ Val.GetHashCode();
}
}
public class BaseClass
{
}
public class FC
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public struct FS
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public class PC
{
public int II { get; set; }
public static int SI { get; set; }
public int this[int i]
{
get { return 1; }
set { }
}
}
public struct PS
{
public int II { get; set; }
public static int SI { get; set; }
}
}
| comdiv/corefx | src/System.Linq.Expressions/tests/HelperTypes.cs | C# | mit | 4,525 |
<?php
require_once('HTML/QuickForm/submit.php');
/**
* HTML class for a submit type element
*
* @author Jamie Pratt
* @access public
*/
class MoodleQuickForm_cancel extends MoodleQuickForm_submit
{
// {{{ constructor
/**
* Class constructor
*
* @since 1.0
* @access public
* @return void
*/
function MoodleQuickForm_cancel($elementName=null, $value=null, $attributes=null)
{
if ($elementName==null){
$elementName='cancel';
}
if ($value==null){
$value=get_string('cancel');
}
MoodleQuickForm_submit::MoodleQuickForm_submit($elementName, $value, $attributes);
$this->updateAttributes(array('onclick'=>'skipClientValidation = true; return true;'));
} //end constructor
function onQuickFormEvent($event, $arg, &$caller)
{
switch ($event) {
case 'createElement':
$className = get_class($this);
$this->$className($arg[0], $arg[1], $arg[2]);
$caller->_registerCancelButton($this->getName());
return true;
break;
}
return parent::onQuickFormEvent($event, $arg, $caller);
} // end func onQuickFormEvent
function getFrozenHtml(){
return HTML_QuickForm_submit::getFrozenHtml();
}
function freeze(){
return HTML_QuickForm_submit::freeze();
}
// }}}
} //end class MoodleQuickForm_cancel
?> | feniix/moodle | lib/form/cancel.php | PHP | gpl-2.0 | 1,501 |
package teammates.test.pageobjects;
public class EntityNotFoundPage extends AppPage {
public EntityNotFoundPage(Browser browser) {
super(browser);
}
@Override
protected boolean containsExpectedPageContents() {
return getPageSource().contains("TEAMMATES could not locate what you were trying to access.");
}
}
| LiHaoTan/teammates | src/test/java/teammates/test/pageobjects/EntityNotFoundPage.java | Java | gpl-2.0 | 349 |
/*
* Copyright (C) 2012-2013 Team XBMC
* http://xbmc.org
*
* This Program 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 2, or (at your option)
* any later version.
*
* This Program 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 XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "FileItem.h"
#include "epg/Epg.h"
#include "guilib/GUIWindowManager.h"
#include "input/Key.h"
#include "view/ViewState.h"
#include "pvr/PVRManager.h"
#include "GUIDialogPVRGuideInfo.h"
#include "GUIDialogPVRGuideOSD.h"
using namespace PVR;
#define CONTROL_LIST 11
CGUIDialogPVRGuideOSD::CGUIDialogPVRGuideOSD()
: CGUIDialog(WINDOW_DIALOG_PVR_OSD_GUIDE, "DialogPVRGuideOSD.xml")
{
m_vecItems = new CFileItemList;
}
CGUIDialogPVRGuideOSD::~CGUIDialogPVRGuideOSD()
{
delete m_vecItems;
}
bool CGUIDialogPVRGuideOSD::OnMessage(CGUIMessage& message)
{
switch (message.GetMessage())
{
case GUI_MSG_CLICKED:
{
int iControl = message.GetSenderId();
if (m_viewControl.HasControl(iControl)) // list/thumb control
{
int iItem = m_viewControl.GetSelectedItem();
int iAction = message.GetParam1();
if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK)
{
ShowInfo(iItem);
return true;
}
}
}
break;
}
return CGUIDialog::OnMessage(message);
}
void CGUIDialogPVRGuideOSD::OnInitWindow()
{
/* Close dialog immediately if no TV or radio channel is playing */
if (!g_PVRManager.IsPlaying())
{
Close();
return;
}
// lock our display, as this window is rendered from the player thread
g_graphicsContext.Lock();
m_viewControl.SetCurrentView(DEFAULT_VIEW_LIST);
// empty the list ready for population
Clear();
g_PVRManager.GetCurrentEpg(*m_vecItems);
m_viewControl.SetItems(*m_vecItems);
g_graphicsContext.Unlock();
// call init
CGUIDialog::OnInitWindow();
// select the active entry
unsigned int iSelectedItem = 0;
for (int iEpgPtr = 0; iEpgPtr < m_vecItems->Size(); ++iEpgPtr)
{
CFileItemPtr entry = m_vecItems->Get(iEpgPtr);
if (entry->HasEPGInfoTag() && entry->GetEPGInfoTag()->IsActive())
{
iSelectedItem = iEpgPtr;
break;
}
}
m_viewControl.SetSelectedItem(iSelectedItem);
}
void CGUIDialogPVRGuideOSD::OnDeinitWindow(int nextWindowID)
{
CGUIDialog::OnDeinitWindow(nextWindowID);
Clear();
}
void CGUIDialogPVRGuideOSD::Clear()
{
m_viewControl.Clear();
m_vecItems->Clear();
}
void CGUIDialogPVRGuideOSD::ShowInfo(int item)
{
/* Check file item is in list range and get his pointer */
if (item < 0 || item >= (int)m_vecItems->Size()) return;
CFileItemPtr pItem = m_vecItems->Get(item);
/* Load programme info dialog */
CGUIDialogPVRGuideInfo* pDlgInfo = (CGUIDialogPVRGuideInfo*)g_windowManager.GetWindow(WINDOW_DIALOG_PVR_GUIDE_INFO);
if (!pDlgInfo)
return;
/* inform dialog about the file item and open dialog window */
pDlgInfo->SetProgInfo(pItem->GetEPGInfoTag());
pDlgInfo->Open();
}
void CGUIDialogPVRGuideOSD::OnWindowLoaded()
{
CGUIDialog::OnWindowLoaded();
m_viewControl.Reset();
m_viewControl.SetParentWindow(GetID());
m_viewControl.AddView(GetControl(CONTROL_LIST));
}
void CGUIDialogPVRGuideOSD::OnWindowUnload()
{
CGUIDialog::OnWindowUnload();
m_viewControl.Reset();
}
CGUIControl *CGUIDialogPVRGuideOSD::GetFirstFocusableControl(int id)
{
if (m_viewControl.HasControl(id))
id = m_viewControl.GetCurrentControl();
return CGUIWindow::GetFirstFocusableControl(id);
}
| Shine-/xbmc | xbmc/pvr/dialogs/GUIDialogPVRGuideOSD.cpp | C++ | gpl-2.0 | 3,993 |
/* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org>
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */
/**
* VictorOps Generic-API Transport - Based on PagerDuty transport
* @author f0o <f0o@devilcode.org>
* @author laf <neil@librenms.org>
* @copyright 2015 f0o, laf, LibreNMS
* @license GPL
* @package LibreNMS
* @subpackage Alerts
*/
$url = $opts['url'];
$protocol = array(
'entity_id' => ($obj['id'] ? $obj['id'] : $obj['uid']),
'state_start_time' => strtotime($obj['timestamp']),
'monitoring_tool' => 'librenms',
);
if( $obj['state'] == 0 ) {
$protocol['message_type'] = 'recovery';
}
elseif( $obj['state'] == 2 ) {
$protocol['message_type'] = 'acknowledgement';
}
elseif ($obj['state'] == 1) {
$protocol['message_type'] = 'critical';
}
foreach( $obj['faults'] as $fault=>$data ) {
$protocol['state_message'] .= $data['string'];
}
$curl = curl_init();
set_curl_proxy($curl);
curl_setopt($curl, CURLOPT_URL, $url );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type'=> 'application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($protocol));
$ret = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if( $code != 200 ) {
var_dump("VictorOps returned Error, retry later"); //FIXME: propper debuging
return false;
}
return true;
| NetworkNub/librenms | includes/alerts/transport.victorops.php | PHP | gpl-3.0 | 1,967 |
/*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.0
* LICENSE: See LICENSE in the top level directory
* FILE: mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp
* PURPOSE: Player statistics packet class
* DEVELOPERS: Jax <>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
CPlayerStatsPacket::~CPlayerStatsPacket ( void )
{
Clear ( );
}
bool CPlayerStatsPacket::Write ( NetBitStreamInterface& BitStream ) const
{
// Write the source player.
if ( m_pSourceElement )
{
ElementID ID = m_pSourceElement->GetID ();
BitStream.Write ( ID );
// Write the stats
unsigned short usNumStats = static_cast < unsigned short >( m_List.size () );
BitStream.WriteCompressed ( usNumStats );
map < unsigned short, sPlayerStat > ::const_iterator iter = m_List.begin ();
for ( ; iter != m_List.end () ; ++iter )
{
const sPlayerStat& playerStat = (*iter).second;
BitStream.Write ( playerStat.id );
BitStream.Write ( playerStat.value );
}
return true;
}
return false;
}
void CPlayerStatsPacket::Add ( unsigned short usID, float fValue )
{
map < unsigned short, sPlayerStat > ::iterator iter = m_List.find ( usID );
if ( iter != m_List.end ( ) )
{
if ( fValue == 0.0f )
{
m_List.erase ( iter );
}
else
{
sPlayerStat& stat = (*iter).second;
stat.value = fValue;
}
}
else
{
sPlayerStat stat;
stat.id = usID;
stat.value = fValue;
m_List[ usID ] = stat;
}
}
void CPlayerStatsPacket::Remove ( unsigned short usID, float fValue )
{
map < unsigned short, sPlayerStat > ::iterator iter = m_List.find ( usID );
if ( iter != m_List.end ( ) )
{
m_List.erase ( iter );
}
}
void CPlayerStatsPacket::Clear ( void )
{
m_List.clear ();
} | zneext/mtasa-blue | Server/mods/deathmatch/logic/packets/CPlayerStatsPacket.cpp | C++ | gpl-3.0 | 2,217 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.protocol.datatransfer;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.PacketHeaderProto;
import org.apache.hadoop.hdfs.util.ByteBufferOutputStream;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Shorts;
import com.google.common.primitives.Ints;
import com.google.protobuf.InvalidProtocolBufferException;
/**
* Header data for each packet that goes through the read/write pipelines.
* Includes all of the information about the packet, excluding checksums and
* actual data.
*
* This data includes:
* - the offset in bytes into the HDFS block of the data in this packet
* - the sequence number of this packet in the pipeline
* - whether or not this is the last packet in the pipeline
* - the length of the data in this packet
* - whether or not this packet should be synced by the DNs.
*
* When serialized, this header is written out as a protocol buffer, preceded
* by a 4-byte integer representing the full packet length, and a 2-byte short
* representing the header length.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class PacketHeader {
private static final int MAX_PROTO_SIZE = PacketHeaderProto.newBuilder()
.setOffsetInBlock(0)
.setSeqno(0)
.setLastPacketInBlock(false)
.setDataLen(0)
.setSyncBlock(false)
.build().getSerializedSize();
public static final int PKT_LENGTHS_LEN =
Ints.BYTES + Shorts.BYTES;
public static final int PKT_MAX_HEADER_LEN =
PKT_LENGTHS_LEN + MAX_PROTO_SIZE;
private int packetLen;
private PacketHeaderProto proto;
public PacketHeader() {
}
public PacketHeader(int packetLen, long offsetInBlock, long seqno,
boolean lastPacketInBlock, int dataLen, boolean syncBlock) {
this.packetLen = packetLen;
Preconditions.checkArgument(packetLen >= Ints.BYTES,
"packet len %s should always be at least 4 bytes",
packetLen);
PacketHeaderProto.Builder builder = PacketHeaderProto.newBuilder()
.setOffsetInBlock(offsetInBlock)
.setSeqno(seqno)
.setLastPacketInBlock(lastPacketInBlock)
.setDataLen(dataLen);
if (syncBlock) {
// Only set syncBlock if it is specified.
// This is wire-incompatible with Hadoop 2.0.0-alpha due to HDFS-3721
// because it changes the length of the packet header, and BlockReceiver
// in that version did not support variable-length headers.
builder.setSyncBlock(true);
}
proto = builder.build();
}
public int getDataLen() {
return proto.getDataLen();
}
public boolean isLastPacketInBlock() {
return proto.getLastPacketInBlock();
}
public long getSeqno() {
return proto.getSeqno();
}
public long getOffsetInBlock() {
return proto.getOffsetInBlock();
}
public int getPacketLen() {
return packetLen;
}
public boolean getSyncBlock() {
return proto.getSyncBlock();
}
@Override
public String toString() {
return "PacketHeader with packetLen=" + packetLen +
" header data: " +
proto.toString();
}
public void setFieldsFromData(
int packetLen, byte[] headerData) throws InvalidProtocolBufferException {
this.packetLen = packetLen;
proto = PacketHeaderProto.parseFrom(headerData);
}
public void readFields(ByteBuffer buf) throws IOException {
packetLen = buf.getInt();
short protoLen = buf.getShort();
byte[] data = new byte[protoLen];
buf.get(data);
proto = PacketHeaderProto.parseFrom(data);
}
public void readFields(DataInputStream in) throws IOException {
this.packetLen = in.readInt();
short protoLen = in.readShort();
byte[] data = new byte[protoLen];
in.readFully(data);
proto = PacketHeaderProto.parseFrom(data);
}
/**
* @return the number of bytes necessary to write out this header,
* including the length-prefixing of the payload and header
*/
public int getSerializedSize() {
return PKT_LENGTHS_LEN + proto.getSerializedSize();
}
/**
* Write the header into the buffer.
* This requires that PKT_HEADER_LEN bytes are available.
*/
public void putInBuffer(final ByteBuffer buf) {
assert proto.getSerializedSize() <= MAX_PROTO_SIZE
: "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize();
try {
buf.putInt(packetLen);
buf.putShort((short) proto.getSerializedSize());
proto.writeTo(new ByteBufferOutputStream(buf));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void write(DataOutputStream out) throws IOException {
assert proto.getSerializedSize() <= MAX_PROTO_SIZE
: "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize();
out.writeInt(packetLen);
out.writeShort(proto.getSerializedSize());
proto.writeTo(out);
}
public byte[] getBytes() {
ByteBuffer buf = ByteBuffer.allocate(getSerializedSize());
putInBuffer(buf);
return buf.array();
}
/**
* Perform a sanity check on the packet, returning true if it is sane.
* @param lastSeqNo the previous sequence number received - we expect the
* current sequence number to be larger by 1.
*/
public boolean sanityCheck(long lastSeqNo) {
// We should only have a non-positive data length for the last packet
if (proto.getDataLen() <= 0 && !proto.getLastPacketInBlock()) return false;
// The last packet should not contain data
if (proto.getLastPacketInBlock() && proto.getDataLen() != 0) return false;
// Seqnos should always increase by 1 with each packet received
return proto.getSeqno() == lastSeqNo + 1;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PacketHeader)) return false;
PacketHeader other = (PacketHeader)o;
return this.proto.equals(other.proto);
}
@Override
public int hashCode() {
return (int)proto.getSeqno();
}
}
| dennishuo/hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketHeader.java | Java | apache-2.0 | 7,020 |
/**
* Modules in this bundle
* @license
*
* opentype.js:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Frederik De Bleser <frederik@debleser.be>
* version: 0.6.7
*
* tiny-inflate:
* license: MIT (http://opensource.org/licenses/MIT)
* author: Devon Govett <devongovett@gmail.com>
* maintainers: devongovett <devongovett@gmail.com>
* homepage: https://github.com/devongovett/tiny-inflate
* version: 1.0.2
*
* This header is generated by licensify (https://github.com/twada/licensify)
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.opentype = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var TINF_OK = 0;
var TINF_DATA_ERROR = -3;
function Tree() {
this.table = new Uint16Array(16); /* table of code length counts */
this.trans = new Uint16Array(288); /* code -> symbol translation table */
}
function Data(source, dest) {
this.source = source;
this.sourceIndex = 0;
this.tag = 0;
this.bitcount = 0;
this.dest = dest;
this.destLen = 0;
this.ltree = new Tree(); /* dynamic length/symbol tree */
this.dtree = new Tree(); /* dynamic distance tree */
}
/* --------------------------------------------------- *
* -- uninitialized global data (static structures) -- *
* --------------------------------------------------- */
var sltree = new Tree();
var sdtree = new Tree();
/* extra bits and base tables for length codes */
var length_bits = new Uint8Array(30);
var length_base = new Uint16Array(30);
/* extra bits and base tables for distance codes */
var dist_bits = new Uint8Array(30);
var dist_base = new Uint16Array(30);
/* special ordering of code length codes */
var clcidx = new Uint8Array([
16, 17, 18, 0, 8, 7, 9, 6,
10, 5, 11, 4, 12, 3, 13, 2,
14, 1, 15
]);
/* used by tinf_decode_trees, avoids allocations every call */
var code_tree = new Tree();
var lengths = new Uint8Array(288 + 32);
/* ----------------------- *
* -- utility functions -- *
* ----------------------- */
/* build extra bits and base tables */
function tinf_build_bits_base(bits, base, delta, first) {
var i, sum;
/* build bits table */
for (i = 0; i < delta; ++i) bits[i] = 0;
for (i = 0; i < 30 - delta; ++i) bits[i + delta] = i / delta | 0;
/* build base table */
for (sum = first, i = 0; i < 30; ++i) {
base[i] = sum;
sum += 1 << bits[i];
}
}
/* build the fixed huffman trees */
function tinf_build_fixed_trees(lt, dt) {
var i;
/* build fixed length tree */
for (i = 0; i < 7; ++i) lt.table[i] = 0;
lt.table[7] = 24;
lt.table[8] = 152;
lt.table[9] = 112;
for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i;
for (i = 0; i < 144; ++i) lt.trans[24 + i] = i;
for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i;
for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i;
/* build fixed distance tree */
for (i = 0; i < 5; ++i) dt.table[i] = 0;
dt.table[5] = 32;
for (i = 0; i < 32; ++i) dt.trans[i] = i;
}
/* given an array of code lengths, build a tree */
var offs = new Uint16Array(16);
function tinf_build_tree(t, lengths, off, num) {
var i, sum;
/* clear code length count table */
for (i = 0; i < 16; ++i) t.table[i] = 0;
/* scan symbol lengths, and sum code length counts */
for (i = 0; i < num; ++i) t.table[lengths[off + i]]++;
t.table[0] = 0;
/* compute offset table for distribution sort */
for (sum = 0, i = 0; i < 16; ++i) {
offs[i] = sum;
sum += t.table[i];
}
/* create code->symbol translation table (symbols sorted by code) */
for (i = 0; i < num; ++i) {
if (lengths[off + i]) t.trans[offs[lengths[off + i]]++] = i;
}
}
/* ---------------------- *
* -- decode functions -- *
* ---------------------- */
/* get one bit from source stream */
function tinf_getbit(d) {
/* check if tag is empty */
if (!d.bitcount--) {
/* load next tag */
d.tag = d.source[d.sourceIndex++];
d.bitcount = 7;
}
/* shift bit out of tag */
var bit = d.tag & 1;
d.tag >>>= 1;
return bit;
}
/* read a num bit value from a stream and add base */
function tinf_read_bits(d, num, base) {
if (!num)
return base;
while (d.bitcount < 24) {
d.tag |= d.source[d.sourceIndex++] << d.bitcount;
d.bitcount += 8;
}
var val = d.tag & (0xffff >>> (16 - num));
d.tag >>>= num;
d.bitcount -= num;
return val + base;
}
/* given a data stream and a tree, decode a symbol */
function tinf_decode_symbol(d, t) {
while (d.bitcount < 24) {
d.tag |= d.source[d.sourceIndex++] << d.bitcount;
d.bitcount += 8;
}
var sum = 0, cur = 0, len = 0;
var tag = d.tag;
/* get more bits while code value is above sum */
do {
cur = 2 * cur + (tag & 1);
tag >>>= 1;
++len;
sum += t.table[len];
cur -= t.table[len];
} while (cur >= 0);
d.tag = tag;
d.bitcount -= len;
return t.trans[sum + cur];
}
/* given a data stream, decode dynamic trees from it */
function tinf_decode_trees(d, lt, dt) {
var hlit, hdist, hclen;
var i, num, length;
/* get 5 bits HLIT (257-286) */
hlit = tinf_read_bits(d, 5, 257);
/* get 5 bits HDIST (1-32) */
hdist = tinf_read_bits(d, 5, 1);
/* get 4 bits HCLEN (4-19) */
hclen = tinf_read_bits(d, 4, 4);
for (i = 0; i < 19; ++i) lengths[i] = 0;
/* read code lengths for code length alphabet */
for (i = 0; i < hclen; ++i) {
/* get 3 bits code length (0-7) */
var clen = tinf_read_bits(d, 3, 0);
lengths[clcidx[i]] = clen;
}
/* build code length tree */
tinf_build_tree(code_tree, lengths, 0, 19);
/* decode code lengths for the dynamic trees */
for (num = 0; num < hlit + hdist;) {
var sym = tinf_decode_symbol(d, code_tree);
switch (sym) {
case 16:
/* copy previous code length 3-6 times (read 2 bits) */
var prev = lengths[num - 1];
for (length = tinf_read_bits(d, 2, 3); length; --length) {
lengths[num++] = prev;
}
break;
case 17:
/* repeat code length 0 for 3-10 times (read 3 bits) */
for (length = tinf_read_bits(d, 3, 3); length; --length) {
lengths[num++] = 0;
}
break;
case 18:
/* repeat code length 0 for 11-138 times (read 7 bits) */
for (length = tinf_read_bits(d, 7, 11); length; --length) {
lengths[num++] = 0;
}
break;
default:
/* values 0-15 represent the actual code lengths */
lengths[num++] = sym;
break;
}
}
/* build dynamic trees */
tinf_build_tree(lt, lengths, 0, hlit);
tinf_build_tree(dt, lengths, hlit, hdist);
}
/* ----------------------------- *
* -- block inflate functions -- *
* ----------------------------- */
/* given a stream and two trees, inflate a block of data */
function tinf_inflate_block_data(d, lt, dt) {
while (1) {
var sym = tinf_decode_symbol(d, lt);
/* check for end of block */
if (sym === 256) {
return TINF_OK;
}
if (sym < 256) {
d.dest[d.destLen++] = sym;
} else {
var length, dist, offs;
var i;
sym -= 257;
/* possibly get more bits from length code */
length = tinf_read_bits(d, length_bits[sym], length_base[sym]);
dist = tinf_decode_symbol(d, dt);
/* possibly get more bits from distance code */
offs = d.destLen - tinf_read_bits(d, dist_bits[dist], dist_base[dist]);
/* copy match */
for (i = offs; i < offs + length; ++i) {
d.dest[d.destLen++] = d.dest[i];
}
}
}
}
/* inflate an uncompressed block of data */
function tinf_inflate_uncompressed_block(d) {
var length, invlength;
var i;
/* unread from bitbuffer */
while (d.bitcount > 8) {
d.sourceIndex--;
d.bitcount -= 8;
}
/* get length */
length = d.source[d.sourceIndex + 1];
length = 256 * length + d.source[d.sourceIndex];
/* get one's complement of length */
invlength = d.source[d.sourceIndex + 3];
invlength = 256 * invlength + d.source[d.sourceIndex + 2];
/* check length */
if (length !== (~invlength & 0x0000ffff))
return TINF_DATA_ERROR;
d.sourceIndex += 4;
/* copy block */
for (i = length; i; --i)
d.dest[d.destLen++] = d.source[d.sourceIndex++];
/* make sure we start next block on a byte boundary */
d.bitcount = 0;
return TINF_OK;
}
/* inflate stream from source to dest */
function tinf_uncompress(source, dest) {
var d = new Data(source, dest);
var bfinal, btype, res;
do {
/* read final block flag */
bfinal = tinf_getbit(d);
/* read block type (2 bits) */
btype = tinf_read_bits(d, 2, 0);
/* decompress block */
switch (btype) {
case 0:
/* decompress uncompressed block */
res = tinf_inflate_uncompressed_block(d);
break;
case 1:
/* decompress block with fixed huffman trees */
res = tinf_inflate_block_data(d, sltree, sdtree);
break;
case 2:
/* decompress block with dynamic huffman trees */
tinf_decode_trees(d, d.ltree, d.dtree);
res = tinf_inflate_block_data(d, d.ltree, d.dtree);
break;
default:
res = TINF_DATA_ERROR;
}
if (res !== TINF_OK)
throw new Error('Data error');
} while (!bfinal);
if (d.destLen < d.dest.length) {
if (typeof d.dest.slice === 'function')
return d.dest.slice(0, d.destLen);
else
return d.dest.subarray(0, d.destLen);
}
return d.dest;
}
/* -------------------- *
* -- initialization -- *
* -------------------- */
/* build fixed huffman trees */
tinf_build_fixed_trees(sltree, sdtree);
/* build extra bits and base tables */
tinf_build_bits_base(length_bits, length_base, 4, 3);
tinf_build_bits_base(dist_bits, dist_base, 2, 1);
/* fix a special case */
length_bits[28] = 0;
length_base[28] = 258;
module.exports = tinf_uncompress;
},{}],2:[function(require,module,exports){
// Run-time checking of preconditions.
'use strict';
exports.fail = function(message) {
throw new Error(message);
};
// Precondition function that checks if the given predicate is true.
// If not, it will throw an error.
exports.argument = function(predicate, message) {
if (!predicate) {
exports.fail(message);
}
};
// Precondition function that checks if the given assertion is true.
// If not, it will throw an error.
exports.assert = exports.argument;
},{}],3:[function(require,module,exports){
// Drawing utility functions.
'use strict';
// Draw a line on the given context from point `x1,y1` to point `x2,y2`.
function line(ctx, x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
exports.line = line;
},{}],4:[function(require,module,exports){
// Glyph encoding
'use strict';
var cffStandardStrings = [
'.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent', 'sterling',
'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle', 'quotedblleft', 'guillemotleft',
'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl', 'periodcentered', 'paragraph',
'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright', 'guillemotright', 'ellipsis', 'perthousand',
'questiondown', 'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'dieresis', 'ring',
'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE',
'ordmasculine', 'ae', 'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn', 'onequarter', 'divide', 'brokenbar', 'degree', 'thorn',
'threequarters', 'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior', 'copyright',
'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex',
'Edieresis', 'Egrave', 'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute', 'Ocircumflex',
'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute',
'Ydieresis', 'Zcaron', 'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute',
'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute',
'ocircumflex', 'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex', 'udieresis', 'ugrave',
'yacute', 'ydieresis', 'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior',
'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', '266 ff', 'onedotenleader',
'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior', 'threequartersemdash', 'periodsuperior',
'questionsmall', 'asuperior', 'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior', 'lsuperior',
'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior', 'ff', 'ffi', 'ffl',
'parenleftinferior', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', 'exclamdownsmall',
'centoldstyle', 'Lslashsmall', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall',
'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior',
'zeroinferior', 'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
'seveninferior', 'eightinferior', 'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall',
'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000',
'001.001', '001.002', '001.003', 'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'];
var cffStandardEncoding = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent', 'ampersand', 'quoteright',
'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two',
'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal', 'greater',
'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum', 'underscore',
'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'exclamdown', 'cent', 'sterling', 'fraction', 'yen', 'florin', 'section', 'currency', 'quotesingle',
'quotedblleft', 'guillemotleft', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', '', 'endash', 'dagger',
'daggerdbl', 'periodcentered', '', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase', 'quotedblright',
'guillemotright', 'ellipsis', 'perthousand', '', 'questiondown', '', 'grave', 'acute', 'circumflex', 'tilde',
'macron', 'breve', 'dotaccent', 'dieresis', '', 'ring', 'cedilla', '', 'hungarumlaut', 'ogonek', 'caron',
'emdash', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 'AE', '', 'ordfeminine', '', '', '',
'', 'Lslash', 'Oslash', 'OE', 'ordmasculine', '', '', '', '', '', 'ae', '', '', '', 'dotlessi', '', '',
'lslash', 'oslash', 'oe', 'germandbls'];
var cffExpertEncoding = [
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', 'space', 'exclamsmall', 'Hungarumlautsmall', '', 'dollaroldstyle', 'dollarsuperior',
'ampersandsmall', 'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader', 'onedotenleader',
'comma', 'hyphen', 'period', 'fraction', 'zerooldstyle', 'oneoldstyle', 'twooldstyle', 'threeoldstyle',
'fouroldstyle', 'fiveoldstyle', 'sixoldstyle', 'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'colon',
'semicolon', 'commasuperior', 'threequartersemdash', 'periodsuperior', 'questionsmall', '', 'asuperior',
'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', '', '', 'isuperior', '', '', 'lsuperior', 'msuperior',
'nsuperior', 'osuperior', '', '', 'rsuperior', 'ssuperior', 'tsuperior', '', 'ff', 'fi', 'fl', 'ffi', 'ffl',
'parenleftinferior', '', 'parenrightinferior', 'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall',
'Msmall', 'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'exclamdownsmall', 'centoldstyle', 'Lslashsmall', '', '', 'Scaronsmall', 'Zcaronsmall', 'Dieresissmall',
'Brevesmall', 'Caronsmall', '', 'Dotaccentsmall', '', '', 'Macronsmall', '', '', 'figuredash', 'hypheninferior',
'', '', 'Ogoneksmall', 'Ringsmall', 'Cedillasmall', '', '', '', 'onequarter', 'onehalf', 'threequarters',
'questiondownsmall', 'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds', '',
'', 'zerosuperior', 'onesuperior', 'twosuperior', 'threesuperior', 'foursuperior', 'fivesuperior',
'sixsuperior', 'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior', 'commainferior', 'Agravesmall',
'Aacutesmall', 'Acircumflexsmall', 'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall', 'Igravesmall', 'Iacutesmall',
'Icircumflexsmall', 'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall',
'Ocircumflexsmall', 'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall', 'Uacutesmall',
'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall', 'Thornsmall', 'Ydieresissmall'];
var standardNames = [
'.notdef', '.null', 'nonmarkingreturn', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
'ampersand', 'quotesingle', 'parenleft', 'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period', 'slash',
'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright',
'asciicircum', 'underscore', 'grave', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'braceleft', 'bar', 'braceright', 'asciitilde',
'Adieresis', 'Aring', 'Ccedilla', 'Eacute', 'Ntilde', 'Odieresis', 'Udieresis', 'aacute', 'agrave',
'acircumflex', 'adieresis', 'atilde', 'aring', 'ccedilla', 'eacute', 'egrave', 'ecircumflex', 'edieresis',
'iacute', 'igrave', 'icircumflex', 'idieresis', 'ntilde', 'oacute', 'ograve', 'ocircumflex', 'odieresis',
'otilde', 'uacute', 'ugrave', 'ucircumflex', 'udieresis', 'dagger', 'degree', 'cent', 'sterling', 'section',
'bullet', 'paragraph', 'germandbls', 'registered', 'copyright', 'trademark', 'acute', 'dieresis', 'notequal',
'AE', 'Oslash', 'infinity', 'plusminus', 'lessequal', 'greaterequal', 'yen', 'mu', 'partialdiff', 'summation',
'product', 'pi', 'integral', 'ordfeminine', 'ordmasculine', 'Omega', 'ae', 'oslash', 'questiondown',
'exclamdown', 'logicalnot', 'radical', 'florin', 'approxequal', 'Delta', 'guillemotleft', 'guillemotright',
'ellipsis', 'nonbreakingspace', 'Agrave', 'Atilde', 'Otilde', 'OE', 'oe', 'endash', 'emdash', 'quotedblleft',
'quotedblright', 'quoteleft', 'quoteright', 'divide', 'lozenge', 'ydieresis', 'Ydieresis', 'fraction',
'currency', 'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'daggerdbl', 'periodcentered', 'quotesinglbase',
'quotedblbase', 'perthousand', 'Acircumflex', 'Ecircumflex', 'Aacute', 'Edieresis', 'Egrave', 'Iacute',
'Icircumflex', 'Idieresis', 'Igrave', 'Oacute', 'Ocircumflex', 'apple', 'Ograve', 'Uacute', 'Ucircumflex',
'Ugrave', 'dotlessi', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent', 'ring', 'cedilla', 'hungarumlaut',
'ogonek', 'caron', 'Lslash', 'lslash', 'Scaron', 'scaron', 'Zcaron', 'zcaron', 'brokenbar', 'Eth', 'eth',
'Yacute', 'yacute', 'Thorn', 'thorn', 'minus', 'multiply', 'onesuperior', 'twosuperior', 'threesuperior',
'onehalf', 'onequarter', 'threequarters', 'franc', 'Gbreve', 'gbreve', 'Idotaccent', 'Scedilla', 'scedilla',
'Cacute', 'cacute', 'Ccaron', 'ccaron', 'dcroat'];
/**
* This is the encoding used for fonts created from scratch.
* It loops through all glyphs and finds the appropriate unicode value.
* Since it's linear time, other encodings will be faster.
* @exports opentype.DefaultEncoding
* @class
* @constructor
* @param {opentype.Font}
*/
function DefaultEncoding(font) {
this.font = font;
}
DefaultEncoding.prototype.charToGlyphIndex = function(c) {
var code = c.charCodeAt(0);
var glyphs = this.font.glyphs;
if (glyphs) {
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
for (var j = 0; j < glyph.unicodes.length; j += 1) {
if (glyph.unicodes[j] === code) {
return i;
}
}
}
} else {
return null;
}
};
/**
* @exports opentype.CmapEncoding
* @class
* @constructor
* @param {Object} cmap - a object with the cmap encoded data
*/
function CmapEncoding(cmap) {
this.cmap = cmap;
}
/**
* @param {string} c - the character
* @return {number} The glyph index.
*/
CmapEncoding.prototype.charToGlyphIndex = function(c) {
return this.cmap.glyphIndexMap[c.charCodeAt(0)] || 0;
};
/**
* @exports opentype.CffEncoding
* @class
* @constructor
* @param {string} encoding - The encoding
* @param {Array} charset - The charcater set.
*/
function CffEncoding(encoding, charset) {
this.encoding = encoding;
this.charset = charset;
}
/**
* @param {string} s - The character
* @return {number} The index.
*/
CffEncoding.prototype.charToGlyphIndex = function(s) {
var code = s.charCodeAt(0);
var charName = this.encoding[code];
return this.charset.indexOf(charName);
};
/**
* @exports opentype.GlyphNames
* @class
* @constructor
* @param {Object} post
*/
function GlyphNames(post) {
var i;
switch (post.version) {
case 1:
this.names = exports.standardNames.slice();
break;
case 2:
this.names = new Array(post.numberOfGlyphs);
for (i = 0; i < post.numberOfGlyphs; i++) {
if (post.glyphNameIndex[i] < exports.standardNames.length) {
this.names[i] = exports.standardNames[post.glyphNameIndex[i]];
} else {
this.names[i] = post.names[post.glyphNameIndex[i] - exports.standardNames.length];
}
}
break;
case 2.5:
this.names = new Array(post.numberOfGlyphs);
for (i = 0; i < post.numberOfGlyphs; i++) {
this.names[i] = exports.standardNames[i + post.glyphNameIndex[i]];
}
break;
case 3:
this.names = [];
break;
}
}
/**
* Gets the index of a glyph by name.
* @param {string} name - The glyph name
* @return {number} The index
*/
GlyphNames.prototype.nameToGlyphIndex = function(name) {
return this.names.indexOf(name);
};
/**
* @param {number} gid
* @return {string}
*/
GlyphNames.prototype.glyphIndexToName = function(gid) {
return this.names[gid];
};
/**
* @alias opentype.addGlyphNames
* @param {opentype.Font}
*/
function addGlyphNames(font) {
var glyph;
var glyphIndexMap = font.tables.cmap.glyphIndexMap;
var charCodes = Object.keys(glyphIndexMap);
for (var i = 0; i < charCodes.length; i += 1) {
var c = charCodes[i];
var glyphIndex = glyphIndexMap[c];
glyph = font.glyphs.get(glyphIndex);
glyph.addUnicode(parseInt(c));
}
for (i = 0; i < font.glyphs.length; i += 1) {
glyph = font.glyphs.get(i);
if (font.cffEncoding) {
glyph.name = font.cffEncoding.charset[i];
} else if (font.glyphNames.names) {
glyph.name = font.glyphNames.glyphIndexToName(i);
}
}
}
exports.cffStandardStrings = cffStandardStrings;
exports.cffStandardEncoding = cffStandardEncoding;
exports.cffExpertEncoding = cffExpertEncoding;
exports.standardNames = standardNames;
exports.DefaultEncoding = DefaultEncoding;
exports.CmapEncoding = CmapEncoding;
exports.CffEncoding = CffEncoding;
exports.GlyphNames = GlyphNames;
exports.addGlyphNames = addGlyphNames;
},{}],5:[function(require,module,exports){
// The Font object
'use strict';
var path = require('./path');
var sfnt = require('./tables/sfnt');
var encoding = require('./encoding');
var glyphset = require('./glyphset');
var Substitution = require('./substitution');
var util = require('./util');
/**
* @typedef FontOptions
* @type Object
* @property {Boolean} empty - whether to create a new empty font
* @property {string} familyName
* @property {string} styleName
* @property {string=} fullName
* @property {string=} postScriptName
* @property {string=} designer
* @property {string=} designerURL
* @property {string=} manufacturer
* @property {string=} manufacturerURL
* @property {string=} license
* @property {string=} licenseURL
* @property {string=} version
* @property {string=} description
* @property {string=} copyright
* @property {string=} trademark
* @property {Number} unitsPerEm
* @property {Number} ascender
* @property {Number} descender
* @property {Number} createdTimestamp
* @property {string=} weightClass
* @property {string=} widthClass
* @property {string=} fsSelection
*/
/**
* A Font represents a loaded OpenType font file.
* It contains a set of glyphs and methods to draw text on a drawing context,
* or to get a path representing the text.
* @exports opentype.Font
* @class
* @param {FontOptions}
* @constructor
*/
function Font(options) {
options = options || {};
if (!options.empty) {
// Check that we've provided the minimum set of names.
util.checkArgument(options.familyName, 'When creating a new Font object, familyName is required.');
util.checkArgument(options.styleName, 'When creating a new Font object, styleName is required.');
util.checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.');
util.checkArgument(options.ascender, 'When creating a new Font object, ascender is required.');
util.checkArgument(options.descender, 'When creating a new Font object, descender is required.');
util.checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).');
// OS X will complain if the names are empty, so we put a single space everywhere by default.
this.names = {
fontFamily: {en: options.familyName || ' '},
fontSubfamily: {en: options.styleName || ' '},
fullName: {en: options.fullName || options.familyName + ' ' + options.styleName},
postScriptName: {en: options.postScriptName || options.familyName + options.styleName},
designer: {en: options.designer || ' '},
designerURL: {en: options.designerURL || ' '},
manufacturer: {en: options.manufacturer || ' '},
manufacturerURL: {en: options.manufacturerURL || ' '},
license: {en: options.license || ' '},
licenseURL: {en: options.licenseURL || ' '},
version: {en: options.version || 'Version 0.1'},
description: {en: options.description || ' '},
copyright: {en: options.copyright || ' '},
trademark: {en: options.trademark || ' '}
};
this.unitsPerEm = options.unitsPerEm || 1000;
this.ascender = options.ascender;
this.descender = options.descender;
this.createdTimestamp = options.createdTimestamp;
this.tables = { os2: {
usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM,
usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM,
fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR
} };
}
this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported.
this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []);
this.encoding = new encoding.DefaultEncoding(this);
this.substitution = new Substitution(this);
this.tables = this.tables || {};
}
/**
* Check if the font has a glyph for the given character.
* @param {string}
* @return {Boolean}
*/
Font.prototype.hasChar = function(c) {
return this.encoding.charToGlyphIndex(c) !== null;
};
/**
* Convert the given character to a single glyph index.
* Note that this function assumes that there is a one-to-one mapping between
* the given character and a glyph; for complex scripts this might not be the case.
* @param {string}
* @return {Number}
*/
Font.prototype.charToGlyphIndex = function(s) {
return this.encoding.charToGlyphIndex(s);
};
/**
* Convert the given character to a single Glyph object.
* Note that this function assumes that there is a one-to-one mapping between
* the given character and a glyph; for complex scripts this might not be the case.
* @param {string}
* @return {opentype.Glyph}
*/
Font.prototype.charToGlyph = function(c) {
var glyphIndex = this.charToGlyphIndex(c);
var glyph = this.glyphs.get(glyphIndex);
if (!glyph) {
// .notdef
glyph = this.glyphs.get(0);
}
return glyph;
};
/**
* Convert the given text to a list of Glyph objects.
* Note that there is no strict one-to-one mapping between characters and
* glyphs, so the list of returned glyphs can be larger or smaller than the
* length of the given string.
* @param {string}
* @return {opentype.Glyph[]}
*/
Font.prototype.stringToGlyphs = function(s) {
var glyphs = [];
for (var i = 0; i < s.length; i += 1) {
var c = s[i];
glyphs.push(this.charToGlyph(c));
}
return glyphs;
};
/**
* @param {string}
* @return {Number}
*/
Font.prototype.nameToGlyphIndex = function(name) {
return this.glyphNames.nameToGlyphIndex(name);
};
/**
* @param {string}
* @return {opentype.Glyph}
*/
Font.prototype.nameToGlyph = function(name) {
var glyphIndex = this.nameToGlyphIndex(name);
var glyph = this.glyphs.get(glyphIndex);
if (!glyph) {
// .notdef
glyph = this.glyphs.get(0);
}
return glyph;
};
/**
* @param {Number}
* @return {String}
*/
Font.prototype.glyphIndexToName = function(gid) {
if (!this.glyphNames.glyphIndexToName) {
return '';
}
return this.glyphNames.glyphIndexToName(gid);
};
/**
* Retrieve the value of the kerning pair between the left glyph (or its index)
* and the right glyph (or its index). If no kerning pair is found, return 0.
* The kerning value gets added to the advance width when calculating the spacing
* between glyphs.
* @param {opentype.Glyph} leftGlyph
* @param {opentype.Glyph} rightGlyph
* @return {Number}
*/
Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) {
leftGlyph = leftGlyph.index || leftGlyph;
rightGlyph = rightGlyph.index || rightGlyph;
var gposKerning = this.getGposKerningValue;
return gposKerning ? gposKerning(leftGlyph, rightGlyph) :
(this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0);
};
/**
* @typedef GlyphRenderOptions
* @type Object
* @property {boolean} [kerning] - whether to include kerning values
*/
/**
* Helper function that invokes the given callback for each glyph in the given text.
* The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text
* @param {string} text - The text to apply.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @param {Function} callback
*/
Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) {
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 72;
options = options || {};
var kerning = options.kerning === undefined ? true : options.kerning;
var fontScale = 1 / this.unitsPerEm * fontSize;
var glyphs = this.stringToGlyphs(text);
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs[i];
callback(glyph, x, y, fontSize, options);
if (glyph.advanceWidth) {
x += glyph.advanceWidth * fontScale;
}
if (kerning && i < glyphs.length - 1) {
var kerningValue = this.getKerningValue(glyph, glyphs[i + 1]);
x += kerningValue * fontScale;
}
if (options.letterSpacing) {
x += options.letterSpacing * fontSize;
} else if (options.tracking) {
x += (options.tracking / 1000) * fontSize;
}
}
};
/**
* Create a Path object that represents the given text.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @return {opentype.Path}
*/
Font.prototype.getPath = function(text, x, y, fontSize, options) {
var fullPath = new path.Path();
this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
var glyphPath = glyph.getPath(gX, gY, gFontSize);
fullPath.extend(glyphPath);
});
return fullPath;
};
/**
* Create an array of Path objects that represent the glyps of a given text.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @return {opentype.Path[]}
*/
Font.prototype.getPaths = function(text, x, y, fontSize, options) {
var glyphPaths = [];
this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
var glyphPath = glyph.getPath(gX, gY, gFontSize);
glyphPaths.push(glyphPath);
});
return glyphPaths;
};
/**
* Draw the text on the given drawing context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.draw = function(ctx, text, x, y, fontSize, options) {
this.getPath(text, x, y, fontSize, options).draw(ctx);
};
/**
* Draw the points of all glyphs in the text.
* On-curve points will be drawn in blue, off-curve points will be drawn in red.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) {
this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
glyph.drawPoints(ctx, gX, gY, gFontSize);
});
};
/**
* Draw lines indicating important font measurements for all glyphs in the text.
* Black lines indicate the origin of the coordinate system (point 0,0).
* Blue lines indicate the glyph bounding box.
* Green line indicates the advance width of the glyph.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {string} text - The text to create.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
*/
Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) {
this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) {
glyph.drawMetrics(ctx, gX, gY, gFontSize);
});
};
/**
* @param {string}
* @return {string}
*/
Font.prototype.getEnglishName = function(name) {
var translations = this.names[name];
if (translations) {
return translations.en;
}
};
/**
* Validate
*/
Font.prototype.validate = function() {
var warnings = [];
var _this = this;
function assert(predicate, message) {
if (!predicate) {
warnings.push(message);
}
}
function assertNamePresent(name) {
var englishName = _this.getEnglishName(name);
assert(englishName && englishName.trim().length > 0,
'No English ' + name + ' specified.');
}
// Identification information
assertNamePresent('fontFamily');
assertNamePresent('weightName');
assertNamePresent('manufacturer');
assertNamePresent('copyright');
assertNamePresent('version');
// Dimension information
assert(this.unitsPerEm > 0, 'No unitsPerEm specified.');
};
/**
* Convert the font object to a SFNT data structure.
* This structure contains all the necessary tables and metadata to create a binary OTF file.
* @return {opentype.Table}
*/
Font.prototype.toTables = function() {
return sfnt.fontToTable(this);
};
/**
* @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.
*/
Font.prototype.toBuffer = function() {
console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.');
return this.toArrayBuffer();
};
/**
* Converts a `opentype.Font` into an `ArrayBuffer`
* @return {ArrayBuffer}
*/
Font.prototype.toArrayBuffer = function() {
var sfntTable = this.toTables();
var bytes = sfntTable.encode();
var buffer = new ArrayBuffer(bytes.length);
var intArray = new Uint8Array(buffer);
for (var i = 0; i < bytes.length; i++) {
intArray[i] = bytes[i];
}
return buffer;
};
/**
* Initiate a download of the OpenType font.
*/
Font.prototype.download = function(fileName) {
var familyName = this.getEnglishName('fontFamily');
var styleName = this.getEnglishName('fontSubfamily');
fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf';
var arrayBuffer = this.toArrayBuffer();
if (util.isBrowser()) {
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], {type: 'font/opentype'});
writer.write(blob);
writer.addEventListener('writeend', function() {
// Navigating to the file will download it.
location.href = fileEntry.toURL();
}, false);
});
});
},
function(err) {
throw new Error(err.name + ': ' + err.message);
});
} else {
var fs = require('fs');
var buffer = util.arrayBufferToNodeBuffer(arrayBuffer);
fs.writeFileSync(fileName, buffer);
}
};
/**
* @private
*/
Font.prototype.fsSelectionValues = {
ITALIC: 0x001, //1
UNDERSCORE: 0x002, //2
NEGATIVE: 0x004, //4
OUTLINED: 0x008, //8
STRIKEOUT: 0x010, //16
BOLD: 0x020, //32
REGULAR: 0x040, //64
USER_TYPO_METRICS: 0x080, //128
WWS: 0x100, //256
OBLIQUE: 0x200 //512
};
/**
* @private
*/
Font.prototype.usWidthClasses = {
ULTRA_CONDENSED: 1,
EXTRA_CONDENSED: 2,
CONDENSED: 3,
SEMI_CONDENSED: 4,
MEDIUM: 5,
SEMI_EXPANDED: 6,
EXPANDED: 7,
EXTRA_EXPANDED: 8,
ULTRA_EXPANDED: 9
};
/**
* @private
*/
Font.prototype.usWeightClasses = {
THIN: 100,
EXTRA_LIGHT: 200,
LIGHT: 300,
NORMAL: 400,
MEDIUM: 500,
SEMI_BOLD: 600,
BOLD: 700,
EXTRA_BOLD: 800,
BLACK: 900
};
exports.Font = Font;
},{"./encoding":4,"./glyphset":7,"./path":11,"./substitution":12,"./tables/sfnt":31,"./util":33,"fs":undefined}],6:[function(require,module,exports){
// The Glyph object
'use strict';
var check = require('./check');
var draw = require('./draw');
var path = require('./path');
function getPathDefinition(glyph, path) {
var _path = path || { commands: [] };
return {
configurable: true,
get: function() {
if (typeof _path === 'function') {
_path = _path();
}
return _path;
},
set: function(p) {
_path = p;
}
};
}
/**
* @typedef GlyphOptions
* @type Object
* @property {string} [name] - The glyph name
* @property {number} [unicode]
* @property {Array} [unicodes]
* @property {number} [xMin]
* @property {number} [yMin]
* @property {number} [xMax]
* @property {number} [yMax]
* @property {number} [advanceWidth]
*/
// A Glyph is an individual mark that often corresponds to a character.
// Some glyphs, such as ligatures, are a combination of many characters.
// Glyphs are the basic building blocks of a font.
//
// The `Glyph` class contains utility methods for drawing the path and its points.
/**
* @exports opentype.Glyph
* @class
* @param {GlyphOptions}
* @constructor
*/
function Glyph(options) {
// By putting all the code on a prototype function (which is only declared once)
// we reduce the memory requirements for larger fonts by some 2%
this.bindConstructorValues(options);
}
/**
* @param {GlyphOptions}
*/
Glyph.prototype.bindConstructorValues = function(options) {
this.index = options.index || 0;
// These three values cannnot be deferred for memory optimization:
this.name = options.name || null;
this.unicode = options.unicode || undefined;
this.unicodes = options.unicodes || options.unicode !== undefined ? [options.unicode] : [];
// But by binding these values only when necessary, we reduce can
// the memory requirements by almost 3% for larger fonts.
if (options.xMin) {
this.xMin = options.xMin;
}
if (options.yMin) {
this.yMin = options.yMin;
}
if (options.xMax) {
this.xMax = options.xMax;
}
if (options.yMax) {
this.yMax = options.yMax;
}
if (options.advanceWidth) {
this.advanceWidth = options.advanceWidth;
}
// The path for a glyph is the most memory intensive, and is bound as a value
// with a getter/setter to ensure we actually do path parsing only once the
// path is actually needed by anything.
Object.defineProperty(this, 'path', getPathDefinition(this, options.path));
};
/**
* @param {number}
*/
Glyph.prototype.addUnicode = function(unicode) {
if (this.unicodes.length === 0) {
this.unicode = unicode;
}
this.unicodes.push(unicode);
};
/**
* Convert the glyph to a Path we can draw on a drawing context.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {Object=} options - xScale, yScale to strech the glyph.
* @return {opentype.Path}
*/
Glyph.prototype.getPath = function(x, y, fontSize, options) {
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
options = options !== undefined ? options : {xScale: 1.0, yScale: 1.0};
fontSize = fontSize !== undefined ? fontSize : 72;
var scale = 1 / this.path.unitsPerEm * fontSize;
var xScale = options.xScale * scale;
var yScale = options.yScale * scale;
var p = new path.Path();
var commands = this.path.commands;
for (var i = 0; i < commands.length; i += 1) {
var cmd = commands[i];
if (cmd.type === 'M') {
p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'L') {
p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'Q') {
p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'C') {
p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale),
x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'Z') {
p.closePath();
}
}
return p;
};
/**
* Split the glyph into contours.
* This function is here for backwards compatibility, and to
* provide raw access to the TrueType glyph outlines.
* @return {Array}
*/
Glyph.prototype.getContours = function() {
if (this.points === undefined) {
return [];
}
var contours = [];
var currentContour = [];
for (var i = 0; i < this.points.length; i += 1) {
var pt = this.points[i];
currentContour.push(pt);
if (pt.lastPointOfContour) {
contours.push(currentContour);
currentContour = [];
}
}
check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
return contours;
};
/**
* Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph.
* @return {Object}
*/
Glyph.prototype.getMetrics = function() {
var commands = this.path.commands;
var xCoords = [];
var yCoords = [];
for (var i = 0; i < commands.length; i += 1) {
var cmd = commands[i];
if (cmd.type !== 'Z') {
xCoords.push(cmd.x);
yCoords.push(cmd.y);
}
if (cmd.type === 'Q' || cmd.type === 'C') {
xCoords.push(cmd.x1);
yCoords.push(cmd.y1);
}
if (cmd.type === 'C') {
xCoords.push(cmd.x2);
yCoords.push(cmd.y2);
}
}
var metrics = {
xMin: Math.min.apply(null, xCoords),
yMin: Math.min.apply(null, yCoords),
xMax: Math.max.apply(null, xCoords),
yMax: Math.max.apply(null, yCoords),
leftSideBearing: this.leftSideBearing
};
if (!isFinite(metrics.xMin)) {
metrics.xMin = 0;
}
if (!isFinite(metrics.xMax)) {
metrics.xMax = this.advanceWidth;
}
if (!isFinite(metrics.yMin)) {
metrics.yMin = 0;
}
if (!isFinite(metrics.yMax)) {
metrics.yMax = 0;
}
metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin);
return metrics;
};
/**
* Draw the glyph on the given context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {Object=} options - xScale, yScale to strech the glyph.
*/
Glyph.prototype.draw = function(ctx, x, y, fontSize, options) {
this.getPath(x, y, fontSize, options).draw(ctx);
};
/**
* Draw the points of the glyph.
* On-curve points will be drawn in blue, off-curve points will be drawn in red.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
*/
Glyph.prototype.drawPoints = function(ctx, x, y, fontSize) {
function drawCircles(l, x, y, scale) {
var PI_SQ = Math.PI * 2;
ctx.beginPath();
for (var j = 0; j < l.length; j += 1) {
ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale));
ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, PI_SQ, false);
}
ctx.closePath();
ctx.fill();
}
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
var scale = 1 / this.path.unitsPerEm * fontSize;
var blueCircles = [];
var redCircles = [];
var path = this.path;
for (var i = 0; i < path.commands.length; i += 1) {
var cmd = path.commands[i];
if (cmd.x !== undefined) {
blueCircles.push({x: cmd.x, y: -cmd.y});
}
if (cmd.x1 !== undefined) {
redCircles.push({x: cmd.x1, y: -cmd.y1});
}
if (cmd.x2 !== undefined) {
redCircles.push({x: cmd.x2, y: -cmd.y2});
}
}
ctx.fillStyle = 'blue';
drawCircles(blueCircles, x, y, scale);
ctx.fillStyle = 'red';
drawCircles(redCircles, x, y, scale);
};
/**
* Draw lines indicating important font measurements.
* Black lines indicate the origin of the coordinate system (point 0,0).
* Blue lines indicate the glyph bounding box.
* Green line indicates the advance width of the glyph.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
*/
Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) {
var scale;
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
scale = 1 / this.path.unitsPerEm * fontSize;
ctx.lineWidth = 1;
// Draw the origin
ctx.strokeStyle = 'black';
draw.line(ctx, x, -10000, x, 10000);
draw.line(ctx, -10000, y, 10000, y);
// This code is here due to memory optimization: by not using
// defaults in the constructor, we save a notable amount of memory.
var xMin = this.xMin || 0;
var yMin = this.yMin || 0;
var xMax = this.xMax || 0;
var yMax = this.yMax || 0;
var advanceWidth = this.advanceWidth || 0;
// Draw the glyph box
ctx.strokeStyle = 'blue';
draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000);
draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000);
draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale));
draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale));
// Draw the advance width
ctx.strokeStyle = 'green';
draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000);
};
exports.Glyph = Glyph;
},{"./check":2,"./draw":3,"./path":11}],7:[function(require,module,exports){
// The GlyphSet object
'use strict';
var _glyph = require('./glyph');
// Define a property on the glyph that depends on the path being loaded.
function defineDependentProperty(glyph, externalName, internalName) {
Object.defineProperty(glyph, externalName, {
get: function() {
// Request the path property to make sure the path is loaded.
glyph.path; // jshint ignore:line
return glyph[internalName];
},
set: function(newValue) {
glyph[internalName] = newValue;
},
enumerable: true,
configurable: true
});
}
/**
* A GlyphSet represents all glyphs available in the font, but modelled using
* a deferred glyph loader, for retrieving glyphs only once they are absolutely
* necessary, to keep the memory footprint down.
* @exports opentype.GlyphSet
* @class
* @param {opentype.Font}
* @param {Array}
*/
function GlyphSet(font, glyphs) {
this.font = font;
this.glyphs = {};
if (Array.isArray(glyphs)) {
for (var i = 0; i < glyphs.length; i++) {
this.glyphs[i] = glyphs[i];
}
}
this.length = (glyphs && glyphs.length) || 0;
}
/**
* @param {number} index
* @return {opentype.Glyph}
*/
GlyphSet.prototype.get = function(index) {
if (typeof this.glyphs[index] === 'function') {
this.glyphs[index] = this.glyphs[index]();
}
return this.glyphs[index];
};
/**
* @param {number} index
* @param {Object}
*/
GlyphSet.prototype.push = function(index, loader) {
this.glyphs[index] = loader;
this.length++;
};
/**
* @alias opentype.glyphLoader
* @param {opentype.Font} font
* @param {number} index
* @return {opentype.Glyph}
*/
function glyphLoader(font, index) {
return new _glyph.Glyph({index: index, font: font});
}
/**
* Generate a stub glyph that can be filled with all metadata *except*
* the "points" and "path" properties, which must be loaded only once
* the glyph's path is actually requested for text shaping.
* @alias opentype.ttfGlyphLoader
* @param {opentype.Font} font
* @param {number} index
* @param {Function} parseGlyph
* @param {Object} data
* @param {number} position
* @param {Function} buildPath
* @return {opentype.Glyph}
*/
function ttfGlyphLoader(font, index, parseGlyph, data, position, buildPath) {
return function() {
var glyph = new _glyph.Glyph({index: index, font: font});
glyph.path = function() {
parseGlyph(glyph, data, position);
var path = buildPath(font.glyphs, glyph);
path.unitsPerEm = font.unitsPerEm;
return path;
};
defineDependentProperty(glyph, 'xMin', '_xMin');
defineDependentProperty(glyph, 'xMax', '_xMax');
defineDependentProperty(glyph, 'yMin', '_yMin');
defineDependentProperty(glyph, 'yMax', '_yMax');
return glyph;
};
}
/**
* @alias opentype.cffGlyphLoader
* @param {opentype.Font} font
* @param {number} index
* @param {Function} parseCFFCharstring
* @param {string} charstring
* @return {opentype.Glyph}
*/
function cffGlyphLoader(font, index, parseCFFCharstring, charstring) {
return function() {
var glyph = new _glyph.Glyph({index: index, font: font});
glyph.path = function() {
var path = parseCFFCharstring(font, glyph, charstring);
path.unitsPerEm = font.unitsPerEm;
return path;
};
return glyph;
};
}
exports.GlyphSet = GlyphSet;
exports.glyphLoader = glyphLoader;
exports.ttfGlyphLoader = ttfGlyphLoader;
exports.cffGlyphLoader = cffGlyphLoader;
},{"./glyph":6}],8:[function(require,module,exports){
// The Layout object is the prototype of Substition objects, and provides utility methods to manipulate
// common layout tables (GPOS, GSUB, GDEF...)
'use strict';
var check = require('./check');
function searchTag(arr, tag) {
/* jshint bitwise: false */
var imin = 0;
var imax = arr.length - 1;
while (imin <= imax) {
var imid = (imin + imax) >>> 1;
var val = arr[imid].tag;
if (val === tag) {
return imid;
} else if (val < tag) {
imin = imid + 1;
} else { imax = imid - 1; }
}
// Not found: return -1-insertion point
return -imin - 1;
}
function binSearch(arr, value) {
/* jshint bitwise: false */
var imin = 0;
var imax = arr.length - 1;
while (imin <= imax) {
var imid = (imin + imax) >>> 1;
var val = arr[imid];
if (val === value) {
return imid;
} else if (val < value) {
imin = imid + 1;
} else { imax = imid - 1; }
}
// Not found: return -1-insertion point
return -imin - 1;
}
/**
* @exports opentype.Layout
* @class
*/
var Layout = {
/**
* Binary search an object by "tag" property
* @instance
* @function searchTag
* @memberof opentype.Layout
* @param {Array} arr
* @param {string} tag
* @return {number}
*/
searchTag: searchTag,
/**
* Binary search in a list of numbers
* @instance
* @function binSearch
* @memberof opentype.Layout
* @param {Array} arr
* @param {number} value
* @return {number}
*/
binSearch: binSearch,
/**
* Returns all scripts in the substitution table.
* @instance
* @return {Array}
*/
getScriptNames: function() {
var gsub = this.getGsubTable();
if (!gsub) { return []; }
return gsub.scripts.map(function(script) {
return script.tag;
});
},
/**
* Returns all LangSysRecords in the given script.
* @instance
* @param {string} script - Use 'DFLT' for default script
* @param {boolean} create - forces the creation of this script table if it doesn't exist.
* @return {Object} An object with tag and script properties.
*/
getScriptTable: function(script, create) {
var gsub = this.getGsubTable(create);
if (gsub) {
var scripts = gsub.scripts;
var pos = searchTag(gsub.scripts, script);
if (pos >= 0) {
return scripts[pos].script;
} else {
var scr = {
tag: script,
script: {
defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] },
langSysRecords: []
}
};
scripts.splice(-1 - pos, 0, scr.script);
return scr;
}
}
},
/**
* Returns a language system table
* @instance
* @param {string} script - Use 'DFLT' for default script
* @param {string} language - Use 'DFLT' for default language
* @param {boolean} create - forces the creation of this langSysTable if it doesn't exist.
* @return {Object}
*/
getLangSysTable: function(script, language, create) {
var scriptTable = this.getScriptTable(script, create);
if (scriptTable) {
if (language === 'DFLT') {
return scriptTable.defaultLangSys;
}
var pos = searchTag(scriptTable.langSysRecords, language);
if (pos >= 0) {
return scriptTable.langSysRecords[pos].langSys;
} else if (create) {
var langSysRecord = {
tag: language,
langSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] }
};
scriptTable.langSysRecords.splice(-1 - pos, 0, langSysRecord);
return langSysRecord.langSys;
}
}
},
/**
* Get a specific feature table.
* @instance
* @param {string} script - Use 'DFLT' for default script
* @param {string} language - Use 'DFLT' for default language
* @param {string} feature - One of the codes listed at https://www.microsoft.com/typography/OTSPEC/featurelist.htm
* @param {boolean} create - forces the creation of the feature table if it doesn't exist.
* @return {Object}
*/
getFeatureTable: function(script, language, feature, create) {
var langSysTable = this.getLangSysTable(script, language, create);
if (langSysTable) {
var featureRecord;
var featIndexes = langSysTable.featureIndexes;
var allFeatures = this.font.tables.gsub.features;
// The FeatureIndex array of indices is in arbitrary order,
// even if allFeatures is sorted alphabetically by feature tag.
for (var i = 0; i < featIndexes.length; i++) {
featureRecord = allFeatures[featIndexes[i]];
if (featureRecord.tag === feature) {
return featureRecord.feature;
}
}
if (create) {
var index = allFeatures.length;
// Automatic ordering of features would require to shift feature indexes in the script list.
check.assert(index === 0 || feature >= allFeatures[index - 1].tag, 'Features must be added in alphabetical order.');
featureRecord = {
tag: feature,
feature: { params: 0, lookupListIndexes: [] }
};
allFeatures.push(featureRecord);
featIndexes.push(index);
return featureRecord.feature;
}
}
},
/**
* Get the first lookup table of a given type for a script/language/feature.
* @instance
* @param {string} script - Use 'DFLT' for default script
* @param {string} language - Use 'DFLT' for default language
* @param {string} feature - 4-letter feature code
* @param {number} lookupType - 1 to 8
* @param {boolean} create - forces the creation of the lookup table if it doesn't exist, with no subtables.
* @return {Object}
*/
getLookupTable: function(script, language, feature, lookupType, create) {
var featureTable = this.getFeatureTable(script, language, feature, create);
if (featureTable) {
var lookupTable;
var lookupListIndexes = featureTable.lookupListIndexes;
var allLookups = this.font.tables.gsub.lookups;
// lookupListIndexes are in no particular order, so use naïve search.
for (var i = 0; i < lookupListIndexes.length; i++) {
lookupTable = allLookups[lookupListIndexes[i]];
if (lookupTable.lookupType === lookupType) {
return lookupTable;
}
}
if (create) {
lookupTable = {
lookupType: lookupType,
lookupFlag: 0,
subtables: [],
markFilteringSet: undefined
};
var index = allLookups.length;
allLookups.push(lookupTable);
lookupListIndexes.push(index);
return lookupTable;
}
}
},
/**
* Returns the list of glyph indexes of a coverage table.
* Format 1: the list is stored raw
* Format 2: compact list as range records.
* @instance
* @param {Object} coverageTable
* @return {Array}
*/
expandCoverage: function(coverageTable) {
if (coverageTable.format === 1) {
return coverageTable.glyphs;
} else {
var glyphs = [];
var ranges = coverageTable.ranges;
for (var i = 0; i < ranges; i++) {
var range = ranges[i];
var start = range.start;
var end = range.end;
for (var j = start; j <= end; j++) {
glyphs.push(j);
}
}
return glyphs;
}
}
};
module.exports = Layout;
},{"./check":2}],9:[function(require,module,exports){
// opentype.js
// https://github.com/nodebox/opentype.js
// (c) 2015 Frederik De Bleser
// opentype.js may be freely distributed under the MIT license.
/* global DataView, Uint8Array, XMLHttpRequest */
'use strict';
var inflate = require('tiny-inflate');
var encoding = require('./encoding');
var _font = require('./font');
var glyph = require('./glyph');
var parse = require('./parse');
var path = require('./path');
var util = require('./util');
var cmap = require('./tables/cmap');
var cff = require('./tables/cff');
var fvar = require('./tables/fvar');
var glyf = require('./tables/glyf');
var gpos = require('./tables/gpos');
var gsub = require('./tables/gsub');
var head = require('./tables/head');
var hhea = require('./tables/hhea');
var hmtx = require('./tables/hmtx');
var kern = require('./tables/kern');
var ltag = require('./tables/ltag');
var loca = require('./tables/loca');
var maxp = require('./tables/maxp');
var _name = require('./tables/name');
var os2 = require('./tables/os2');
var post = require('./tables/post');
var meta = require('./tables/meta');
/**
* The opentype library.
* @namespace opentype
*/
// File loaders /////////////////////////////////////////////////////////
/**
* Loads a font from a file. The callback throws an error message as the first parameter if it fails
* and the font as an ArrayBuffer in the second parameter if it succeeds.
* @param {string} path - The path of the file
* @param {Function} callback - The function to call when the font load completes
*/
function loadFromFile(path, callback) {
var fs = require('fs');
fs.readFile(path, function(err, buffer) {
if (err) {
return callback(err.message);
}
callback(null, util.nodeBufferToArrayBuffer(buffer));
});
}
/**
* Loads a font from a URL. The callback throws an error message as the first parameter if it fails
* and the font as an ArrayBuffer in the second parameter if it succeeds.
* @param {string} url - The URL of the font file.
* @param {Function} callback - The function to call when the font load completes
*/
function loadFromUrl(url, callback) {
var request = new XMLHttpRequest();
request.open('get', url, true);
request.responseType = 'arraybuffer';
request.onload = function() {
if (request.status !== 200) {
return callback('Font could not be loaded: ' + request.statusText);
}
return callback(null, request.response);
};
request.send();
}
// Table Directory Entries //////////////////////////////////////////////
/**
* Parses OpenType table entries.
* @param {DataView}
* @param {Number}
* @return {Object[]}
*/
function parseOpenTypeTableEntries(data, numTables) {
var tableEntries = [];
var p = 12;
for (var i = 0; i < numTables; i += 1) {
var tag = parse.getTag(data, p);
var checksum = parse.getULong(data, p + 4);
var offset = parse.getULong(data, p + 8);
var length = parse.getULong(data, p + 12);
tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false});
p += 16;
}
return tableEntries;
}
/**
* Parses WOFF table entries.
* @param {DataView}
* @param {Number}
* @return {Object[]}
*/
function parseWOFFTableEntries(data, numTables) {
var tableEntries = [];
var p = 44; // offset to the first table directory entry.
for (var i = 0; i < numTables; i += 1) {
var tag = parse.getTag(data, p);
var offset = parse.getULong(data, p + 4);
var compLength = parse.getULong(data, p + 8);
var origLength = parse.getULong(data, p + 12);
var compression;
if (compLength < origLength) {
compression = 'WOFF';
} else {
compression = false;
}
tableEntries.push({tag: tag, offset: offset, compression: compression,
compressedLength: compLength, originalLength: origLength});
p += 20;
}
return tableEntries;
}
/**
* @typedef TableData
* @type Object
* @property {DataView} data - The DataView
* @property {number} offset - The data offset.
*/
/**
* @param {DataView}
* @param {Object}
* @return {TableData}
*/
function uncompressTable(data, tableEntry) {
if (tableEntry.compression === 'WOFF') {
var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2);
var outBuffer = new Uint8Array(tableEntry.originalLength);
inflate(inBuffer, outBuffer);
if (outBuffer.byteLength !== tableEntry.originalLength) {
throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length');
}
var view = new DataView(outBuffer.buffer, 0);
return {data: view, offset: 0};
} else {
return {data: data, offset: tableEntry.offset};
}
}
// Public API ///////////////////////////////////////////////////////////
/**
* Parse the OpenType file data (as an ArrayBuffer) and return a Font object.
* Throws an error if the font could not be parsed.
* @param {ArrayBuffer}
* @return {opentype.Font}
*/
function parseBuffer(buffer) {
var indexToLocFormat;
var ltagTable;
// Since the constructor can also be called to create new fonts from scratch, we indicate this
// should be an empty font that we'll fill with our own data.
var font = new _font.Font({empty: true});
// OpenType fonts use big endian byte ordering.
// We can't rely on typed array view types, because they operate with the endianness of the host computer.
// Instead we use DataViews where we can specify endianness.
var data = new DataView(buffer, 0);
var numTables;
var tableEntries = [];
var signature = parse.getTag(data, 0);
if (signature === String.fromCharCode(0, 1, 0, 0)) {
font.outlinesFormat = 'truetype';
numTables = parse.getUShort(data, 4);
tableEntries = parseOpenTypeTableEntries(data, numTables);
} else if (signature === 'OTTO') {
font.outlinesFormat = 'cff';
numTables = parse.getUShort(data, 4);
tableEntries = parseOpenTypeTableEntries(data, numTables);
} else if (signature === 'wOFF') {
var flavor = parse.getTag(data, 4);
if (flavor === String.fromCharCode(0, 1, 0, 0)) {
font.outlinesFormat = 'truetype';
} else if (flavor === 'OTTO') {
font.outlinesFormat = 'cff';
} else {
throw new Error('Unsupported OpenType flavor ' + signature);
}
numTables = parse.getUShort(data, 12);
tableEntries = parseWOFFTableEntries(data, numTables);
} else {
throw new Error('Unsupported OpenType signature ' + signature);
}
var cffTableEntry;
var fvarTableEntry;
var glyfTableEntry;
var gposTableEntry;
var gsubTableEntry;
var hmtxTableEntry;
var kernTableEntry;
var locaTableEntry;
var nameTableEntry;
var metaTableEntry;
for (var i = 0; i < numTables; i += 1) {
var tableEntry = tableEntries[i];
var table;
switch (tableEntry.tag) {
case 'cmap':
table = uncompressTable(data, tableEntry);
font.tables.cmap = cmap.parse(table.data, table.offset);
font.encoding = new encoding.CmapEncoding(font.tables.cmap);
break;
case 'fvar':
fvarTableEntry = tableEntry;
break;
case 'head':
table = uncompressTable(data, tableEntry);
font.tables.head = head.parse(table.data, table.offset);
font.unitsPerEm = font.tables.head.unitsPerEm;
indexToLocFormat = font.tables.head.indexToLocFormat;
break;
case 'hhea':
table = uncompressTable(data, tableEntry);
font.tables.hhea = hhea.parse(table.data, table.offset);
font.ascender = font.tables.hhea.ascender;
font.descender = font.tables.hhea.descender;
font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics;
break;
case 'hmtx':
hmtxTableEntry = tableEntry;
break;
case 'ltag':
table = uncompressTable(data, tableEntry);
ltagTable = ltag.parse(table.data, table.offset);
break;
case 'maxp':
table = uncompressTable(data, tableEntry);
font.tables.maxp = maxp.parse(table.data, table.offset);
font.numGlyphs = font.tables.maxp.numGlyphs;
break;
case 'name':
nameTableEntry = tableEntry;
break;
case 'OS/2':
table = uncompressTable(data, tableEntry);
font.tables.os2 = os2.parse(table.data, table.offset);
break;
case 'post':
table = uncompressTable(data, tableEntry);
font.tables.post = post.parse(table.data, table.offset);
font.glyphNames = new encoding.GlyphNames(font.tables.post);
break;
case 'glyf':
glyfTableEntry = tableEntry;
break;
case 'loca':
locaTableEntry = tableEntry;
break;
case 'CFF ':
cffTableEntry = tableEntry;
break;
case 'kern':
kernTableEntry = tableEntry;
break;
case 'GPOS':
gposTableEntry = tableEntry;
break;
case 'GSUB':
gsubTableEntry = tableEntry;
break;
case 'meta':
metaTableEntry = tableEntry;
break;
}
}
var nameTable = uncompressTable(data, nameTableEntry);
font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable);
font.names = font.tables.name;
if (glyfTableEntry && locaTableEntry) {
var shortVersion = indexToLocFormat === 0;
var locaTable = uncompressTable(data, locaTableEntry);
var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion);
var glyfTable = uncompressTable(data, glyfTableEntry);
font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font);
} else if (cffTableEntry) {
var cffTable = uncompressTable(data, cffTableEntry);
cff.parse(cffTable.data, cffTable.offset, font);
} else {
throw new Error('Font doesn\'t contain TrueType or CFF outlines.');
}
var hmtxTable = uncompressTable(data, hmtxTableEntry);
hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs);
encoding.addGlyphNames(font);
if (kernTableEntry) {
var kernTable = uncompressTable(data, kernTableEntry);
font.kerningPairs = kern.parse(kernTable.data, kernTable.offset);
} else {
font.kerningPairs = {};
}
if (gposTableEntry) {
var gposTable = uncompressTable(data, gposTableEntry);
gpos.parse(gposTable.data, gposTable.offset, font);
}
if (gsubTableEntry) {
var gsubTable = uncompressTable(data, gsubTableEntry);
font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset);
}
if (fvarTableEntry) {
var fvarTable = uncompressTable(data, fvarTableEntry);
font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names);
}
if (metaTableEntry) {
var metaTable = uncompressTable(data, metaTableEntry);
font.tables.meta = meta.parse(metaTable.data, metaTable.offset);
font.metas = font.tables.meta;
}
return font;
}
/**
* Asynchronously load the font from a URL or a filesystem. When done, call the callback
* with two arguments `(err, font)`. The `err` will be null on success,
* the `font` is a Font object.
* We use the node.js callback convention so that
* opentype.js can integrate with frameworks like async.js.
* @alias opentype.load
* @param {string} url - The URL of the font to load.
* @param {Function} callback - The callback.
*/
function load(url, callback) {
var isNode = typeof window === 'undefined';
var loadFn = isNode ? loadFromFile : loadFromUrl;
loadFn(url, function(err, arrayBuffer) {
if (err) {
return callback(err);
}
var font;
try {
font = parseBuffer(arrayBuffer);
} catch (e) {
return callback(e, null);
}
return callback(null, font);
});
}
/**
* Synchronously load the font from a URL or file.
* When done, returns the font object or throws an error.
* @alias opentype.loadSync
* @param {string} url - The URL of the font to load.
* @return {opentype.Font}
*/
function loadSync(url) {
var fs = require('fs');
var buffer = fs.readFileSync(url);
return parseBuffer(util.nodeBufferToArrayBuffer(buffer));
}
exports._parse = parse;
exports.Font = _font.Font;
exports.Glyph = glyph.Glyph;
exports.Path = path.Path;
exports.parse = parseBuffer;
exports.load = load;
exports.loadSync = loadSync;
},{"./encoding":4,"./font":5,"./glyph":6,"./parse":10,"./path":11,"./tables/cff":14,"./tables/cmap":15,"./tables/fvar":16,"./tables/glyf":17,"./tables/gpos":18,"./tables/gsub":19,"./tables/head":20,"./tables/hhea":21,"./tables/hmtx":22,"./tables/kern":23,"./tables/loca":24,"./tables/ltag":25,"./tables/maxp":26,"./tables/meta":27,"./tables/name":28,"./tables/os2":29,"./tables/post":30,"./util":33,"fs":undefined,"tiny-inflate":1}],10:[function(require,module,exports){
// Parsing utility functions
'use strict';
var check = require('./check');
// Retrieve an unsigned byte from the DataView.
exports.getByte = function getByte(dataView, offset) {
return dataView.getUint8(offset);
};
exports.getCard8 = exports.getByte;
// Retrieve an unsigned 16-bit short from the DataView.
// The value is stored in big endian.
function getUShort(dataView, offset) {
return dataView.getUint16(offset, false);
}
exports.getUShort = exports.getCard16 = getUShort;
// Retrieve a signed 16-bit short from the DataView.
// The value is stored in big endian.
exports.getShort = function(dataView, offset) {
return dataView.getInt16(offset, false);
};
// Retrieve an unsigned 32-bit long from the DataView.
// The value is stored in big endian.
exports.getULong = function(dataView, offset) {
return dataView.getUint32(offset, false);
};
// Retrieve a 32-bit signed fixed-point number (16.16) from the DataView.
// The value is stored in big endian.
exports.getFixed = function(dataView, offset) {
var decimal = dataView.getInt16(offset, false);
var fraction = dataView.getUint16(offset + 2, false);
return decimal + fraction / 65535;
};
// Retrieve a 4-character tag from the DataView.
// Tags are used to identify tables.
exports.getTag = function(dataView, offset) {
var tag = '';
for (var i = offset; i < offset + 4; i += 1) {
tag += String.fromCharCode(dataView.getInt8(i));
}
return tag;
};
// Retrieve an offset from the DataView.
// Offsets are 1 to 4 bytes in length, depending on the offSize argument.
exports.getOffset = function(dataView, offset, offSize) {
var v = 0;
for (var i = 0; i < offSize; i += 1) {
v <<= 8;
v += dataView.getUint8(offset + i);
}
return v;
};
// Retrieve a number of bytes from start offset to the end offset from the DataView.
exports.getBytes = function(dataView, startOffset, endOffset) {
var bytes = [];
for (var i = startOffset; i < endOffset; i += 1) {
bytes.push(dataView.getUint8(i));
}
return bytes;
};
// Convert the list of bytes to a string.
exports.bytesToString = function(bytes) {
var s = '';
for (var i = 0; i < bytes.length; i += 1) {
s += String.fromCharCode(bytes[i]);
}
return s;
};
var typeOffsets = {
byte: 1,
uShort: 2,
short: 2,
uLong: 4,
fixed: 4,
longDateTime: 8,
tag: 4
};
// A stateful parser that changes the offset whenever a value is retrieved.
// The data is a DataView.
function Parser(data, offset) {
this.data = data;
this.offset = offset;
this.relativeOffset = 0;
}
Parser.prototype.parseByte = function() {
var v = this.data.getUint8(this.offset + this.relativeOffset);
this.relativeOffset += 1;
return v;
};
Parser.prototype.parseChar = function() {
var v = this.data.getInt8(this.offset + this.relativeOffset);
this.relativeOffset += 1;
return v;
};
Parser.prototype.parseCard8 = Parser.prototype.parseByte;
Parser.prototype.parseUShort = function() {
var v = this.data.getUint16(this.offset + this.relativeOffset);
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseCard16 = Parser.prototype.parseUShort;
Parser.prototype.parseSID = Parser.prototype.parseUShort;
Parser.prototype.parseOffset16 = Parser.prototype.parseUShort;
Parser.prototype.parseShort = function() {
var v = this.data.getInt16(this.offset + this.relativeOffset);
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseF2Dot14 = function() {
var v = this.data.getInt16(this.offset + this.relativeOffset) / 16384;
this.relativeOffset += 2;
return v;
};
Parser.prototype.parseULong = function() {
var v = exports.getULong(this.data, this.offset + this.relativeOffset);
this.relativeOffset += 4;
return v;
};
Parser.prototype.parseFixed = function() {
var v = exports.getFixed(this.data, this.offset + this.relativeOffset);
this.relativeOffset += 4;
return v;
};
Parser.prototype.parseString = function(length) {
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
var string = '';
this.relativeOffset += length;
for (var i = 0; i < length; i++) {
string += String.fromCharCode(dataView.getUint8(offset + i));
}
return string;
};
Parser.prototype.parseTag = function() {
return this.parseString(4);
};
// LONGDATETIME is a 64-bit integer.
// JavaScript and unix timestamps traditionally use 32 bits, so we
// only take the last 32 bits.
// + Since until 2038 those bits will be filled by zeros we can ignore them.
Parser.prototype.parseLongDateTime = function() {
var v = exports.getULong(this.data, this.offset + this.relativeOffset + 4);
// Subtract seconds between 01/01/1904 and 01/01/1970
// to convert Apple Mac timstamp to Standard Unix timestamp
v -= 2082844800;
this.relativeOffset += 8;
return v;
};
Parser.prototype.parseVersion = function() {
var major = getUShort(this.data, this.offset + this.relativeOffset);
// How to interpret the minor version is very vague in the spec. 0x5000 is 5, 0x1000 is 1
// This returns the correct number if minor = 0xN000 where N is 0-9
var minor = getUShort(this.data, this.offset + this.relativeOffset + 2);
this.relativeOffset += 4;
return major + minor / 0x1000 / 10;
};
Parser.prototype.skip = function(type, amount) {
if (amount === undefined) {
amount = 1;
}
this.relativeOffset += typeOffsets[type] * amount;
};
///// Parsing lists and records ///////////////////////////////
// Parse a list of 16 bit integers. The length of the list can be read on the stream
// or provided as an argument.
Parser.prototype.parseOffset16List =
Parser.prototype.parseUShortList = function(count) {
if (count === undefined) { count = this.parseUShort(); }
var offsets = new Array(count);
var dataView = this.data;
var offset = this.offset + this.relativeOffset;
for (var i = 0; i < count; i++) {
offsets[i] = dataView.getUint16(offset);
offset += 2;
}
this.relativeOffset += count * 2;
return offsets;
};
/**
* Parse a list of items.
* Record count is optional, if omitted it is read from the stream.
* itemCallback is one of the Parser methods.
*/
Parser.prototype.parseList = function(count, itemCallback) {
if (!itemCallback) {
itemCallback = count;
count = this.parseUShort();
}
var list = new Array(count);
for (var i = 0; i < count; i++) {
list[i] = itemCallback.call(this);
}
return list;
};
/**
* Parse a list of records.
* Record count is optional, if omitted it is read from the stream.
* Example of recordDescription: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
*/
Parser.prototype.parseRecordList = function(count, recordDescription) {
// If the count argument is absent, read it in the stream.
if (!recordDescription) {
recordDescription = count;
count = this.parseUShort();
}
var records = new Array(count);
var fields = Object.keys(recordDescription);
for (var i = 0; i < count; i++) {
var rec = {};
for (var j = 0; j < fields.length; j++) {
var fieldName = fields[j];
var fieldType = recordDescription[fieldName];
rec[fieldName] = fieldType.call(this);
}
records[i] = rec;
}
return records;
};
// Parse a data structure into an object
// Example of description: { sequenceIndex: Parser.uShort, lookupListIndex: Parser.uShort }
Parser.prototype.parseStruct = function(description) {
if (typeof description === 'function') {
return description.call(this);
} else {
var fields = Object.keys(description);
var struct = {};
for (var j = 0; j < fields.length; j++) {
var fieldName = fields[j];
var fieldType = description[fieldName];
struct[fieldName] = fieldType.call(this);
}
return struct;
}
};
Parser.prototype.parsePointer = function(description) {
var structOffset = this.parseOffset16();
if (structOffset > 0) { // NULL offset => return indefined
return new Parser(this.data, this.offset + structOffset).parseStruct(description);
}
};
/**
* Parse a list of offsets to lists of 16-bit integers,
* or a list of offsets to lists of offsets to any kind of items.
* If itemCallback is not provided, a list of list of UShort is assumed.
* If provided, itemCallback is called on each item and must parse the item.
* See examples in tables/gsub.js
*/
Parser.prototype.parseListOfLists = function(itemCallback) {
var offsets = this.parseOffset16List();
var count = offsets.length;
var relativeOffset = this.relativeOffset;
var list = new Array(count);
for (var i = 0; i < count; i++) {
var start = offsets[i];
if (start === 0) { // NULL offset
list[i] = undefined; // Add i as owned property to list. Convenient with assert.
continue;
}
this.relativeOffset = start;
if (itemCallback) {
var subOffsets = this.parseOffset16List();
var subList = new Array(subOffsets.length);
for (var j = 0; j < subOffsets.length; j++) {
this.relativeOffset = start + subOffsets[j];
subList[j] = itemCallback.call(this);
}
list[i] = subList;
} else {
list[i] = this.parseUShortList();
}
}
this.relativeOffset = relativeOffset;
return list;
};
///// Complex tables parsing //////////////////////////////////
// Parse a coverage table in a GSUB, GPOS or GDEF table.
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
// parser.offset must point to the start of the table containing the coverage.
Parser.prototype.parseCoverage = function() {
var startOffset = this.offset + this.relativeOffset;
var format = this.parseUShort();
var count = this.parseUShort();
if (format === 1) {
return {
format: 1,
glyphs: this.parseUShortList(count)
};
} else if (format === 2) {
var ranges = new Array(count);
for (var i = 0; i < count; i++) {
ranges[i] = {
start: this.parseUShort(),
end: this.parseUShort(),
index: this.parseUShort()
};
}
return {
format: 2,
ranges: ranges
};
}
check.assert(false, '0x' + startOffset.toString(16) + ': Coverage format must be 1 or 2.');
};
// Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
Parser.prototype.parseClassDef = function() {
var startOffset = this.offset + this.relativeOffset;
var format = this.parseUShort();
if (format === 1) {
return {
format: 1,
startGlyph: this.parseUShort(),
classes: this.parseUShortList()
};
} else if (format === 2) {
return {
format: 2,
ranges: this.parseRecordList({
start: Parser.uShort,
end: Parser.uShort,
classId: Parser.uShort
})
};
}
check.assert(false, '0x' + startOffset.toString(16) + ': ClassDef format must be 1 or 2.');
};
///// Static methods ///////////////////////////////////
// These convenience methods can be used as callbacks and should be called with "this" context set to a Parser instance.
Parser.list = function(count, itemCallback) {
return function() {
return this.parseList(count, itemCallback);
};
};
Parser.recordList = function(count, recordDescription) {
return function() {
return this.parseRecordList(count, recordDescription);
};
};
Parser.pointer = function(description) {
return function() {
return this.parsePointer(description);
};
};
Parser.tag = Parser.prototype.parseTag;
Parser.byte = Parser.prototype.parseByte;
Parser.uShort = Parser.offset16 = Parser.prototype.parseUShort;
Parser.uShortList = Parser.prototype.parseUShortList;
Parser.struct = Parser.prototype.parseStruct;
Parser.coverage = Parser.prototype.parseCoverage;
Parser.classDef = Parser.prototype.parseClassDef;
///// Script, Feature, Lookup lists ///////////////////////////////////////////////
// https://www.microsoft.com/typography/OTSPEC/chapter2.htm
var langSysTable = {
reserved: Parser.uShort,
reqFeatureIndex: Parser.uShort,
featureIndexes: Parser.uShortList
};
Parser.prototype.parseScriptList = function() {
return this.parsePointer(Parser.recordList({
tag: Parser.tag,
script: Parser.pointer({
defaultLangSys: Parser.pointer(langSysTable),
langSysRecords: Parser.recordList({
tag: Parser.tag,
langSys: Parser.pointer(langSysTable)
})
})
}));
};
Parser.prototype.parseFeatureList = function() {
return this.parsePointer(Parser.recordList({
tag: Parser.tag,
feature: Parser.pointer({
featureParams: Parser.offset16,
lookupListIndexes: Parser.uShortList
})
}));
};
Parser.prototype.parseLookupList = function(lookupTableParsers) {
return this.parsePointer(Parser.list(Parser.pointer(function() {
var lookupType = this.parseUShort();
check.argument(1 <= lookupType && lookupType <= 8, 'GSUB lookup type ' + lookupType + ' unknown.');
var lookupFlag = this.parseUShort();
var useMarkFilteringSet = lookupFlag & 0x10;
return {
lookupType: lookupType,
lookupFlag: lookupFlag,
subtables: this.parseList(Parser.pointer(lookupTableParsers[lookupType])),
markFilteringSet: useMarkFilteringSet ? this.parseUShort() : undefined
};
})));
};
exports.Parser = Parser;
},{"./check":2}],11:[function(require,module,exports){
// Geometric objects
'use strict';
/**
* A bézier path containing a set of path commands similar to a SVG path.
* Paths can be drawn on a context using `draw`.
* @exports opentype.Path
* @class
* @constructor
*/
function Path() {
this.commands = [];
this.fill = 'black';
this.stroke = null;
this.strokeWidth = 1;
}
/**
* @param {number} x
* @param {number} y
*/
Path.prototype.moveTo = function(x, y) {
this.commands.push({
type: 'M',
x: x,
y: y
});
};
/**
* @param {number} x
* @param {number} y
*/
Path.prototype.lineTo = function(x, y) {
this.commands.push({
type: 'L',
x: x,
y: y
});
};
/**
* Draws cubic curve
* @function
* curveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control 1
* @param {number} y1 - y of control 1
* @param {number} x2 - x of control 2
* @param {number} y2 - y of control 2
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
/**
* Draws cubic curve
* @function
* bezierCurveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control 1
* @param {number} y1 - y of control 1
* @param {number} x2 - x of control 2
* @param {number} y2 - y of control 2
* @param {number} x - x of path point
* @param {number} y - y of path point
* @see curveTo
*/
Path.prototype.curveTo = Path.prototype.bezierCurveTo = function(x1, y1, x2, y2, x, y) {
this.commands.push({
type: 'C',
x1: x1,
y1: y1,
x2: x2,
y2: y2,
x: x,
y: y
});
};
/**
* Draws quadratic curve
* @function
* quadraticCurveTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control
* @param {number} y1 - y of control
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
/**
* Draws quadratic curve
* @function
* quadTo
* @memberof opentype.Path.prototype
* @param {number} x1 - x of control
* @param {number} y1 - y of control
* @param {number} x - x of path point
* @param {number} y - y of path point
*/
Path.prototype.quadTo = Path.prototype.quadraticCurveTo = function(x1, y1, x, y) {
this.commands.push({
type: 'Q',
x1: x1,
y1: y1,
x: x,
y: y
});
};
/**
* Closes the path
* @function closePath
* @memberof opentype.Path.prototype
*/
/**
* Close the path
* @function close
* @memberof opentype.Path.prototype
*/
Path.prototype.close = Path.prototype.closePath = function() {
this.commands.push({
type: 'Z'
});
};
/**
* Add the given path or list of commands to the commands of this path.
* @param {Array}
*/
Path.prototype.extend = function(pathOrCommands) {
if (pathOrCommands.commands) {
pathOrCommands = pathOrCommands.commands;
}
Array.prototype.push.apply(this.commands, pathOrCommands);
};
/**
* Draw the path to a 2D context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context.
*/
Path.prototype.draw = function(ctx) {
ctx.beginPath();
for (var i = 0; i < this.commands.length; i += 1) {
var cmd = this.commands[i];
if (cmd.type === 'M') {
ctx.moveTo(cmd.x, cmd.y);
} else if (cmd.type === 'L') {
ctx.lineTo(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
} else if (cmd.type === 'Z') {
ctx.closePath();
}
}
if (this.fill) {
ctx.fillStyle = this.fill;
ctx.fill();
}
if (this.stroke) {
ctx.strokeStyle = this.stroke;
ctx.lineWidth = this.strokeWidth;
ctx.stroke();
}
};
/**
* Convert the Path to a string of path data instructions
* See http://www.w3.org/TR/SVG/paths.html#PathData
* @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
* @return {string}
*/
Path.prototype.toPathData = function(decimalPlaces) {
decimalPlaces = decimalPlaces !== undefined ? decimalPlaces : 2;
function floatToString(v) {
if (Math.round(v) === v) {
return '' + Math.round(v);
} else {
return v.toFixed(decimalPlaces);
}
}
function packValues() {
var s = '';
for (var i = 0; i < arguments.length; i += 1) {
var v = arguments[i];
if (v >= 0 && i > 0) {
s += ' ';
}
s += floatToString(v);
}
return s;
}
var d = '';
for (var i = 0; i < this.commands.length; i += 1) {
var cmd = this.commands[i];
if (cmd.type === 'M') {
d += 'M' + packValues(cmd.x, cmd.y);
} else if (cmd.type === 'L') {
d += 'L' + packValues(cmd.x, cmd.y);
} else if (cmd.type === 'C') {
d += 'C' + packValues(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
} else if (cmd.type === 'Q') {
d += 'Q' + packValues(cmd.x1, cmd.y1, cmd.x, cmd.y);
} else if (cmd.type === 'Z') {
d += 'Z';
}
}
return d;
};
/**
* Convert the path to an SVG <path> element, as a string.
* @param {number} [decimalPlaces=2] - The amount of decimal places for floating-point values
* @return {string}
*/
Path.prototype.toSVG = function(decimalPlaces) {
var svg = '<path d="';
svg += this.toPathData(decimalPlaces);
svg += '"';
if (this.fill && this.fill !== 'black') {
if (this.fill === null) {
svg += ' fill="none"';
} else {
svg += ' fill="' + this.fill + '"';
}
}
if (this.stroke) {
svg += ' stroke="' + this.stroke + '" stroke-width="' + this.strokeWidth + '"';
}
svg += '/>';
return svg;
};
exports.Path = Path;
},{}],12:[function(require,module,exports){
// The Substitution object provides utility methods to manipulate
// the GSUB substitution table.
'use strict';
var check = require('./check');
var Layout = require('./layout');
/**
* @exports opentype.Substitution
* @class
* @extends opentype.Layout
* @param {opentype.Font}
* @constructor
*/
var Substitution = function(font) {
this.font = font;
};
// Check if 2 arrays of primitives are equal.
function arraysEqual(ar1, ar2) {
var n = ar1.length;
if (n !== ar2.length) { return false; }
for (var i = 0; i < n; i++) {
if (ar1[i] !== ar2[i]) { return false; }
}
return true;
}
// Find the first subtable of a lookup table in a particular format.
function getSubstFormat(lookupTable, format, defaultSubtable) {
var subtables = lookupTable.subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
if (subtable.substFormat === format) {
return subtable;
}
}
if (defaultSubtable) {
subtables.push(defaultSubtable);
return defaultSubtable;
}
}
Substitution.prototype = Layout;
/**
* Get or create the GSUB table.
* @param {boolean} create - Whether to create a new one.
* @return {Object} gsub - The GSUB table.
*/
Substitution.prototype.getGsubTable = function(create) {
var gsub = this.font.tables.gsub;
if (!gsub && create) {
// Generate a default empty GSUB table with just a DFLT script and dflt lang sys.
this.font.tables.gsub = gsub = {
version: 1,
scripts: [{
tag: 'DFLT',
script: {
defaultLangSys: { reserved: 0, reqFeatureIndex: 0xffff, featureIndexes: [] },
langSysRecords: []
}
}],
features: [],
lookups: []
};
}
return gsub;
};
/**
* List all single substitutions (lookup type 1) for a given script, language, and feature.
* @param {string} script
* @param {string} language
* @param {string} feature - 4-character feature name ('aalt', 'salt', 'ss01'...)
* @return {Array} substitutions - The list of substitutions.
*/
Substitution.prototype.getSingle = function(feature, script, language) {
var substitutions = [];
var lookupTable = this.getLookupTable(script, language, feature, 1);
if (!lookupTable) { return substitutions; }
var subtables = lookupTable.subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this.expandCoverage(subtable.coverage);
var j;
if (subtable.substFormat === 1) {
var delta = subtable.deltaGlyphId;
for (j = 0; j < glyphs.length; j++) {
var glyph = glyphs[j];
substitutions.push({ sub: glyph, by: glyph + delta });
}
} else {
var substitute = subtable.substitute;
for (j = 0; j < glyphs.length; j++) {
substitutions.push({ sub: glyphs[j], by: substitute[j] });
}
}
}
return substitutions;
};
/**
* List all alternates (lookup type 3) for a given script, language, and feature.
* @param {string} script
* @param {string} language
* @param {string} feature - 4-character feature name ('aalt', 'salt'...)
* @return {Array} alternates - The list of alternates
*/
Substitution.prototype.getAlternates = function(feature, script, language) {
var alternates = [];
var lookupTable = this.getLookupTable(script, language, feature, 3);
if (!lookupTable) { return alternates; }
var subtables = lookupTable.subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this.expandCoverage(subtable.coverage);
var alternateSets = subtable.alternateSets;
for (var j = 0; j < glyphs.length; j++) {
alternates.push({ sub: glyphs[j], by: alternateSets[j] });
}
}
return alternates;
};
/**
* List all ligatures (lookup type 4) for a given script, language, and feature.
* The result is an array of ligature objects like { sub: [ids], by: id }
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {string} script
* @param {string} language
* @return {Array} ligatures - The list of ligatures.
*/
Substitution.prototype.getLigatures = function(feature, script, language) {
var ligatures = [];
var lookupTable = this.getLookupTable(script, language, feature, 4);
if (!lookupTable) { return []; }
var subtables = lookupTable.subtables;
for (var i = 0; i < subtables.length; i++) {
var subtable = subtables[i];
var glyphs = this.expandCoverage(subtable.coverage);
var ligatureSets = subtable.ligatureSets;
for (var j = 0; j < glyphs.length; j++) {
var startGlyph = glyphs[j];
var ligSet = ligatureSets[j];
for (var k = 0; k < ligSet.length; k++) {
var lig = ligSet[k];
ligatures.push({
sub: [startGlyph].concat(lig.components),
by: lig.ligGlyph
});
}
}
}
return ligatures;
};
/**
* Add or modify a single substitution (lookup type 1)
* Format 2, more flexible, is always used.
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} substitution - { sub: id, delta: number } for format 1 or { sub: id, by: id } for format 2.
* @param {string} [script='DFLT']
* @param {string} [language='DFLT']
*/
Substitution.prototype.addSingle = function(feature, substitution, script, language) {
var lookupTable = this.getLookupTable(script, language, feature, 1, true);
var subtable = getSubstFormat(lookupTable, 2, { // lookup type 1 subtable, format 2, coverage format 1
substFormat: 2,
coverage: { format: 1, glyphs: [] },
substitute: []
});
check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
var coverageGlyph = substitution.sub;
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos < 0) {
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.substitute.splice(pos, 0, 0);
}
subtable.substitute[pos] = substitution.by;
};
/**
* Add or modify an alternate substitution (lookup type 1)
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} substitution - { sub: id, by: [ids] }
* @param {string} [script='DFLT']
* @param {string} [language='DFLT']
*/
Substitution.prototype.addAlternate = function(feature, substitution, script, language) {
var lookupTable = this.getLookupTable(script, language, feature, 3, true);
var subtable = getSubstFormat(lookupTable, 1, { // lookup type 3 subtable, format 1, coverage format 1
substFormat: 1,
coverage: { format: 1, glyphs: [] },
alternateSets: []
});
check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
var coverageGlyph = substitution.sub;
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos < 0) {
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.alternateSets.splice(pos, 0, 0);
}
subtable.alternateSets[pos] = substitution.by;
};
/**
* Add a ligature (lookup type 4)
* Ligatures with more components must be stored ahead of those with fewer components in order to be found
* @param {string} feature - 4-letter feature name ('liga', 'rlig', 'dlig'...)
* @param {Object} ligature - { sub: [ids], by: id }
* @param {string} [script='DFLT']
* @param {string} [language='DFLT']
*/
Substitution.prototype.addLigature = function(feature, ligature, script, language) {
script = script || 'DFLT';
language = language || 'DFLT';
var lookupTable = this.getLookupTable(script, language, feature, 4, true);
var subtable = lookupTable.subtables[0];
if (!subtable) {
subtable = { // lookup type 4 subtable, format 1, coverage format 1
substFormat: 1,
coverage: { format: 1, glyphs: [] },
ligatureSets: []
};
lookupTable.subtables[0] = subtable;
}
check.assert(subtable.coverage.format === 1, 'Ligature: unable to modify coverage table format ' + subtable.coverage.format);
var coverageGlyph = ligature.sub[0];
var ligComponents = ligature.sub.slice(1);
var ligatureTable = {
ligGlyph: ligature.by,
components: ligComponents
};
var pos = this.binSearch(subtable.coverage.glyphs, coverageGlyph);
if (pos >= 0) {
// ligatureSet already exists
var ligatureSet = subtable.ligatureSets[pos];
for (var i = 0; i < ligatureSet.length; i++) {
// If ligature already exists, return.
if (arraysEqual(ligatureSet[i].components, ligComponents)) {
return;
}
}
// ligature does not exist: add it.
ligatureSet.push(ligatureTable);
} else {
// Create a new ligatureSet and add coverage for the first glyph.
pos = -1 - pos;
subtable.coverage.glyphs.splice(pos, 0, coverageGlyph);
subtable.ligatureSets.splice(pos, 0, [ligatureTable]);
}
};
/**
* List all feature data for a given script and language.
* @param {string} feature - 4-letter feature name
* @param {string} [script='DFLT']
* @param {string} [language='DFLT']
* @return {Array} substitutions - The list of substitutions.
*/
Substitution.prototype.getFeature = function(feature, script, language) {
script = script || 'DFLT';
language = language || 'DFLT';
if (/ss\d\d/.test(feature)) { // ss01 - ss20
return this.getSingle(feature, script, language);
}
switch (feature) {
case 'aalt':
case 'salt':
return this.getSingle(feature, script, language)
.concat(this.getAlternates(feature, script, language));
case 'dlig':
case 'liga':
case 'rlig': return this.getLigatures(feature, script, language);
}
};
/**
* Add a substitution to a feature for a given script and language.
* @param {string} feature - 4-letter feature name
* @param {Object} sub - the substitution to add (an object like { sub: id or [ids], by: id or [ids] })
* @param {string} [script='DFLT']
* @param {string} [language='DFLT']
*/
Substitution.prototype.add = function(feature, sub, script, language) {
script = script || 'DFLT';
language = language || 'DFLT';
if (/ss\d\d/.test(feature)) { // ss01 - ss20
return this.addSingle(feature, sub, script, language);
}
switch (feature) {
case 'aalt':
case 'salt':
if (typeof sub.by === 'number') {
return this.addSingle(feature, sub, script, language);
}
return this.addAlternate(feature, sub, script, language);
case 'dlig':
case 'liga':
case 'rlig':
return this.addLigature(feature, sub, script, language);
}
};
module.exports = Substitution;
},{"./check":2,"./layout":8}],13:[function(require,module,exports){
// Table metadata
'use strict';
var check = require('./check');
var encode = require('./types').encode;
var sizeOf = require('./types').sizeOf;
/**
* @exports opentype.Table
* @class
* @param {string} tableName
* @param {Array} fields
* @param {Object} options
* @constructor
*/
function Table(tableName, fields, options) {
var i;
for (i = 0; i < fields.length; i += 1) {
var field = fields[i];
this[field.name] = field.value;
}
this.tableName = tableName;
this.fields = fields;
if (options) {
var optionKeys = Object.keys(options);
for (i = 0; i < optionKeys.length; i += 1) {
var k = optionKeys[i];
var v = options[k];
if (this[k] !== undefined) {
this[k] = v;
}
}
}
}
/**
* Encodes the table and returns an array of bytes
* @return {Array}
*/
Table.prototype.encode = function() {
return encode.TABLE(this);
};
/**
* Get the size of the table.
* @return {number}
*/
Table.prototype.sizeOf = function() {
return sizeOf.TABLE(this);
};
/**
* @private
*/
function ushortList(itemName, list, count) {
if (count === undefined) {
count = list.length;
}
var fields = new Array(list.length + 1);
fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
for (var i = 0; i < list.length; i++) {
fields[i + 1] = {name: itemName + i, type: 'USHORT', value: list[i]};
}
return fields;
}
/**
* @private
*/
function tableList(itemName, records, itemCallback) {
var count = records.length;
var fields = new Array(count + 1);
fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
for (var i = 0; i < count; i++) {
fields[i + 1] = {name: itemName + i, type: 'TABLE', value: itemCallback(records[i], i)};
}
return fields;
}
/**
* @private
*/
function recordList(itemName, records, itemCallback) {
var count = records.length;
var fields = [];
fields[0] = {name: itemName + 'Count', type: 'USHORT', value: count};
for (var i = 0; i < count; i++) {
fields = fields.concat(itemCallback(records[i], i));
}
return fields;
}
// Common Layout Tables
/**
* @exports opentype.Coverage
* @class
* @param {opentype.Table}
* @constructor
* @extends opentype.Table
*/
function Coverage(coverageTable) {
if (coverageTable.format === 1) {
Table.call(this, 'coverageTable',
[{name: 'coverageFormat', type: 'USHORT', value: 1}]
.concat(ushortList('glyph', coverageTable.glyphs))
);
} else {
check.assert(false, 'Can\'t create coverage table format 2 yet.');
}
}
Coverage.prototype = Object.create(Table.prototype);
Coverage.prototype.constructor = Coverage;
function ScriptList(scriptListTable) {
Table.call(this, 'scriptListTable',
recordList('scriptRecord', scriptListTable, function(scriptRecord, i) {
var script = scriptRecord.script;
var defaultLangSys = script.defaultLangSys;
check.assert(!!defaultLangSys, 'Unable to write GSUB: script ' + scriptRecord.tag + ' has no default language system.');
return [
{name: 'scriptTag' + i, type: 'TAG', value: scriptRecord.tag},
{name: 'script' + i, type: 'TABLE', value: new Table('scriptTable', [
{name: 'defaultLangSys', type: 'TABLE', value: new Table('defaultLangSys', [
{name: 'lookupOrder', type: 'USHORT', value: 0},
{name: 'reqFeatureIndex', type: 'USHORT', value: defaultLangSys.reqFeatureIndex}]
.concat(ushortList('featureIndex', defaultLangSys.featureIndexes)))}
].concat(recordList('langSys', script.langSysRecords, function(langSysRecord, i) {
var langSys = langSysRecord.langSys;
return [
{name: 'langSysTag' + i, type: 'TAG', value: langSysRecord.tag},
{name: 'langSys' + i, type: 'TABLE', value: new Table('langSys', [
{name: 'lookupOrder', type: 'USHORT', value: 0},
{name: 'reqFeatureIndex', type: 'USHORT', value: langSys.reqFeatureIndex}
].concat(ushortList('featureIndex', langSys.featureIndexes)))}
];
})))}
];
})
);
}
ScriptList.prototype = Object.create(Table.prototype);
ScriptList.prototype.constructor = ScriptList;
/**
* @exports opentype.FeatureList
* @class
* @param {opentype.Table}
* @constructor
* @extends opentype.Table
*/
function FeatureList(featureListTable) {
Table.call(this, 'featureListTable',
recordList('featureRecord', featureListTable, function(featureRecord, i) {
var feature = featureRecord.feature;
return [
{name: 'featureTag' + i, type: 'TAG', value: featureRecord.tag},
{name: 'feature' + i, type: 'TABLE', value: new Table('featureTable', [
{name: 'featureParams', type: 'USHORT', value: feature.featureParams},
].concat(ushortList('lookupListIndex', feature.lookupListIndexes)))}
];
})
);
}
FeatureList.prototype = Object.create(Table.prototype);
FeatureList.prototype.constructor = FeatureList;
/**
* @exports opentype.LookupList
* @class
* @param {opentype.Table}
* @param {Object}
* @constructor
* @extends opentype.Table
*/
function LookupList(lookupListTable, subtableMakers) {
Table.call(this, 'lookupListTable', tableList('lookup', lookupListTable, function(lookupTable) {
var subtableCallback = subtableMakers[lookupTable.lookupType];
check.assert(!!subtableCallback, 'Unable to write GSUB lookup type ' + lookupTable.lookupType + ' tables.');
return new Table('lookupTable', [
{name: 'lookupType', type: 'USHORT', value: lookupTable.lookupType},
{name: 'lookupFlag', type: 'USHORT', value: lookupTable.lookupFlag}
].concat(tableList('subtable', lookupTable.subtables, subtableCallback)));
}));
}
LookupList.prototype = Object.create(Table.prototype);
LookupList.prototype.constructor = LookupList;
// Record = same as Table, but inlined (a Table has an offset and its data is further in the stream)
// Don't use offsets inside Records (probable bug), only in Tables.
exports.Record = exports.Table = Table;
exports.Coverage = Coverage;
exports.ScriptList = ScriptList;
exports.FeatureList = FeatureList;
exports.LookupList = LookupList;
exports.ushortList = ushortList;
exports.tableList = tableList;
exports.recordList = recordList;
},{"./check":2,"./types":32}],14:[function(require,module,exports){
// The `CFF` table contains the glyph outlines in PostScript format.
// https://www.microsoft.com/typography/OTSPEC/cff.htm
// http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/cff.pdf
// http://download.microsoft.com/download/8/0/1/801a191c-029d-4af3-9642-555f6fe514ee/type2.pdf
'use strict';
var encoding = require('../encoding');
var glyphset = require('../glyphset');
var parse = require('../parse');
var path = require('../path');
var table = require('../table');
// Custom equals function that can also check lists.
function equals(a, b) {
if (a === b) {
return true;
} else if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i += 1) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
// Parse a `CFF` INDEX array.
// An index array consists of a list of offsets, then a list of objects at those offsets.
function parseCFFIndex(data, start, conversionFn) {
//var i, objectOffset, endOffset;
var offsets = [];
var objects = [];
var count = parse.getCard16(data, start);
var i;
var objectOffset;
var endOffset;
if (count !== 0) {
var offsetSize = parse.getByte(data, start + 2);
objectOffset = start + ((count + 1) * offsetSize) + 2;
var pos = start + 3;
for (i = 0; i < count + 1; i += 1) {
offsets.push(parse.getOffset(data, pos, offsetSize));
pos += offsetSize;
}
// The total size of the index array is 4 header bytes + the value of the last offset.
endOffset = objectOffset + offsets[count];
} else {
endOffset = start + 2;
}
for (i = 0; i < offsets.length - 1; i += 1) {
var value = parse.getBytes(data, objectOffset + offsets[i], objectOffset + offsets[i + 1]);
if (conversionFn) {
value = conversionFn(value);
}
objects.push(value);
}
return {objects: objects, startOffset: start, endOffset: endOffset};
}
// Parse a `CFF` DICT real value.
function parseFloatOperand(parser) {
var s = '';
var eof = 15;
var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'E', 'E-', null, '-'];
while (true) {
var b = parser.parseByte();
var n1 = b >> 4;
var n2 = b & 15;
if (n1 === eof) {
break;
}
s += lookup[n1];
if (n2 === eof) {
break;
}
s += lookup[n2];
}
return parseFloat(s);
}
// Parse a `CFF` DICT operand.
function parseOperand(parser, b0) {
var b1;
var b2;
var b3;
var b4;
if (b0 === 28) {
b1 = parser.parseByte();
b2 = parser.parseByte();
return b1 << 8 | b2;
}
if (b0 === 29) {
b1 = parser.parseByte();
b2 = parser.parseByte();
b3 = parser.parseByte();
b4 = parser.parseByte();
return b1 << 24 | b2 << 16 | b3 << 8 | b4;
}
if (b0 === 30) {
return parseFloatOperand(parser);
}
if (b0 >= 32 && b0 <= 246) {
return b0 - 139;
}
if (b0 >= 247 && b0 <= 250) {
b1 = parser.parseByte();
return (b0 - 247) * 256 + b1 + 108;
}
if (b0 >= 251 && b0 <= 254) {
b1 = parser.parseByte();
return -(b0 - 251) * 256 - b1 - 108;
}
throw new Error('Invalid b0 ' + b0);
}
// Convert the entries returned by `parseDict` to a proper dictionary.
// If a value is a list of one, it is unpacked.
function entriesToObject(entries) {
var o = {};
for (var i = 0; i < entries.length; i += 1) {
var key = entries[i][0];
var values = entries[i][1];
var value;
if (values.length === 1) {
value = values[0];
} else {
value = values;
}
if (o.hasOwnProperty(key)) {
throw new Error('Object ' + o + ' already has key ' + key);
}
o[key] = value;
}
return o;
}
// Parse a `CFF` DICT object.
// A dictionary contains key-value pairs in a compact tokenized format.
function parseCFFDict(data, start, size) {
start = start !== undefined ? start : 0;
var parser = new parse.Parser(data, start);
var entries = [];
var operands = [];
size = size !== undefined ? size : data.length;
while (parser.relativeOffset < size) {
var op = parser.parseByte();
// The first byte for each dict item distinguishes between operator (key) and operand (value).
// Values <= 21 are operators.
if (op <= 21) {
// Two-byte operators have an initial escape byte of 12.
if (op === 12) {
op = 1200 + parser.parseByte();
}
entries.push([op, operands]);
operands = [];
} else {
// Since the operands (values) come before the operators (keys), we store all operands in a list
// until we encounter an operator.
operands.push(parseOperand(parser, op));
}
}
return entriesToObject(entries);
}
// Given a String Index (SID), return the value of the string.
// Strings below index 392 are standard CFF strings and are not encoded in the font.
function getCFFString(strings, index) {
if (index <= 390) {
index = encoding.cffStandardStrings[index];
} else {
index = strings[index - 391];
}
return index;
}
// Interpret a dictionary and return a new dictionary with readable keys and values for missing entries.
// This function takes `meta` which is a list of objects containing `operand`, `name` and `default`.
function interpretDict(dict, meta, strings) {
var newDict = {};
// Because we also want to include missing values, we start out from the meta list
// and lookup values in the dict.
for (var i = 0; i < meta.length; i += 1) {
var m = meta[i];
var value = dict[m.op];
if (value === undefined) {
value = m.value !== undefined ? m.value : null;
}
if (m.type === 'SID') {
value = getCFFString(strings, value);
}
newDict[m.name] = value;
}
return newDict;
}
// Parse the CFF header.
function parseCFFHeader(data, start) {
var header = {};
header.formatMajor = parse.getCard8(data, start);
header.formatMinor = parse.getCard8(data, start + 1);
header.size = parse.getCard8(data, start + 2);
header.offsetSize = parse.getCard8(data, start + 3);
header.startOffset = start;
header.endOffset = start + 4;
return header;
}
var TOP_DICT_META = [
{name: 'version', op: 0, type: 'SID'},
{name: 'notice', op: 1, type: 'SID'},
{name: 'copyright', op: 1200, type: 'SID'},
{name: 'fullName', op: 2, type: 'SID'},
{name: 'familyName', op: 3, type: 'SID'},
{name: 'weight', op: 4, type: 'SID'},
{name: 'isFixedPitch', op: 1201, type: 'number', value: 0},
{name: 'italicAngle', op: 1202, type: 'number', value: 0},
{name: 'underlinePosition', op: 1203, type: 'number', value: -100},
{name: 'underlineThickness', op: 1204, type: 'number', value: 50},
{name: 'paintType', op: 1205, type: 'number', value: 0},
{name: 'charstringType', op: 1206, type: 'number', value: 2},
{name: 'fontMatrix', op: 1207, type: ['real', 'real', 'real', 'real', 'real', 'real'], value: [0.001, 0, 0, 0.001, 0, 0]},
{name: 'uniqueId', op: 13, type: 'number'},
{name: 'fontBBox', op: 5, type: ['number', 'number', 'number', 'number'], value: [0, 0, 0, 0]},
{name: 'strokeWidth', op: 1208, type: 'number', value: 0},
{name: 'xuid', op: 14, type: [], value: null},
{name: 'charset', op: 15, type: 'offset', value: 0},
{name: 'encoding', op: 16, type: 'offset', value: 0},
{name: 'charStrings', op: 17, type: 'offset', value: 0},
{name: 'private', op: 18, type: ['number', 'offset'], value: [0, 0]}
];
var PRIVATE_DICT_META = [
{name: 'subrs', op: 19, type: 'offset', value: 0},
{name: 'defaultWidthX', op: 20, type: 'number', value: 0},
{name: 'nominalWidthX', op: 21, type: 'number', value: 0}
];
// Parse the CFF top dictionary. A CFF table can contain multiple fonts, each with their own top dictionary.
// The top dictionary contains the essential metadata for the font, together with the private dictionary.
function parseCFFTopDict(data, strings) {
var dict = parseCFFDict(data, 0, data.byteLength);
return interpretDict(dict, TOP_DICT_META, strings);
}
// Parse the CFF private dictionary. We don't fully parse out all the values, only the ones we need.
function parseCFFPrivateDict(data, start, size, strings) {
var dict = parseCFFDict(data, start, size);
return interpretDict(dict, PRIVATE_DICT_META, strings);
}
// Parse the CFF charset table, which contains internal names for all the glyphs.
// This function will return a list of glyph names.
// See Adobe TN #5176 chapter 13, "Charsets".
function parseCFFCharset(data, start, nGlyphs, strings) {
var i;
var sid;
var count;
var parser = new parse.Parser(data, start);
// The .notdef glyph is not included, so subtract 1.
nGlyphs -= 1;
var charset = ['.notdef'];
var format = parser.parseCard8();
if (format === 0) {
for (i = 0; i < nGlyphs; i += 1) {
sid = parser.parseSID();
charset.push(getCFFString(strings, sid));
}
} else if (format === 1) {
while (charset.length <= nGlyphs) {
sid = parser.parseSID();
count = parser.parseCard8();
for (i = 0; i <= count; i += 1) {
charset.push(getCFFString(strings, sid));
sid += 1;
}
}
} else if (format === 2) {
while (charset.length <= nGlyphs) {
sid = parser.parseSID();
count = parser.parseCard16();
for (i = 0; i <= count; i += 1) {
charset.push(getCFFString(strings, sid));
sid += 1;
}
}
} else {
throw new Error('Unknown charset format ' + format);
}
return charset;
}
// Parse the CFF encoding data. Only one encoding can be specified per font.
// See Adobe TN #5176 chapter 12, "Encodings".
function parseCFFEncoding(data, start, charset) {
var i;
var code;
var enc = {};
var parser = new parse.Parser(data, start);
var format = parser.parseCard8();
if (format === 0) {
var nCodes = parser.parseCard8();
for (i = 0; i < nCodes; i += 1) {
code = parser.parseCard8();
enc[code] = i;
}
} else if (format === 1) {
var nRanges = parser.parseCard8();
code = 1;
for (i = 0; i < nRanges; i += 1) {
var first = parser.parseCard8();
var nLeft = parser.parseCard8();
for (var j = first; j <= first + nLeft; j += 1) {
enc[j] = code;
code += 1;
}
}
} else {
throw new Error('Unknown encoding format ' + format);
}
return new encoding.CffEncoding(enc, charset);
}
// Take in charstring code and return a Glyph object.
// The encoding is described in the Type 2 Charstring Format
// https://www.microsoft.com/typography/OTSPEC/charstr2.htm
function parseCFFCharstring(font, glyph, code) {
var c1x;
var c1y;
var c2x;
var c2y;
var p = new path.Path();
var stack = [];
var nStems = 0;
var haveWidth = false;
var width = font.defaultWidthX;
var open = false;
var x = 0;
var y = 0;
function newContour(x, y) {
if (open) {
p.closePath();
}
p.moveTo(x, y);
open = true;
}
function parseStems() {
var hasWidthArg;
// The number of stem operators on the stack is always even.
// If the value is uneven, that means a width is specified.
hasWidthArg = stack.length % 2 !== 0;
if (hasWidthArg && !haveWidth) {
width = stack.shift() + font.nominalWidthX;
}
nStems += stack.length >> 1;
stack.length = 0;
haveWidth = true;
}
function parse(code) {
var b1;
var b2;
var b3;
var b4;
var codeIndex;
var subrCode;
var jpx;
var jpy;
var c3x;
var c3y;
var c4x;
var c4y;
var i = 0;
while (i < code.length) {
var v = code[i];
i += 1;
switch (v) {
case 1: // hstem
parseStems();
break;
case 3: // vstem
parseStems();
break;
case 4: // vmoveto
if (stack.length > 1 && !haveWidth) {
width = stack.shift() + font.nominalWidthX;
haveWidth = true;
}
y += stack.pop();
newContour(x, y);
break;
case 5: // rlineto
while (stack.length > 0) {
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
}
break;
case 6: // hlineto
while (stack.length > 0) {
x += stack.shift();
p.lineTo(x, y);
if (stack.length === 0) {
break;
}
y += stack.shift();
p.lineTo(x, y);
}
break;
case 7: // vlineto
while (stack.length > 0) {
y += stack.shift();
p.lineTo(x, y);
if (stack.length === 0) {
break;
}
x += stack.shift();
p.lineTo(x, y);
}
break;
case 8: // rrcurveto
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 10: // callsubr
codeIndex = stack.pop() + font.subrsBias;
subrCode = font.subrs[codeIndex];
if (subrCode) {
parse(subrCode);
}
break;
case 11: // return
return;
case 12: // flex operators
v = code[i];
i += 1;
switch (v) {
case 35: // flex
// |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 dx6 dy6 fd flex (12 35) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y + stack.shift(); // dy3
c3x = jpx + stack.shift(); // dx4
c3y = jpy + stack.shift(); // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
x = c4x + stack.shift(); // dx6
y = c4y + stack.shift(); // dy6
stack.shift(); // flex depth
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 34: // hflex
// |- dx1 dx2 dy2 dx3 dx4 dx5 dx6 hflex (12 34) |-
c1x = x + stack.shift(); // dx1
c1y = y; // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y; // dy3
c3x = jpx + stack.shift(); // dx4
c3y = c2y; // dy4
c4x = c3x + stack.shift(); // dx5
c4y = y; // dy5
x = c4x + stack.shift(); // dx6
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 36: // hflex1
// |- dx1 dy1 dx2 dy2 dx3 dx4 dx5 dy5 dx6 hflex1 (12 36) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y; // dy3
c3x = jpx + stack.shift(); // dx4
c3y = c2y; // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
x = c4x + stack.shift(); // dx6
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
case 37: // flex1
// |- dx1 dy1 dx2 dy2 dx3 dy3 dx4 dy4 dx5 dy5 d6 flex1 (12 37) |-
c1x = x + stack.shift(); // dx1
c1y = y + stack.shift(); // dy1
c2x = c1x + stack.shift(); // dx2
c2y = c1y + stack.shift(); // dy2
jpx = c2x + stack.shift(); // dx3
jpy = c2y + stack.shift(); // dy3
c3x = jpx + stack.shift(); // dx4
c3y = jpy + stack.shift(); // dy4
c4x = c3x + stack.shift(); // dx5
c4y = c3y + stack.shift(); // dy5
if (Math.abs(c4x - x) > Math.abs(c4y - y)) {
x = c4x + stack.shift();
} else {
y = c4y + stack.shift();
}
p.curveTo(c1x, c1y, c2x, c2y, jpx, jpy);
p.curveTo(c3x, c3y, c4x, c4y, x, y);
break;
default:
console.log('Glyph ' + glyph.index + ': unknown operator ' + 1200 + v);
stack.length = 0;
}
break;
case 14: // endchar
if (stack.length > 0 && !haveWidth) {
width = stack.shift() + font.nominalWidthX;
haveWidth = true;
}
if (open) {
p.closePath();
open = false;
}
break;
case 18: // hstemhm
parseStems();
break;
case 19: // hintmask
case 20: // cntrmask
parseStems();
i += (nStems + 7) >> 3;
break;
case 21: // rmoveto
if (stack.length > 2 && !haveWidth) {
width = stack.shift() + font.nominalWidthX;
haveWidth = true;
}
y += stack.pop();
x += stack.pop();
newContour(x, y);
break;
case 22: // hmoveto
if (stack.length > 1 && !haveWidth) {
width = stack.shift() + font.nominalWidthX;
haveWidth = true;
}
x += stack.pop();
newContour(x, y);
break;
case 23: // vstemhm
parseStems();
break;
case 24: // rcurveline
while (stack.length > 2) {
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
break;
case 25: // rlinecurve
while (stack.length > 6) {
x += stack.shift();
y += stack.shift();
p.lineTo(x, y);
}
c1x = x + stack.shift();
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
break;
case 26: // vvcurveto
if (stack.length % 2) {
x += stack.shift();
}
while (stack.length > 0) {
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x;
y = c2y + stack.shift();
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 27: // hhcurveto
if (stack.length % 2) {
y += stack.shift();
}
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y;
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 28: // shortint
b1 = code[i];
b2 = code[i + 1];
stack.push(((b1 << 24) | (b2 << 16)) >> 16);
i += 2;
break;
case 29: // callgsubr
codeIndex = stack.pop() + font.gsubrsBias;
subrCode = font.gsubrs[codeIndex];
if (subrCode) {
parse(subrCode);
}
break;
case 30: // vhcurveto
while (stack.length > 0) {
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
if (stack.length === 0) {
break;
}
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
y = c2y + stack.shift();
x = c2x + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
case 31: // hvcurveto
while (stack.length > 0) {
c1x = x + stack.shift();
c1y = y;
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
y = c2y + stack.shift();
x = c2x + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
if (stack.length === 0) {
break;
}
c1x = x;
c1y = y + stack.shift();
c2x = c1x + stack.shift();
c2y = c1y + stack.shift();
x = c2x + stack.shift();
y = c2y + (stack.length === 1 ? stack.shift() : 0);
p.curveTo(c1x, c1y, c2x, c2y, x, y);
}
break;
default:
if (v < 32) {
console.log('Glyph ' + glyph.index + ': unknown operator ' + v);
} else if (v < 247) {
stack.push(v - 139);
} else if (v < 251) {
b1 = code[i];
i += 1;
stack.push((v - 247) * 256 + b1 + 108);
} else if (v < 255) {
b1 = code[i];
i += 1;
stack.push(-(v - 251) * 256 - b1 - 108);
} else {
b1 = code[i];
b2 = code[i + 1];
b3 = code[i + 2];
b4 = code[i + 3];
i += 4;
stack.push(((b1 << 24) | (b2 << 16) | (b3 << 8) | b4) / 65536);
}
}
}
}
parse(code);
glyph.advanceWidth = width;
return p;
}
// Subroutines are encoded using the negative half of the number space.
// See type 2 chapter 4.7 "Subroutine operators".
function calcCFFSubroutineBias(subrs) {
var bias;
if (subrs.length < 1240) {
bias = 107;
} else if (subrs.length < 33900) {
bias = 1131;
} else {
bias = 32768;
}
return bias;
}
// Parse the `CFF` table, which contains the glyph outlines in PostScript format.
function parseCFFTable(data, start, font) {
font.tables.cff = {};
var header = parseCFFHeader(data, start);
var nameIndex = parseCFFIndex(data, header.endOffset, parse.bytesToString);
var topDictIndex = parseCFFIndex(data, nameIndex.endOffset);
var stringIndex = parseCFFIndex(data, topDictIndex.endOffset, parse.bytesToString);
var globalSubrIndex = parseCFFIndex(data, stringIndex.endOffset);
font.gsubrs = globalSubrIndex.objects;
font.gsubrsBias = calcCFFSubroutineBias(font.gsubrs);
var topDictData = new DataView(new Uint8Array(topDictIndex.objects[0]).buffer);
var topDict = parseCFFTopDict(topDictData, stringIndex.objects);
font.tables.cff.topDict = topDict;
var privateDictOffset = start + topDict['private'][1];
var privateDict = parseCFFPrivateDict(data, privateDictOffset, topDict['private'][0], stringIndex.objects);
font.defaultWidthX = privateDict.defaultWidthX;
font.nominalWidthX = privateDict.nominalWidthX;
if (privateDict.subrs !== 0) {
var subrOffset = privateDictOffset + privateDict.subrs;
var subrIndex = parseCFFIndex(data, subrOffset);
font.subrs = subrIndex.objects;
font.subrsBias = calcCFFSubroutineBias(font.subrs);
} else {
font.subrs = [];
font.subrsBias = 0;
}
// Offsets in the top dict are relative to the beginning of the CFF data, so add the CFF start offset.
var charStringsIndex = parseCFFIndex(data, start + topDict.charStrings);
font.nGlyphs = charStringsIndex.objects.length;
var charset = parseCFFCharset(data, start + topDict.charset, font.nGlyphs, stringIndex.objects);
if (topDict.encoding === 0) { // Standard encoding
font.cffEncoding = new encoding.CffEncoding(encoding.cffStandardEncoding, charset);
} else if (topDict.encoding === 1) { // Expert encoding
font.cffEncoding = new encoding.CffEncoding(encoding.cffExpertEncoding, charset);
} else {
font.cffEncoding = parseCFFEncoding(data, start + topDict.encoding, charset);
}
// Prefer the CMAP encoding to the CFF encoding.
font.encoding = font.encoding || font.cffEncoding;
font.glyphs = new glyphset.GlyphSet(font);
for (var i = 0; i < font.nGlyphs; i += 1) {
var charString = charStringsIndex.objects[i];
font.glyphs.push(i, glyphset.cffGlyphLoader(font, i, parseCFFCharstring, charString));
}
}
// Convert a string to a String ID (SID).
// The list of strings is modified in place.
function encodeString(s, strings) {
var sid;
// Is the string in the CFF standard strings?
var i = encoding.cffStandardStrings.indexOf(s);
if (i >= 0) {
sid = i;
}
// Is the string already in the string index?
i = strings.indexOf(s);
if (i >= 0) {
sid = i + encoding.cffStandardStrings.length;
} else {
sid = encoding.cffStandardStrings.length + strings.length;
strings.push(s);
}
return sid;
}
function makeHeader() {
return new table.Record('Header', [
{name: 'major', type: 'Card8', value: 1},
{name: 'minor', type: 'Card8', value: 0},
{name: 'hdrSize', type: 'Card8', value: 4},
{name: 'major', type: 'Card8', value: 1}
]);
}
function makeNameIndex(fontNames) {
var t = new table.Record('Name INDEX', [
{name: 'names', type: 'INDEX', value: []}
]);
t.names = [];
for (var i = 0; i < fontNames.length; i += 1) {
t.names.push({name: 'name_' + i, type: 'NAME', value: fontNames[i]});
}
return t;
}
// Given a dictionary's metadata, create a DICT structure.
function makeDict(meta, attrs, strings) {
var m = {};
for (var i = 0; i < meta.length; i += 1) {
var entry = meta[i];
var value = attrs[entry.name];
if (value !== undefined && !equals(value, entry.value)) {
if (entry.type === 'SID') {
value = encodeString(value, strings);
}
m[entry.op] = {name: entry.name, type: entry.type, value: value};
}
}
return m;
}
// The Top DICT houses the global font attributes.
function makeTopDict(attrs, strings) {
var t = new table.Record('Top DICT', [
{name: 'dict', type: 'DICT', value: {}}
]);
t.dict = makeDict(TOP_DICT_META, attrs, strings);
return t;
}
function makeTopDictIndex(topDict) {
var t = new table.Record('Top DICT INDEX', [
{name: 'topDicts', type: 'INDEX', value: []}
]);
t.topDicts = [{name: 'topDict_0', type: 'TABLE', value: topDict}];
return t;
}
function makeStringIndex(strings) {
var t = new table.Record('String INDEX', [
{name: 'strings', type: 'INDEX', value: []}
]);
t.strings = [];
for (var i = 0; i < strings.length; i += 1) {
t.strings.push({name: 'string_' + i, type: 'STRING', value: strings[i]});
}
return t;
}
function makeGlobalSubrIndex() {
// Currently we don't use subroutines.
return new table.Record('Global Subr INDEX', [
{name: 'subrs', type: 'INDEX', value: []}
]);
}
function makeCharsets(glyphNames, strings) {
var t = new table.Record('Charsets', [
{name: 'format', type: 'Card8', value: 0}
]);
for (var i = 0; i < glyphNames.length; i += 1) {
var glyphName = glyphNames[i];
var glyphSID = encodeString(glyphName, strings);
t.fields.push({name: 'glyph_' + i, type: 'SID', value: glyphSID});
}
return t;
}
function glyphToOps(glyph) {
var ops = [];
var path = glyph.path;
ops.push({name: 'width', type: 'NUMBER', value: glyph.advanceWidth});
var x = 0;
var y = 0;
for (var i = 0; i < path.commands.length; i += 1) {
var dx;
var dy;
var cmd = path.commands[i];
if (cmd.type === 'Q') {
// CFF only supports bézier curves, so convert the quad to a bézier.
var _13 = 1 / 3;
var _23 = 2 / 3;
// We're going to create a new command so we don't change the original path.
cmd = {
type: 'C',
x: cmd.x,
y: cmd.y,
x1: _13 * x + _23 * cmd.x1,
y1: _13 * y + _23 * cmd.y1,
x2: _13 * cmd.x + _23 * cmd.x1,
y2: _13 * cmd.y + _23 * cmd.y1
};
}
if (cmd.type === 'M') {
dx = Math.round(cmd.x - x);
dy = Math.round(cmd.y - y);
ops.push({name: 'dx', type: 'NUMBER', value: dx});
ops.push({name: 'dy', type: 'NUMBER', value: dy});
ops.push({name: 'rmoveto', type: 'OP', value: 21});
x = Math.round(cmd.x);
y = Math.round(cmd.y);
} else if (cmd.type === 'L') {
dx = Math.round(cmd.x - x);
dy = Math.round(cmd.y - y);
ops.push({name: 'dx', type: 'NUMBER', value: dx});
ops.push({name: 'dy', type: 'NUMBER', value: dy});
ops.push({name: 'rlineto', type: 'OP', value: 5});
x = Math.round(cmd.x);
y = Math.round(cmd.y);
} else if (cmd.type === 'C') {
var dx1 = Math.round(cmd.x1 - x);
var dy1 = Math.round(cmd.y1 - y);
var dx2 = Math.round(cmd.x2 - cmd.x1);
var dy2 = Math.round(cmd.y2 - cmd.y1);
dx = Math.round(cmd.x - cmd.x2);
dy = Math.round(cmd.y - cmd.y2);
ops.push({name: 'dx1', type: 'NUMBER', value: dx1});
ops.push({name: 'dy1', type: 'NUMBER', value: dy1});
ops.push({name: 'dx2', type: 'NUMBER', value: dx2});
ops.push({name: 'dy2', type: 'NUMBER', value: dy2});
ops.push({name: 'dx', type: 'NUMBER', value: dx});
ops.push({name: 'dy', type: 'NUMBER', value: dy});
ops.push({name: 'rrcurveto', type: 'OP', value: 8});
x = Math.round(cmd.x);
y = Math.round(cmd.y);
}
// Contours are closed automatically.
}
ops.push({name: 'endchar', type: 'OP', value: 14});
return ops;
}
function makeCharStringsIndex(glyphs) {
var t = new table.Record('CharStrings INDEX', [
{name: 'charStrings', type: 'INDEX', value: []}
]);
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
var ops = glyphToOps(glyph);
t.charStrings.push({name: glyph.name, type: 'CHARSTRING', value: ops});
}
return t;
}
function makePrivateDict(attrs, strings) {
var t = new table.Record('Private DICT', [
{name: 'dict', type: 'DICT', value: {}}
]);
t.dict = makeDict(PRIVATE_DICT_META, attrs, strings);
return t;
}
function makeCFFTable(glyphs, options) {
var t = new table.Table('CFF ', [
{name: 'header', type: 'RECORD'},
{name: 'nameIndex', type: 'RECORD'},
{name: 'topDictIndex', type: 'RECORD'},
{name: 'stringIndex', type: 'RECORD'},
{name: 'globalSubrIndex', type: 'RECORD'},
{name: 'charsets', type: 'RECORD'},
{name: 'charStringsIndex', type: 'RECORD'},
{name: 'privateDict', type: 'RECORD'}
]);
var fontScale = 1 / options.unitsPerEm;
// We use non-zero values for the offsets so that the DICT encodes them.
// This is important because the size of the Top DICT plays a role in offset calculation,
// and the size shouldn't change after we've written correct offsets.
var attrs = {
version: options.version,
fullName: options.fullName,
familyName: options.familyName,
weight: options.weightName,
fontBBox: options.fontBBox || [0, 0, 0, 0],
fontMatrix: [fontScale, 0, 0, fontScale, 0, 0],
charset: 999,
encoding: 0,
charStrings: 999,
private: [0, 999]
};
var privateAttrs = {};
var glyphNames = [];
var glyph;
// Skip first glyph (.notdef)
for (var i = 1; i < glyphs.length; i += 1) {
glyph = glyphs.get(i);
glyphNames.push(glyph.name);
}
var strings = [];
t.header = makeHeader();
t.nameIndex = makeNameIndex([options.postScriptName]);
var topDict = makeTopDict(attrs, strings);
t.topDictIndex = makeTopDictIndex(topDict);
t.globalSubrIndex = makeGlobalSubrIndex();
t.charsets = makeCharsets(glyphNames, strings);
t.charStringsIndex = makeCharStringsIndex(glyphs);
t.privateDict = makePrivateDict(privateAttrs, strings);
// Needs to come at the end, to encode all custom strings used in the font.
t.stringIndex = makeStringIndex(strings);
var startOffset = t.header.sizeOf() +
t.nameIndex.sizeOf() +
t.topDictIndex.sizeOf() +
t.stringIndex.sizeOf() +
t.globalSubrIndex.sizeOf();
attrs.charset = startOffset;
// We use the CFF standard encoding; proper encoding will be handled in cmap.
attrs.encoding = 0;
attrs.charStrings = attrs.charset + t.charsets.sizeOf();
attrs.private[1] = attrs.charStrings + t.charStringsIndex.sizeOf();
// Recreate the Top DICT INDEX with the correct offsets.
topDict = makeTopDict(attrs, strings);
t.topDictIndex = makeTopDictIndex(topDict);
return t;
}
exports.parse = parseCFFTable;
exports.make = makeCFFTable;
},{"../encoding":4,"../glyphset":7,"../parse":10,"../path":11,"../table":13}],15:[function(require,module,exports){
// The `cmap` table stores the mappings from characters to glyphs.
// https://www.microsoft.com/typography/OTSPEC/cmap.htm
'use strict';
var check = require('../check');
var parse = require('../parse');
var table = require('../table');
function parseCmapTableFormat12(cmap, p) {
var i;
//Skip reserved.
p.parseUShort();
// Length in bytes of the sub-tables.
cmap.length = p.parseULong();
cmap.language = p.parseULong();
var groupCount;
cmap.groupCount = groupCount = p.parseULong();
cmap.glyphIndexMap = {};
for (i = 0; i < groupCount; i += 1) {
var startCharCode = p.parseULong();
var endCharCode = p.parseULong();
var startGlyphId = p.parseULong();
for (var c = startCharCode; c <= endCharCode; c += 1) {
cmap.glyphIndexMap[c] = startGlyphId;
startGlyphId++;
}
}
}
function parseCmapTableFormat4(cmap, p, data, start, offset) {
var i;
// Length in bytes of the sub-tables.
cmap.length = p.parseUShort();
cmap.language = p.parseUShort();
// segCount is stored x 2.
var segCount;
cmap.segCount = segCount = p.parseUShort() >> 1;
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
// The "unrolled" mapping from character codes to glyph indices.
cmap.glyphIndexMap = {};
var endCountParser = new parse.Parser(data, start + offset + 14);
var startCountParser = new parse.Parser(data, start + offset + 16 + segCount * 2);
var idDeltaParser = new parse.Parser(data, start + offset + 16 + segCount * 4);
var idRangeOffsetParser = new parse.Parser(data, start + offset + 16 + segCount * 6);
var glyphIndexOffset = start + offset + 16 + segCount * 8;
for (i = 0; i < segCount - 1; i += 1) {
var glyphIndex;
var endCount = endCountParser.parseUShort();
var startCount = startCountParser.parseUShort();
var idDelta = idDeltaParser.parseShort();
var idRangeOffset = idRangeOffsetParser.parseUShort();
for (var c = startCount; c <= endCount; c += 1) {
if (idRangeOffset !== 0) {
// The idRangeOffset is relative to the current position in the idRangeOffset array.
// Take the current offset in the idRangeOffset array.
glyphIndexOffset = (idRangeOffsetParser.offset + idRangeOffsetParser.relativeOffset - 2);
// Add the value of the idRangeOffset, which will move us into the glyphIndex array.
glyphIndexOffset += idRangeOffset;
// Then add the character index of the current segment, multiplied by 2 for USHORTs.
glyphIndexOffset += (c - startCount) * 2;
glyphIndex = parse.getUShort(data, glyphIndexOffset);
if (glyphIndex !== 0) {
glyphIndex = (glyphIndex + idDelta) & 0xFFFF;
}
} else {
glyphIndex = (c + idDelta) & 0xFFFF;
}
cmap.glyphIndexMap[c] = glyphIndex;
}
}
}
// Parse the `cmap` table. This table stores the mappings from characters to glyphs.
// There are many available formats, but we only support the Windows format 4 and 12.
// This function returns a `CmapEncoding` object or null if no supported format could be found.
function parseCmapTable(data, start) {
var i;
var cmap = {};
cmap.version = parse.getUShort(data, start);
check.argument(cmap.version === 0, 'cmap table version should be 0.');
// The cmap table can contain many sub-tables, each with their own format.
// We're only interested in a "platform 3" table. This is a Windows format.
cmap.numTables = parse.getUShort(data, start + 2);
var offset = -1;
for (i = cmap.numTables - 1; i >= 0; i -= 1) {
var platformId = parse.getUShort(data, start + 4 + (i * 8));
var encodingId = parse.getUShort(data, start + 4 + (i * 8) + 2);
if (platformId === 3 && (encodingId === 0 || encodingId === 1 || encodingId === 10)) {
offset = parse.getULong(data, start + 4 + (i * 8) + 4);
break;
}
}
if (offset === -1) {
// There is no cmap table in the font that we support, so return null.
// This font will be marked as unsupported.
return null;
}
var p = new parse.Parser(data, start + offset);
cmap.format = p.parseUShort();
if (cmap.format === 12) {
parseCmapTableFormat12(cmap, p);
} else if (cmap.format === 4) {
parseCmapTableFormat4(cmap, p, data, start, offset);
} else {
throw new Error('Only format 4 and 12 cmap tables are supported.');
}
return cmap;
}
function addSegment(t, code, glyphIndex) {
t.segments.push({
end: code,
start: code,
delta: -(code - glyphIndex),
offset: 0
});
}
function addTerminatorSegment(t) {
t.segments.push({
end: 0xFFFF,
start: 0xFFFF,
delta: 1,
offset: 0
});
}
function makeCmapTable(glyphs) {
var i;
var t = new table.Table('cmap', [
{name: 'version', type: 'USHORT', value: 0},
{name: 'numTables', type: 'USHORT', value: 1},
{name: 'platformID', type: 'USHORT', value: 3},
{name: 'encodingID', type: 'USHORT', value: 1},
{name: 'offset', type: 'ULONG', value: 12},
{name: 'format', type: 'USHORT', value: 4},
{name: 'length', type: 'USHORT', value: 0},
{name: 'language', type: 'USHORT', value: 0},
{name: 'segCountX2', type: 'USHORT', value: 0},
{name: 'searchRange', type: 'USHORT', value: 0},
{name: 'entrySelector', type: 'USHORT', value: 0},
{name: 'rangeShift', type: 'USHORT', value: 0}
]);
t.segments = [];
for (i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
for (var j = 0; j < glyph.unicodes.length; j += 1) {
addSegment(t, glyph.unicodes[j], i);
}
t.segments = t.segments.sort(function(a, b) {
return a.start - b.start;
});
}
addTerminatorSegment(t);
var segCount;
segCount = t.segments.length;
t.segCountX2 = segCount * 2;
t.searchRange = Math.pow(2, Math.floor(Math.log(segCount) / Math.log(2))) * 2;
t.entrySelector = Math.log(t.searchRange / 2) / Math.log(2);
t.rangeShift = t.segCountX2 - t.searchRange;
// Set up parallel segment arrays.
var endCounts = [];
var startCounts = [];
var idDeltas = [];
var idRangeOffsets = [];
var glyphIds = [];
for (i = 0; i < segCount; i += 1) {
var segment = t.segments[i];
endCounts = endCounts.concat({name: 'end_' + i, type: 'USHORT', value: segment.end});
startCounts = startCounts.concat({name: 'start_' + i, type: 'USHORT', value: segment.start});
idDeltas = idDeltas.concat({name: 'idDelta_' + i, type: 'SHORT', value: segment.delta});
idRangeOffsets = idRangeOffsets.concat({name: 'idRangeOffset_' + i, type: 'USHORT', value: segment.offset});
if (segment.glyphId !== undefined) {
glyphIds = glyphIds.concat({name: 'glyph_' + i, type: 'USHORT', value: segment.glyphId});
}
}
t.fields = t.fields.concat(endCounts);
t.fields.push({name: 'reservedPad', type: 'USHORT', value: 0});
t.fields = t.fields.concat(startCounts);
t.fields = t.fields.concat(idDeltas);
t.fields = t.fields.concat(idRangeOffsets);
t.fields = t.fields.concat(glyphIds);
t.length = 14 + // Subtable header
endCounts.length * 2 +
2 + // reservedPad
startCounts.length * 2 +
idDeltas.length * 2 +
idRangeOffsets.length * 2 +
glyphIds.length * 2;
return t;
}
exports.parse = parseCmapTable;
exports.make = makeCmapTable;
},{"../check":2,"../parse":10,"../table":13}],16:[function(require,module,exports){
// The `fvar` table stores font variation axes and instances.
// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html
'use strict';
var check = require('../check');
var parse = require('../parse');
var table = require('../table');
function addName(name, names) {
var nameString = JSON.stringify(name);
var nameID = 256;
for (var nameKey in names) {
var n = parseInt(nameKey);
if (!n || n < 256) {
continue;
}
if (JSON.stringify(names[nameKey]) === nameString) {
return n;
}
if (nameID <= n) {
nameID = n + 1;
}
}
names[nameID] = name;
return nameID;
}
function makeFvarAxis(n, axis, names) {
var nameID = addName(axis.name, names);
return [
{name: 'tag_' + n, type: 'TAG', value: axis.tag},
{name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16},
{name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16},
{name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16},
{name: 'flags_' + n, type: 'USHORT', value: 0},
{name: 'nameID_' + n, type: 'USHORT', value: nameID}
];
}
function parseFvarAxis(data, start, names) {
var axis = {};
var p = new parse.Parser(data, start);
axis.tag = p.parseTag();
axis.minValue = p.parseFixed();
axis.defaultValue = p.parseFixed();
axis.maxValue = p.parseFixed();
p.skip('uShort', 1); // reserved for flags; no values defined
axis.name = names[p.parseUShort()] || {};
return axis;
}
function makeFvarInstance(n, inst, axes, names) {
var nameID = addName(inst.name, names);
var fields = [
{name: 'nameID_' + n, type: 'USHORT', value: nameID},
{name: 'flags_' + n, type: 'USHORT', value: 0}
];
for (var i = 0; i < axes.length; ++i) {
var axisTag = axes[i].tag;
fields.push({
name: 'axis_' + n + ' ' + axisTag,
type: 'FIXED',
value: inst.coordinates[axisTag] << 16
});
}
return fields;
}
function parseFvarInstance(data, start, axes, names) {
var inst = {};
var p = new parse.Parser(data, start);
inst.name = names[p.parseUShort()] || {};
p.skip('uShort', 1); // reserved for flags; no values defined
inst.coordinates = {};
for (var i = 0; i < axes.length; ++i) {
inst.coordinates[axes[i].tag] = p.parseFixed();
}
return inst;
}
function makeFvarTable(fvar, names) {
var result = new table.Table('fvar', [
{name: 'version', type: 'ULONG', value: 0x10000},
{name: 'offsetToData', type: 'USHORT', value: 0},
{name: 'countSizePairs', type: 'USHORT', value: 2},
{name: 'axisCount', type: 'USHORT', value: fvar.axes.length},
{name: 'axisSize', type: 'USHORT', value: 20},
{name: 'instanceCount', type: 'USHORT', value: fvar.instances.length},
{name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4}
]);
result.offsetToData = result.sizeOf();
for (var i = 0; i < fvar.axes.length; i++) {
result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names));
}
for (var j = 0; j < fvar.instances.length; j++) {
result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names));
}
return result;
}
function parseFvarTable(data, start, names) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.');
var offsetToData = p.parseOffset16();
// Skip countSizePairs.
p.skip('uShort', 1);
var axisCount = p.parseUShort();
var axisSize = p.parseUShort();
var instanceCount = p.parseUShort();
var instanceSize = p.parseUShort();
var axes = [];
for (var i = 0; i < axisCount; i++) {
axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names));
}
var instances = [];
var instanceStart = start + offsetToData + axisCount * axisSize;
for (var j = 0; j < instanceCount; j++) {
instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names));
}
return {axes: axes, instances: instances};
}
exports.make = makeFvarTable;
exports.parse = parseFvarTable;
},{"../check":2,"../parse":10,"../table":13}],17:[function(require,module,exports){
// The `glyf` table describes the glyphs in TrueType outline format.
// http://www.microsoft.com/typography/otspec/glyf.htm
'use strict';
var check = require('../check');
var glyphset = require('../glyphset');
var parse = require('../parse');
var path = require('../path');
// Parse the coordinate data for a glyph.
function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) {
var v;
if ((flag & shortVectorBitMask) > 0) {
// The coordinate is 1 byte long.
v = p.parseByte();
// The `same` bit is re-used for short values to signify the sign of the value.
if ((flag & sameBitMask) === 0) {
v = -v;
}
v = previousValue + v;
} else {
// The coordinate is 2 bytes long.
// If the `same` bit is set, the coordinate is the same as the previous coordinate.
if ((flag & sameBitMask) > 0) {
v = previousValue;
} else {
// Parse the coordinate as a signed 16-bit delta value.
v = previousValue + p.parseShort();
}
}
return v;
}
// Parse a TrueType glyph.
function parseGlyph(glyph, data, start) {
var p = new parse.Parser(data, start);
glyph.numberOfContours = p.parseShort();
glyph._xMin = p.parseShort();
glyph._yMin = p.parseShort();
glyph._xMax = p.parseShort();
glyph._yMax = p.parseShort();
var flags;
var flag;
if (glyph.numberOfContours > 0) {
var i;
// This glyph is not a composite.
var endPointIndices = glyph.endPointIndices = [];
for (i = 0; i < glyph.numberOfContours; i += 1) {
endPointIndices.push(p.parseUShort());
}
glyph.instructionLength = p.parseUShort();
glyph.instructions = [];
for (i = 0; i < glyph.instructionLength; i += 1) {
glyph.instructions.push(p.parseByte());
}
var numberOfCoordinates = endPointIndices[endPointIndices.length - 1] + 1;
flags = [];
for (i = 0; i < numberOfCoordinates; i += 1) {
flag = p.parseByte();
flags.push(flag);
// If bit 3 is set, we repeat this flag n times, where n is the next byte.
if ((flag & 8) > 0) {
var repeatCount = p.parseByte();
for (var j = 0; j < repeatCount; j += 1) {
flags.push(flag);
i += 1;
}
}
}
check.argument(flags.length === numberOfCoordinates, 'Bad flags.');
if (endPointIndices.length > 0) {
var points = [];
var point;
// X/Y coordinates are relative to the previous point, except for the first point which is relative to 0,0.
if (numberOfCoordinates > 0) {
for (i = 0; i < numberOfCoordinates; i += 1) {
flag = flags[i];
point = {};
point.onCurve = !!(flag & 1);
point.lastPointOfContour = endPointIndices.indexOf(i) >= 0;
points.push(point);
}
var px = 0;
for (i = 0; i < numberOfCoordinates; i += 1) {
flag = flags[i];
point = points[i];
point.x = parseGlyphCoordinate(p, flag, px, 2, 16);
px = point.x;
}
var py = 0;
for (i = 0; i < numberOfCoordinates; i += 1) {
flag = flags[i];
point = points[i];
point.y = parseGlyphCoordinate(p, flag, py, 4, 32);
py = point.y;
}
}
glyph.points = points;
} else {
glyph.points = [];
}
} else if (glyph.numberOfContours === 0) {
glyph.points = [];
} else {
glyph.isComposite = true;
glyph.points = [];
glyph.components = [];
var moreComponents = true;
while (moreComponents) {
flags = p.parseUShort();
var component = {
glyphIndex: p.parseUShort(),
xScale: 1,
scale01: 0,
scale10: 0,
yScale: 1,
dx: 0,
dy: 0
};
if ((flags & 1) > 0) {
// The arguments are words
if ((flags & 2) > 0) {
// values are offset
component.dx = p.parseShort();
component.dy = p.parseShort();
} else {
// values are matched points
component.matchedPoints = [p.parseUShort(), p.parseUShort()];
}
} else {
// The arguments are bytes
if ((flags & 2) > 0) {
// values are offset
component.dx = p.parseChar();
component.dy = p.parseChar();
} else {
// values are matched points
component.matchedPoints = [p.parseByte(), p.parseByte()];
}
}
if ((flags & 8) > 0) {
// We have a scale
component.xScale = component.yScale = p.parseF2Dot14();
} else if ((flags & 64) > 0) {
// We have an X / Y scale
component.xScale = p.parseF2Dot14();
component.yScale = p.parseF2Dot14();
} else if ((flags & 128) > 0) {
// We have a 2x2 transformation
component.xScale = p.parseF2Dot14();
component.scale01 = p.parseF2Dot14();
component.scale10 = p.parseF2Dot14();
component.yScale = p.parseF2Dot14();
}
glyph.components.push(component);
moreComponents = !!(flags & 32);
}
}
}
// Transform an array of points and return a new array.
function transformPoints(points, transform) {
var newPoints = [];
for (var i = 0; i < points.length; i += 1) {
var pt = points[i];
var newPt = {
x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx,
y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy,
onCurve: pt.onCurve,
lastPointOfContour: pt.lastPointOfContour
};
newPoints.push(newPt);
}
return newPoints;
}
function getContours(points) {
var contours = [];
var currentContour = [];
for (var i = 0; i < points.length; i += 1) {
var pt = points[i];
currentContour.push(pt);
if (pt.lastPointOfContour) {
contours.push(currentContour);
currentContour = [];
}
}
check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
return contours;
}
// Convert the TrueType glyph outline to a Path.
function getPath(points) {
var p = new path.Path();
if (!points) {
return p;
}
var contours = getContours(points);
for (var i = 0; i < contours.length; i += 1) {
var contour = contours[i];
var firstPt = contour[0];
var lastPt = contour[contour.length - 1];
var curvePt;
var realFirstPoint;
if (firstPt.onCurve) {
curvePt = null;
// The first point will be consumed by the moveTo command,
// so skip it in the loop.
realFirstPoint = true;
} else {
if (lastPt.onCurve) {
// If the first point is off-curve and the last point is on-curve,
// start at the last point.
firstPt = lastPt;
} else {
// If both first and last points are off-curve, start at their middle.
firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 };
}
curvePt = firstPt;
// The first point is synthesized, so don't skip the real first point.
realFirstPoint = false;
}
p.moveTo(firstPt.x, firstPt.y);
for (var j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) {
var pt = contour[j];
var prevPt = j === 0 ? firstPt : contour[j - 1];
if (prevPt.onCurve && pt.onCurve) {
// This is a straight line.
p.lineTo(pt.x, pt.y);
} else if (prevPt.onCurve && !pt.onCurve) {
curvePt = pt;
} else if (!prevPt.onCurve && !pt.onCurve) {
var midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 };
p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y);
curvePt = pt;
} else if (!prevPt.onCurve && pt.onCurve) {
// Previous point off-curve, this point on-curve.
p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y);
curvePt = null;
} else {
throw new Error('Invalid state.');
}
}
if (firstPt !== lastPt) {
// Connect the last and first points
if (curvePt) {
p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y);
} else {
p.lineTo(firstPt.x, firstPt.y);
}
}
}
p.closePath();
return p;
}
function buildPath(glyphs, glyph) {
if (glyph.isComposite) {
for (var j = 0; j < glyph.components.length; j += 1) {
var component = glyph.components[j];
var componentGlyph = glyphs.get(component.glyphIndex);
// Force the ttfGlyphLoader to parse the glyph.
componentGlyph.getPath();
if (componentGlyph.points) {
var transformedPoints;
if (component.matchedPoints === undefined) {
// component positioned by offset
transformedPoints = transformPoints(componentGlyph.points, component);
} else {
// component positioned by matched points
if ((component.matchedPoints[0] > glyph.points.length - 1) ||
(component.matchedPoints[1] > componentGlyph.points.length - 1)) {
throw Error('Matched points out of range in ' + glyph.name);
}
var firstPt = glyph.points[component.matchedPoints[0]];
var secondPt = componentGlyph.points[component.matchedPoints[1]];
var transform = {
xScale: component.xScale, scale01: component.scale01,
scale10: component.scale10, yScale: component.yScale,
dx: 0, dy: 0
};
secondPt = transformPoints([secondPt], transform)[0];
transform.dx = firstPt.x - secondPt.x;
transform.dy = firstPt.y - secondPt.y;
transformedPoints = transformPoints(componentGlyph.points, transform);
}
glyph.points = glyph.points.concat(transformedPoints);
}
}
}
return getPath(glyph.points);
}
// Parse all the glyphs according to the offsets from the `loca` table.
function parseGlyfTable(data, start, loca, font) {
var glyphs = new glyphset.GlyphSet(font);
var i;
// The last element of the loca table is invalid.
for (i = 0; i < loca.length - 1; i += 1) {
var offset = loca[i];
var nextOffset = loca[i + 1];
if (offset !== nextOffset) {
glyphs.push(i, glyphset.ttfGlyphLoader(font, i, parseGlyph, data, start + offset, buildPath));
} else {
glyphs.push(i, glyphset.glyphLoader(font, i));
}
}
return glyphs;
}
exports.parse = parseGlyfTable;
},{"../check":2,"../glyphset":7,"../parse":10,"../path":11}],18:[function(require,module,exports){
// The `GPOS` table contains kerning pairs, among other things.
// https://www.microsoft.com/typography/OTSPEC/gpos.htm
'use strict';
var check = require('../check');
var parse = require('../parse');
// Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables.
// These lists are unused by now, this function is just the basis for a real parsing.
function parseTaggedListTable(data, start) {
var p = new parse.Parser(data, start);
var n = p.parseUShort();
var list = [];
for (var i = 0; i < n; i++) {
list[p.parseTag()] = { offset: p.parseUShort() };
}
return list;
}
// Parse a coverage table in a GSUB, GPOS or GDEF table.
// Format 1 is a simple list of glyph ids,
// Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea.
function parseCoverageTable(data, start) {
var p = new parse.Parser(data, start);
var format = p.parseUShort();
var count = p.parseUShort();
if (format === 1) {
return p.parseUShortList(count);
} else if (format === 2) {
var coverage = [];
for (; count--;) {
var begin = p.parseUShort();
var end = p.parseUShort();
var index = p.parseUShort();
for (var i = begin; i <= end; i++) {
coverage[index++] = i;
}
}
return coverage;
}
}
// Parse a Class Definition Table in a GSUB, GPOS or GDEF table.
// Returns a function that gets a class value from a glyph ID.
function parseClassDefTable(data, start) {
var p = new parse.Parser(data, start);
var format = p.parseUShort();
if (format === 1) {
// Format 1 specifies a range of consecutive glyph indices, one class per glyph ID.
var startGlyph = p.parseUShort();
var glyphCount = p.parseUShort();
var classes = p.parseUShortList(glyphCount);
return function(glyphID) {
return classes[glyphID - startGlyph] || 0;
};
} else if (format === 2) {
// Format 2 defines multiple groups of glyph indices that belong to the same class.
var rangeCount = p.parseUShort();
var startGlyphs = [];
var endGlyphs = [];
var classValues = [];
for (var i = 0; i < rangeCount; i++) {
startGlyphs[i] = p.parseUShort();
endGlyphs[i] = p.parseUShort();
classValues[i] = p.parseUShort();
}
return function(glyphID) {
var l = 0;
var r = startGlyphs.length - 1;
while (l < r) {
var c = (l + r + 1) >> 1;
if (glyphID < startGlyphs[c]) {
r = c - 1;
} else {
l = c;
}
}
if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) {
return classValues[l] || 0;
}
return 0;
};
}
}
// Parse a pair adjustment positioning subtable, format 1 or format 2
// The subtable is returned in the form of a lookup function.
function parsePairPosSubTable(data, start) {
var p = new parse.Parser(data, start);
// This part is common to format 1 and format 2 subtables
var format = p.parseUShort();
var coverageOffset = p.parseUShort();
var coverage = parseCoverageTable(data, start + coverageOffset);
// valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph
// Only valueFormat1=4 and valueFormat2=0 is supported.
var valueFormat1 = p.parseUShort();
var valueFormat2 = p.parseUShort();
var value1;
var value2;
if (valueFormat1 !== 4 || valueFormat2 !== 0) return;
var sharedPairSets = {};
if (format === 1) {
// Pair Positioning Adjustment: Format 1
var pairSetCount = p.parseUShort();
var pairSet = [];
// Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index
var pairSetOffsets = p.parseOffset16List(pairSetCount);
for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) {
var pairSetOffset = pairSetOffsets[firstGlyph];
var sharedPairSet = sharedPairSets[pairSetOffset];
if (!sharedPairSet) {
// Parse a pairset table in a pair adjustment subtable format 1
sharedPairSet = {};
p.relativeOffset = pairSetOffset;
var pairValueCount = p.parseUShort();
for (; pairValueCount--;) {
var secondGlyph = p.parseUShort();
if (valueFormat1) value1 = p.parseShort();
if (valueFormat2) value2 = p.parseShort();
// We only support valueFormat1 = 4 and valueFormat2 = 0,
// so value1 is the XAdvance and value2 is empty.
sharedPairSet[secondGlyph] = value1;
}
}
pairSet[coverage[firstGlyph]] = sharedPairSet;
}
return function(leftGlyph, rightGlyph) {
var pairs = pairSet[leftGlyph];
if (pairs) return pairs[rightGlyph];
};
} else if (format === 2) {
// Pair Positioning Adjustment: Format 2
var classDef1Offset = p.parseUShort();
var classDef2Offset = p.parseUShort();
var class1Count = p.parseUShort();
var class2Count = p.parseUShort();
var getClass1 = parseClassDefTable(data, start + classDef1Offset);
var getClass2 = parseClassDefTable(data, start + classDef2Offset);
// Parse kerning values by class pair.
var kerningMatrix = [];
for (var i = 0; i < class1Count; i++) {
var kerningRow = kerningMatrix[i] = [];
for (var j = 0; j < class2Count; j++) {
if (valueFormat1) value1 = p.parseShort();
if (valueFormat2) value2 = p.parseShort();
// We only support valueFormat1 = 4 and valueFormat2 = 0,
// so value1 is the XAdvance and value2 is empty.
kerningRow[j] = value1;
}
}
// Convert coverage list to a hash
var covered = {};
for (i = 0; i < coverage.length; i++) covered[coverage[i]] = 1;
// Get the kerning value for a specific glyph pair.
return function(leftGlyph, rightGlyph) {
if (!covered[leftGlyph]) return;
var class1 = getClass1(leftGlyph);
var class2 = getClass2(rightGlyph);
var kerningRow = kerningMatrix[class1];
if (kerningRow) {
return kerningRow[class2];
}
};
}
}
// Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables).
function parseLookupTable(data, start) {
var p = new parse.Parser(data, start);
var lookupType = p.parseUShort();
var lookupFlag = p.parseUShort();
var useMarkFilteringSet = lookupFlag & 0x10;
var subTableCount = p.parseUShort();
var subTableOffsets = p.parseOffset16List(subTableCount);
var table = {
lookupType: lookupType,
lookupFlag: lookupFlag,
markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1
};
// LookupType 2, Pair adjustment
if (lookupType === 2) {
var subtables = [];
for (var i = 0; i < subTableCount; i++) {
subtables.push(parsePairPosSubTable(data, start + subTableOffsets[i]));
}
// Return a function which finds the kerning values in the subtables.
table.getKerningValue = function(leftGlyph, rightGlyph) {
for (var i = subtables.length; i--;) {
var value = subtables[i](leftGlyph, rightGlyph);
if (value !== undefined) return value;
}
return 0;
};
}
return table;
}
// Parse the `GPOS` table which contains, among other things, kerning pairs.
// https://www.microsoft.com/typography/OTSPEC/gpos.htm
function parseGposTable(data, start, font) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseFixed();
check.argument(tableVersion === 1, 'Unsupported GPOS table version.');
// ScriptList and FeatureList - ignored for now
parseTaggedListTable(data, start + p.parseUShort());
// 'kern' is the feature we are looking for.
parseTaggedListTable(data, start + p.parseUShort());
// LookupList
var lookupListOffset = p.parseUShort();
p.relativeOffset = lookupListOffset;
var lookupCount = p.parseUShort();
var lookupTableOffsets = p.parseOffset16List(lookupCount);
var lookupListAbsoluteOffset = start + lookupListOffset;
for (var i = 0; i < lookupCount; i++) {
var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]);
if (table.lookupType === 2 && !font.getGposKerningValue) font.getGposKerningValue = table.getKerningValue;
}
}
exports.parse = parseGposTable;
},{"../check":2,"../parse":10}],19:[function(require,module,exports){
// The `GSUB` table contains ligatures, among other things.
// https://www.microsoft.com/typography/OTSPEC/gsub.htm
'use strict';
var check = require('../check');
var Parser = require('../parse').Parser;
var subtableParsers = new Array(9); // subtableParsers[0] is unused
var table = require('../table');
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#SS
subtableParsers[1] = function parseLookup1() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: 1,
coverage: this.parsePointer(Parser.coverage),
deltaGlyphId: this.parseUShort()
};
} else if (substFormat === 2) {
return {
substFormat: 2,
coverage: this.parsePointer(Parser.coverage),
substitute: this.parseOffset16List()
};
}
check.assert(false, '0x' + start.toString(16) + ': lookup type 1 format must be 1 or 2.');
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#MS
subtableParsers[2] = function parseLookup2() {
var substFormat = this.parseUShort();
check.argument(substFormat === 1, 'GSUB Multiple Substitution Subtable identifier-format must be 1');
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
sequences: this.parseListOfLists()
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#AS
subtableParsers[3] = function parseLookup3() {
var substFormat = this.parseUShort();
check.argument(substFormat === 1, 'GSUB Alternate Substitution Subtable identifier-format must be 1');
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
alternateSets: this.parseListOfLists()
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#LS
subtableParsers[4] = function parseLookup4() {
var substFormat = this.parseUShort();
check.argument(substFormat === 1, 'GSUB ligature table identifier-format must be 1');
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
ligatureSets: this.parseListOfLists(function() {
return {
ligGlyph: this.parseUShort(),
components: this.parseUShortList(this.parseUShort() - 1)
};
})
};
};
var lookupRecordDesc = {
sequenceIndex: Parser.uShort,
lookupListIndex: Parser.uShort
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CSF
subtableParsers[5] = function parseLookup5() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
ruleSets: this.parseListOfLists(function() {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
input: this.parseUShortList(glyphCount - 1),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
})
};
} else if (substFormat === 2) {
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
classDef: this.parsePointer(Parser.classDef),
classSets: this.parseListOfLists(function() {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
classes: this.parseUShortList(glyphCount - 1),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
})
};
} else if (substFormat === 3) {
var glyphCount = this.parseUShort();
var substCount = this.parseUShort();
return {
substFormat: substFormat,
coverages: this.parseList(glyphCount, Parser.pointer(Parser.coverage)),
lookupRecords: this.parseRecordList(substCount, lookupRecordDesc)
};
}
check.assert(false, '0x' + start.toString(16) + ': lookup type 5 format must be 1, 2 or 3.');
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#CC
subtableParsers[6] = function parseLookup6() {
var start = this.offset + this.relativeOffset;
var substFormat = this.parseUShort();
if (substFormat === 1) {
return {
substFormat: 1,
coverage: this.parsePointer(Parser.coverage),
chainRuleSets: this.parseListOfLists(function() {
return {
backtrack: this.parseUShortList(),
input: this.parseUShortList(this.parseShort() - 1),
lookahead: this.parseUShortList(),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
})
};
} else if (substFormat === 2) {
return {
substFormat: 2,
coverage: this.parsePointer(Parser.coverage),
backtrackClassDef: this.parsePointer(Parser.classDef),
inputClassDef: this.parsePointer(Parser.classDef),
lookaheadClassDef: this.parsePointer(Parser.classDef),
chainClassSet: this.parseListOfLists(function() {
return {
backtrack: this.parseUShortList(),
input: this.parseUShortList(this.parseShort() - 1),
lookahead: this.parseUShortList(),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
})
};
} else if (substFormat === 3) {
return {
substFormat: 3,
backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
inputCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookupRecords: this.parseRecordList(lookupRecordDesc)
};
}
check.assert(false, '0x' + start.toString(16) + ': lookup type 6 format must be 1, 2 or 3.');
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#ES
subtableParsers[7] = function parseLookup7() {
// Extension Substitution subtable
var substFormat = this.parseUShort();
check.argument(substFormat === 1, 'GSUB Extension Substitution subtable identifier-format must be 1');
var extensionLookupType = this.parseUShort();
var extensionParser = new Parser(this.data, this.offset + this.parseULong());
return {
substFormat: 1,
lookupType: extensionLookupType,
extension: subtableParsers[extensionLookupType].call(extensionParser)
};
};
// https://www.microsoft.com/typography/OTSPEC/GSUB.htm#RCCS
subtableParsers[8] = function parseLookup8() {
var substFormat = this.parseUShort();
check.argument(substFormat === 1, 'GSUB Reverse Chaining Contextual Single Substitution Subtable identifier-format must be 1');
return {
substFormat: substFormat,
coverage: this.parsePointer(Parser.coverage),
backtrackCoverage: this.parseList(Parser.pointer(Parser.coverage)),
lookaheadCoverage: this.parseList(Parser.pointer(Parser.coverage)),
substitutes: this.parseUShortList()
};
};
// https://www.microsoft.com/typography/OTSPEC/gsub.htm
function parseGsubTable(data, start) {
start = start || 0;
var p = new Parser(data, start);
var tableVersion = p.parseVersion();
check.argument(tableVersion === 1, 'Unsupported GSUB table version.');
return {
version: tableVersion,
scripts: p.parseScriptList(),
features: p.parseFeatureList(),
lookups: p.parseLookupList(subtableParsers)
};
}
// GSUB Writing //////////////////////////////////////////////
var subtableMakers = new Array(9);
subtableMakers[1] = function makeLookup1(subtable) {
if (subtable.substFormat === 1) {
return new table.Table('substitutionTable', [
{name: 'substFormat', type: 'USHORT', value: 1},
{name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)},
{name: 'deltaGlyphID', type: 'USHORT', value: subtable.deltaGlyphId}
]);
} else {
return new table.Table('substitutionTable', [
{name: 'substFormat', type: 'USHORT', value: 2},
{name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
].concat(table.ushortList('substitute', subtable.substitute)));
}
check.fail('Lookup type 1 substFormat must be 1 or 2.');
};
subtableMakers[3] = function makeLookup3(subtable) {
check.assert(subtable.substFormat === 1, 'Lookup type 3 substFormat must be 1.');
return new table.Table('substitutionTable', [
{name: 'substFormat', type: 'USHORT', value: 1},
{name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
].concat(table.tableList('altSet', subtable.alternateSets, function(alternateSet) {
return new table.Table('alternateSetTable', table.ushortList('alternate', alternateSet));
})));
};
subtableMakers[4] = function makeLookup4(subtable) {
check.assert(subtable.substFormat === 1, 'Lookup type 4 substFormat must be 1.');
return new table.Table('substitutionTable', [
{name: 'substFormat', type: 'USHORT', value: 1},
{name: 'coverage', type: 'TABLE', value: new table.Coverage(subtable.coverage)}
].concat(table.tableList('ligSet', subtable.ligatureSets, function(ligatureSet) {
return new table.Table('ligatureSetTable', table.tableList('ligature', ligatureSet, function(ligature) {
return new table.Table('ligatureTable',
[{name: 'ligGlyph', type: 'USHORT', value: ligature.ligGlyph}]
.concat(table.ushortList('component', ligature.components, ligature.components.length + 1))
);
}));
})));
};
function makeGsubTable(gsub) {
return new table.Table('GSUB', [
{name: 'version', type: 'ULONG', value: 0x10000},
{name: 'scripts', type: 'TABLE', value: new table.ScriptList(gsub.scripts)},
{name: 'features', type: 'TABLE', value: new table.FeatureList(gsub.features)},
{name: 'lookups', type: 'TABLE', value: new table.LookupList(gsub.lookups, subtableMakers)}
]);
}
exports.parse = parseGsubTable;
exports.make = makeGsubTable;
},{"../check":2,"../parse":10,"../table":13}],20:[function(require,module,exports){
// The `head` table contains global information about the font.
// https://www.microsoft.com/typography/OTSPEC/head.htm
'use strict';
var check = require('../check');
var parse = require('../parse');
var table = require('../table');
// Parse the header `head` table
function parseHeadTable(data, start) {
var head = {};
var p = new parse.Parser(data, start);
head.version = p.parseVersion();
head.fontRevision = Math.round(p.parseFixed() * 1000) / 1000;
head.checkSumAdjustment = p.parseULong();
head.magicNumber = p.parseULong();
check.argument(head.magicNumber === 0x5F0F3CF5, 'Font header has wrong magic number.');
head.flags = p.parseUShort();
head.unitsPerEm = p.parseUShort();
head.created = p.parseLongDateTime();
head.modified = p.parseLongDateTime();
head.xMin = p.parseShort();
head.yMin = p.parseShort();
head.xMax = p.parseShort();
head.yMax = p.parseShort();
head.macStyle = p.parseUShort();
head.lowestRecPPEM = p.parseUShort();
head.fontDirectionHint = p.parseShort();
head.indexToLocFormat = p.parseShort();
head.glyphDataFormat = p.parseShort();
return head;
}
function makeHeadTable(options) {
// Apple Mac timestamp epoch is 01/01/1904 not 01/01/1970
var timestamp = Math.round(new Date().getTime() / 1000) + 2082844800;
var createdTimestamp = timestamp;
if (options.createdTimestamp) {
createdTimestamp = options.createdTimestamp + 2082844800;
}
return new table.Table('head', [
{name: 'version', type: 'FIXED', value: 0x00010000},
{name: 'fontRevision', type: 'FIXED', value: 0x00010000},
{name: 'checkSumAdjustment', type: 'ULONG', value: 0},
{name: 'magicNumber', type: 'ULONG', value: 0x5F0F3CF5},
{name: 'flags', type: 'USHORT', value: 0},
{name: 'unitsPerEm', type: 'USHORT', value: 1000},
{name: 'created', type: 'LONGDATETIME', value: createdTimestamp},
{name: 'modified', type: 'LONGDATETIME', value: timestamp},
{name: 'xMin', type: 'SHORT', value: 0},
{name: 'yMin', type: 'SHORT', value: 0},
{name: 'xMax', type: 'SHORT', value: 0},
{name: 'yMax', type: 'SHORT', value: 0},
{name: 'macStyle', type: 'USHORT', value: 0},
{name: 'lowestRecPPEM', type: 'USHORT', value: 0},
{name: 'fontDirectionHint', type: 'SHORT', value: 2},
{name: 'indexToLocFormat', type: 'SHORT', value: 0},
{name: 'glyphDataFormat', type: 'SHORT', value: 0}
], options);
}
exports.parse = parseHeadTable;
exports.make = makeHeadTable;
},{"../check":2,"../parse":10,"../table":13}],21:[function(require,module,exports){
// The `hhea` table contains information for horizontal layout.
// https://www.microsoft.com/typography/OTSPEC/hhea.htm
'use strict';
var parse = require('../parse');
var table = require('../table');
// Parse the horizontal header `hhea` table
function parseHheaTable(data, start) {
var hhea = {};
var p = new parse.Parser(data, start);
hhea.version = p.parseVersion();
hhea.ascender = p.parseShort();
hhea.descender = p.parseShort();
hhea.lineGap = p.parseShort();
hhea.advanceWidthMax = p.parseUShort();
hhea.minLeftSideBearing = p.parseShort();
hhea.minRightSideBearing = p.parseShort();
hhea.xMaxExtent = p.parseShort();
hhea.caretSlopeRise = p.parseShort();
hhea.caretSlopeRun = p.parseShort();
hhea.caretOffset = p.parseShort();
p.relativeOffset += 8;
hhea.metricDataFormat = p.parseShort();
hhea.numberOfHMetrics = p.parseUShort();
return hhea;
}
function makeHheaTable(options) {
return new table.Table('hhea', [
{name: 'version', type: 'FIXED', value: 0x00010000},
{name: 'ascender', type: 'FWORD', value: 0},
{name: 'descender', type: 'FWORD', value: 0},
{name: 'lineGap', type: 'FWORD', value: 0},
{name: 'advanceWidthMax', type: 'UFWORD', value: 0},
{name: 'minLeftSideBearing', type: 'FWORD', value: 0},
{name: 'minRightSideBearing', type: 'FWORD', value: 0},
{name: 'xMaxExtent', type: 'FWORD', value: 0},
{name: 'caretSlopeRise', type: 'SHORT', value: 1},
{name: 'caretSlopeRun', type: 'SHORT', value: 0},
{name: 'caretOffset', type: 'SHORT', value: 0},
{name: 'reserved1', type: 'SHORT', value: 0},
{name: 'reserved2', type: 'SHORT', value: 0},
{name: 'reserved3', type: 'SHORT', value: 0},
{name: 'reserved4', type: 'SHORT', value: 0},
{name: 'metricDataFormat', type: 'SHORT', value: 0},
{name: 'numberOfHMetrics', type: 'USHORT', value: 0}
], options);
}
exports.parse = parseHheaTable;
exports.make = makeHheaTable;
},{"../parse":10,"../table":13}],22:[function(require,module,exports){
// The `hmtx` table contains the horizontal metrics for all glyphs.
// https://www.microsoft.com/typography/OTSPEC/hmtx.htm
'use strict';
var parse = require('../parse');
var table = require('../table');
// Parse the `hmtx` table, which contains the horizontal metrics for all glyphs.
// This function augments the glyph array, adding the advanceWidth and leftSideBearing to each glyph.
function parseHmtxTable(data, start, numMetrics, numGlyphs, glyphs) {
var advanceWidth;
var leftSideBearing;
var p = new parse.Parser(data, start);
for (var i = 0; i < numGlyphs; i += 1) {
// If the font is monospaced, only one entry is needed. This last entry applies to all subsequent glyphs.
if (i < numMetrics) {
advanceWidth = p.parseUShort();
leftSideBearing = p.parseShort();
}
var glyph = glyphs.get(i);
glyph.advanceWidth = advanceWidth;
glyph.leftSideBearing = leftSideBearing;
}
}
function makeHmtxTable(glyphs) {
var t = new table.Table('hmtx', []);
for (var i = 0; i < glyphs.length; i += 1) {
var glyph = glyphs.get(i);
var advanceWidth = glyph.advanceWidth || 0;
var leftSideBearing = glyph.leftSideBearing || 0;
t.fields.push({name: 'advanceWidth_' + i, type: 'USHORT', value: advanceWidth});
t.fields.push({name: 'leftSideBearing_' + i, type: 'SHORT', value: leftSideBearing});
}
return t;
}
exports.parse = parseHmtxTable;
exports.make = makeHmtxTable;
},{"../parse":10,"../table":13}],23:[function(require,module,exports){
// The `kern` table contains kerning pairs.
// Note that some fonts use the GPOS OpenType layout table to specify kerning.
// https://www.microsoft.com/typography/OTSPEC/kern.htm
'use strict';
var check = require('../check');
var parse = require('../parse');
function parseWindowsKernTable(p) {
var pairs = {};
// Skip nTables.
p.skip('uShort');
var subtableVersion = p.parseUShort();
check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.');
// Skip subtableLength, subtableCoverage
p.skip('uShort', 2);
var nPairs = p.parseUShort();
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
for (var i = 0; i < nPairs; i += 1) {
var leftIndex = p.parseUShort();
var rightIndex = p.parseUShort();
var value = p.parseShort();
pairs[leftIndex + ',' + rightIndex] = value;
}
return pairs;
}
function parseMacKernTable(p) {
var pairs = {};
// The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits.
// Skip the rest.
p.skip('uShort');
var nTables = p.parseULong();
//check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').');
if (nTables > 1) {
console.warn('Only the first kern subtable is supported.');
}
p.skip('uLong');
var coverage = p.parseUShort();
var subtableVersion = coverage & 0xFF;
p.skip('uShort');
if (subtableVersion === 0) {
var nPairs = p.parseUShort();
// Skip searchRange, entrySelector, rangeShift.
p.skip('uShort', 3);
for (var i = 0; i < nPairs; i += 1) {
var leftIndex = p.parseUShort();
var rightIndex = p.parseUShort();
var value = p.parseShort();
pairs[leftIndex + ',' + rightIndex] = value;
}
}
return pairs;
}
// Parse the `kern` table which contains kerning pairs.
function parseKernTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseUShort();
if (tableVersion === 0) {
return parseWindowsKernTable(p);
} else if (tableVersion === 1) {
return parseMacKernTable(p);
} else {
throw new Error('Unsupported kern table version (' + tableVersion + ').');
}
}
exports.parse = parseKernTable;
},{"../check":2,"../parse":10}],24:[function(require,module,exports){
// The `loca` table stores the offsets to the locations of the glyphs in the font.
// https://www.microsoft.com/typography/OTSPEC/loca.htm
'use strict';
var parse = require('../parse');
// Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font,
// relative to the beginning of the glyphData table.
// The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs)
// The loca table has two versions: a short version where offsets are stored as uShorts, and a long
// version where offsets are stored as uLongs. The `head` table specifies which version to use
// (under indexToLocFormat).
function parseLocaTable(data, start, numGlyphs, shortVersion) {
var p = new parse.Parser(data, start);
var parseFn = shortVersion ? p.parseUShort : p.parseULong;
// There is an extra entry after the last index element to compute the length of the last glyph.
// That's why we use numGlyphs + 1.
var glyphOffsets = [];
for (var i = 0; i < numGlyphs + 1; i += 1) {
var glyphOffset = parseFn.call(p);
if (shortVersion) {
// The short table version stores the actual offset divided by 2.
glyphOffset *= 2;
}
glyphOffsets.push(glyphOffset);
}
return glyphOffsets;
}
exports.parse = parseLocaTable;
},{"../parse":10}],25:[function(require,module,exports){
// The `ltag` table stores IETF BCP-47 language tags. It allows supporting
// languages for which TrueType does not assign a numeric code.
// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html
// http://www.w3.org/International/articles/language-tags/
// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
'use strict';
var check = require('../check');
var parse = require('../parse');
var table = require('../table');
function makeLtagTable(tags) {
var result = new table.Table('ltag', [
{name: 'version', type: 'ULONG', value: 1},
{name: 'flags', type: 'ULONG', value: 0},
{name: 'numTags', type: 'ULONG', value: tags.length}
]);
var stringPool = '';
var stringPoolOffset = 12 + tags.length * 4;
for (var i = 0; i < tags.length; ++i) {
var pos = stringPool.indexOf(tags[i]);
if (pos < 0) {
pos = stringPool.length;
stringPool += tags[i];
}
result.fields.push({name: 'offset ' + i, type: 'USHORT', value: stringPoolOffset + pos});
result.fields.push({name: 'length ' + i, type: 'USHORT', value: tags[i].length});
}
result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
return result;
}
function parseLtagTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(tableVersion === 1, 'Unsupported ltag table version.');
// The 'ltag' specification does not define any flags; skip the field.
p.skip('uLong', 1);
var numTags = p.parseULong();
var tags = [];
for (var i = 0; i < numTags; i++) {
var tag = '';
var offset = start + p.parseUShort();
var length = p.parseUShort();
for (var j = offset; j < offset + length; ++j) {
tag += String.fromCharCode(data.getInt8(j));
}
tags.push(tag);
}
return tags;
}
exports.make = makeLtagTable;
exports.parse = parseLtagTable;
},{"../check":2,"../parse":10,"../table":13}],26:[function(require,module,exports){
// The `maxp` table establishes the memory requirements for the font.
// We need it just to get the number of glyphs in the font.
// https://www.microsoft.com/typography/OTSPEC/maxp.htm
'use strict';
var parse = require('../parse');
var table = require('../table');
// Parse the maximum profile `maxp` table.
function parseMaxpTable(data, start) {
var maxp = {};
var p = new parse.Parser(data, start);
maxp.version = p.parseVersion();
maxp.numGlyphs = p.parseUShort();
if (maxp.version === 1.0) {
maxp.maxPoints = p.parseUShort();
maxp.maxContours = p.parseUShort();
maxp.maxCompositePoints = p.parseUShort();
maxp.maxCompositeContours = p.parseUShort();
maxp.maxZones = p.parseUShort();
maxp.maxTwilightPoints = p.parseUShort();
maxp.maxStorage = p.parseUShort();
maxp.maxFunctionDefs = p.parseUShort();
maxp.maxInstructionDefs = p.parseUShort();
maxp.maxStackElements = p.parseUShort();
maxp.maxSizeOfInstructions = p.parseUShort();
maxp.maxComponentElements = p.parseUShort();
maxp.maxComponentDepth = p.parseUShort();
}
return maxp;
}
function makeMaxpTable(numGlyphs) {
return new table.Table('maxp', [
{name: 'version', type: 'FIXED', value: 0x00005000},
{name: 'numGlyphs', type: 'USHORT', value: numGlyphs}
]);
}
exports.parse = parseMaxpTable;
exports.make = makeMaxpTable;
},{"../parse":10,"../table":13}],27:[function(require,module,exports){
// The `GPOS` table contains kerning pairs, among other things.
// https://www.microsoft.com/typography/OTSPEC/gpos.htm
'use strict';
var types = require('../types');
var decode = types.decode;
var check = require('../check');
var parse = require('../parse');
var table = require('../table');
// Parse the metadata `meta` table.
// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6meta.html
function parseMetaTable(data, start) {
var p = new parse.Parser(data, start);
var tableVersion = p.parseULong();
check.argument(tableVersion === 1, 'Unsupported META table version.');
p.parseULong(); // flags - currently unused and set to 0
p.parseULong(); // tableOffset
var numDataMaps = p.parseULong();
var tags = {};
for (var i = 0; i < numDataMaps; i++) {
var tag = p.parseTag();
var dataOffset = p.parseULong();
var dataLength = p.parseULong();
var text = decode.UTF8(data, start + dataOffset, dataLength);
tags[tag] = text;
}
return tags;
}
function makeMetaTable(tags) {
var numTags = Object.keys(tags).length;
var stringPool = '';
var stringPoolOffset = 16 + numTags * 12;
var result = new table.Table('meta', [
{name: 'version', type: 'ULONG', value: 1},
{name: 'flags', type: 'ULONG', value: 0},
{name: 'offset', type: 'ULONG', value: stringPoolOffset},
{name: 'numTags', type: 'ULONG', value: numTags}
]);
for (var tag in tags) {
var pos = stringPool.length;
stringPool += tags[tag];
result.fields.push({name: 'tag ' + tag, type: 'TAG', value: tag});
result.fields.push({name: 'offset ' + tag, type: 'ULONG', value: stringPoolOffset + pos});
result.fields.push({name: 'length ' + tag, type: 'ULONG', value: tags[tag].length});
}
result.fields.push({name: 'stringPool', type: 'CHARARRAY', value: stringPool});
return result;
}
exports.parse = parseMetaTable;
exports.make = makeMetaTable;
},{"../check":2,"../parse":10,"../table":13,"../types":32}],28:[function(require,module,exports){
// The `name` naming table.
// https://www.microsoft.com/typography/OTSPEC/name.htm
'use strict';
var types = require('../types');
var decode = types.decode;
var encode = types.encode;
var parse = require('../parse');
var table = require('../table');
// NameIDs for the name table.
var nameTableNames = [
'copyright', // 0
'fontFamily', // 1
'fontSubfamily', // 2
'uniqueID', // 3
'fullName', // 4
'version', // 5
'postScriptName', // 6
'trademark', // 7
'manufacturer', // 8
'designer', // 9
'description', // 10
'manufacturerURL', // 11
'designerURL', // 12
'license', // 13
'licenseURL', // 14
'reserved', // 15
'preferredFamily', // 16
'preferredSubfamily', // 17
'compatibleFullName', // 18
'sampleText', // 19
'postScriptFindFontName', // 20
'wwsFamily', // 21
'wwsSubfamily' // 22
];
var macLanguages = {
0: 'en',
1: 'fr',
2: 'de',
3: 'it',
4: 'nl',
5: 'sv',
6: 'es',
7: 'da',
8: 'pt',
9: 'no',
10: 'he',
11: 'ja',
12: 'ar',
13: 'fi',
14: 'el',
15: 'is',
16: 'mt',
17: 'tr',
18: 'hr',
19: 'zh-Hant',
20: 'ur',
21: 'hi',
22: 'th',
23: 'ko',
24: 'lt',
25: 'pl',
26: 'hu',
27: 'es',
28: 'lv',
29: 'se',
30: 'fo',
31: 'fa',
32: 'ru',
33: 'zh',
34: 'nl-BE',
35: 'ga',
36: 'sq',
37: 'ro',
38: 'cz',
39: 'sk',
40: 'si',
41: 'yi',
42: 'sr',
43: 'mk',
44: 'bg',
45: 'uk',
46: 'be',
47: 'uz',
48: 'kk',
49: 'az-Cyrl',
50: 'az-Arab',
51: 'hy',
52: 'ka',
53: 'mo',
54: 'ky',
55: 'tg',
56: 'tk',
57: 'mn-CN',
58: 'mn',
59: 'ps',
60: 'ks',
61: 'ku',
62: 'sd',
63: 'bo',
64: 'ne',
65: 'sa',
66: 'mr',
67: 'bn',
68: 'as',
69: 'gu',
70: 'pa',
71: 'or',
72: 'ml',
73: 'kn',
74: 'ta',
75: 'te',
76: 'si',
77: 'my',
78: 'km',
79: 'lo',
80: 'vi',
81: 'id',
82: 'tl',
83: 'ms',
84: 'ms-Arab',
85: 'am',
86: 'ti',
87: 'om',
88: 'so',
89: 'sw',
90: 'rw',
91: 'rn',
92: 'ny',
93: 'mg',
94: 'eo',
128: 'cy',
129: 'eu',
130: 'ca',
131: 'la',
132: 'qu',
133: 'gn',
134: 'ay',
135: 'tt',
136: 'ug',
137: 'dz',
138: 'jv',
139: 'su',
140: 'gl',
141: 'af',
142: 'br',
143: 'iu',
144: 'gd',
145: 'gv',
146: 'ga',
147: 'to',
148: 'el-polyton',
149: 'kl',
150: 'az',
151: 'nn'
};
// MacOS language ID → MacOS script ID
//
// Note that the script ID is not sufficient to determine what encoding
// to use in TrueType files. For some languages, MacOS used a modification
// of a mainstream script. For example, an Icelandic name would be stored
// with smRoman in the TrueType naming table, but the actual encoding
// is a special Icelandic version of the normal Macintosh Roman encoding.
// As another example, Inuktitut uses an 8-bit encoding for Canadian Aboriginal
// Syllables but MacOS had run out of available script codes, so this was
// done as a (pretty radical) "modification" of Ethiopic.
//
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
var macLanguageToScript = {
0: 0, // langEnglish → smRoman
1: 0, // langFrench → smRoman
2: 0, // langGerman → smRoman
3: 0, // langItalian → smRoman
4: 0, // langDutch → smRoman
5: 0, // langSwedish → smRoman
6: 0, // langSpanish → smRoman
7: 0, // langDanish → smRoman
8: 0, // langPortuguese → smRoman
9: 0, // langNorwegian → smRoman
10: 5, // langHebrew → smHebrew
11: 1, // langJapanese → smJapanese
12: 4, // langArabic → smArabic
13: 0, // langFinnish → smRoman
14: 6, // langGreek → smGreek
15: 0, // langIcelandic → smRoman (modified)
16: 0, // langMaltese → smRoman
17: 0, // langTurkish → smRoman (modified)
18: 0, // langCroatian → smRoman (modified)
19: 2, // langTradChinese → smTradChinese
20: 4, // langUrdu → smArabic
21: 9, // langHindi → smDevanagari
22: 21, // langThai → smThai
23: 3, // langKorean → smKorean
24: 29, // langLithuanian → smCentralEuroRoman
25: 29, // langPolish → smCentralEuroRoman
26: 29, // langHungarian → smCentralEuroRoman
27: 29, // langEstonian → smCentralEuroRoman
28: 29, // langLatvian → smCentralEuroRoman
29: 0, // langSami → smRoman
30: 0, // langFaroese → smRoman (modified)
31: 4, // langFarsi → smArabic (modified)
32: 7, // langRussian → smCyrillic
33: 25, // langSimpChinese → smSimpChinese
34: 0, // langFlemish → smRoman
35: 0, // langIrishGaelic → smRoman (modified)
36: 0, // langAlbanian → smRoman
37: 0, // langRomanian → smRoman (modified)
38: 29, // langCzech → smCentralEuroRoman
39: 29, // langSlovak → smCentralEuroRoman
40: 0, // langSlovenian → smRoman (modified)
41: 5, // langYiddish → smHebrew
42: 7, // langSerbian → smCyrillic
43: 7, // langMacedonian → smCyrillic
44: 7, // langBulgarian → smCyrillic
45: 7, // langUkrainian → smCyrillic (modified)
46: 7, // langByelorussian → smCyrillic
47: 7, // langUzbek → smCyrillic
48: 7, // langKazakh → smCyrillic
49: 7, // langAzerbaijani → smCyrillic
50: 4, // langAzerbaijanAr → smArabic
51: 24, // langArmenian → smArmenian
52: 23, // langGeorgian → smGeorgian
53: 7, // langMoldavian → smCyrillic
54: 7, // langKirghiz → smCyrillic
55: 7, // langTajiki → smCyrillic
56: 7, // langTurkmen → smCyrillic
57: 27, // langMongolian → smMongolian
58: 7, // langMongolianCyr → smCyrillic
59: 4, // langPashto → smArabic
60: 4, // langKurdish → smArabic
61: 4, // langKashmiri → smArabic
62: 4, // langSindhi → smArabic
63: 26, // langTibetan → smTibetan
64: 9, // langNepali → smDevanagari
65: 9, // langSanskrit → smDevanagari
66: 9, // langMarathi → smDevanagari
67: 13, // langBengali → smBengali
68: 13, // langAssamese → smBengali
69: 11, // langGujarati → smGujarati
70: 10, // langPunjabi → smGurmukhi
71: 12, // langOriya → smOriya
72: 17, // langMalayalam → smMalayalam
73: 16, // langKannada → smKannada
74: 14, // langTamil → smTamil
75: 15, // langTelugu → smTelugu
76: 18, // langSinhalese → smSinhalese
77: 19, // langBurmese → smBurmese
78: 20, // langKhmer → smKhmer
79: 22, // langLao → smLao
80: 30, // langVietnamese → smVietnamese
81: 0, // langIndonesian → smRoman
82: 0, // langTagalog → smRoman
83: 0, // langMalayRoman → smRoman
84: 4, // langMalayArabic → smArabic
85: 28, // langAmharic → smEthiopic
86: 28, // langTigrinya → smEthiopic
87: 28, // langOromo → smEthiopic
88: 0, // langSomali → smRoman
89: 0, // langSwahili → smRoman
90: 0, // langKinyarwanda → smRoman
91: 0, // langRundi → smRoman
92: 0, // langNyanja → smRoman
93: 0, // langMalagasy → smRoman
94: 0, // langEsperanto → smRoman
128: 0, // langWelsh → smRoman (modified)
129: 0, // langBasque → smRoman
130: 0, // langCatalan → smRoman
131: 0, // langLatin → smRoman
132: 0, // langQuechua → smRoman
133: 0, // langGuarani → smRoman
134: 0, // langAymara → smRoman
135: 7, // langTatar → smCyrillic
136: 4, // langUighur → smArabic
137: 26, // langDzongkha → smTibetan
138: 0, // langJavaneseRom → smRoman
139: 0, // langSundaneseRom → smRoman
140: 0, // langGalician → smRoman
141: 0, // langAfrikaans → smRoman
142: 0, // langBreton → smRoman (modified)
143: 28, // langInuktitut → smEthiopic (modified)
144: 0, // langScottishGaelic → smRoman (modified)
145: 0, // langManxGaelic → smRoman (modified)
146: 0, // langIrishGaelicScript → smRoman (modified)
147: 0, // langTongan → smRoman
148: 6, // langGreekAncient → smRoman
149: 0, // langGreenlandic → smRoman
150: 0, // langAzerbaijanRoman → smRoman
151: 0 // langNynorsk → smRoman
};
// While Microsoft indicates a region/country for all its language
// IDs, we omit the region code if it's equal to the "most likely
// region subtag" according to Unicode CLDR. For scripts, we omit
// the subtag if it is equal to the Suppress-Script entry in the
// IANA language subtag registry for IETF BCP 47.
//
// For example, Microsoft states that its language code 0x041A is
// Croatian in Croatia. We transform this to the BCP 47 language code 'hr'
// and not 'hr-HR' because Croatia is the default country for Croatian,
// according to Unicode CLDR. As another example, Microsoft states
// that 0x101A is Croatian (Latin) in Bosnia-Herzegovina. We transform
// this to 'hr-BA' and not 'hr-Latn-BA' because Latin is the default script
// for the Croatian language, according to IANA.
//
// http://www.unicode.org/cldr/charts/latest/supplemental/likely_subtags.html
// http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry
var windowsLanguages = {
0x0436: 'af',
0x041C: 'sq',
0x0484: 'gsw',
0x045E: 'am',
0x1401: 'ar-DZ',
0x3C01: 'ar-BH',
0x0C01: 'ar',
0x0801: 'ar-IQ',
0x2C01: 'ar-JO',
0x3401: 'ar-KW',
0x3001: 'ar-LB',
0x1001: 'ar-LY',
0x1801: 'ary',
0x2001: 'ar-OM',
0x4001: 'ar-QA',
0x0401: 'ar-SA',
0x2801: 'ar-SY',
0x1C01: 'aeb',
0x3801: 'ar-AE',
0x2401: 'ar-YE',
0x042B: 'hy',
0x044D: 'as',
0x082C: 'az-Cyrl',
0x042C: 'az',
0x046D: 'ba',
0x042D: 'eu',
0x0423: 'be',
0x0845: 'bn',
0x0445: 'bn-IN',
0x201A: 'bs-Cyrl',
0x141A: 'bs',
0x047E: 'br',
0x0402: 'bg',
0x0403: 'ca',
0x0C04: 'zh-HK',
0x1404: 'zh-MO',
0x0804: 'zh',
0x1004: 'zh-SG',
0x0404: 'zh-TW',
0x0483: 'co',
0x041A: 'hr',
0x101A: 'hr-BA',
0x0405: 'cs',
0x0406: 'da',
0x048C: 'prs',
0x0465: 'dv',
0x0813: 'nl-BE',
0x0413: 'nl',
0x0C09: 'en-AU',
0x2809: 'en-BZ',
0x1009: 'en-CA',
0x2409: 'en-029',
0x4009: 'en-IN',
0x1809: 'en-IE',
0x2009: 'en-JM',
0x4409: 'en-MY',
0x1409: 'en-NZ',
0x3409: 'en-PH',
0x4809: 'en-SG',
0x1C09: 'en-ZA',
0x2C09: 'en-TT',
0x0809: 'en-GB',
0x0409: 'en',
0x3009: 'en-ZW',
0x0425: 'et',
0x0438: 'fo',
0x0464: 'fil',
0x040B: 'fi',
0x080C: 'fr-BE',
0x0C0C: 'fr-CA',
0x040C: 'fr',
0x140C: 'fr-LU',
0x180C: 'fr-MC',
0x100C: 'fr-CH',
0x0462: 'fy',
0x0456: 'gl',
0x0437: 'ka',
0x0C07: 'de-AT',
0x0407: 'de',
0x1407: 'de-LI',
0x1007: 'de-LU',
0x0807: 'de-CH',
0x0408: 'el',
0x046F: 'kl',
0x0447: 'gu',
0x0468: 'ha',
0x040D: 'he',
0x0439: 'hi',
0x040E: 'hu',
0x040F: 'is',
0x0470: 'ig',
0x0421: 'id',
0x045D: 'iu',
0x085D: 'iu-Latn',
0x083C: 'ga',
0x0434: 'xh',
0x0435: 'zu',
0x0410: 'it',
0x0810: 'it-CH',
0x0411: 'ja',
0x044B: 'kn',
0x043F: 'kk',
0x0453: 'km',
0x0486: 'quc',
0x0487: 'rw',
0x0441: 'sw',
0x0457: 'kok',
0x0412: 'ko',
0x0440: 'ky',
0x0454: 'lo',
0x0426: 'lv',
0x0427: 'lt',
0x082E: 'dsb',
0x046E: 'lb',
0x042F: 'mk',
0x083E: 'ms-BN',
0x043E: 'ms',
0x044C: 'ml',
0x043A: 'mt',
0x0481: 'mi',
0x047A: 'arn',
0x044E: 'mr',
0x047C: 'moh',
0x0450: 'mn',
0x0850: 'mn-CN',
0x0461: 'ne',
0x0414: 'nb',
0x0814: 'nn',
0x0482: 'oc',
0x0448: 'or',
0x0463: 'ps',
0x0415: 'pl',
0x0416: 'pt',
0x0816: 'pt-PT',
0x0446: 'pa',
0x046B: 'qu-BO',
0x086B: 'qu-EC',
0x0C6B: 'qu',
0x0418: 'ro',
0x0417: 'rm',
0x0419: 'ru',
0x243B: 'smn',
0x103B: 'smj-NO',
0x143B: 'smj',
0x0C3B: 'se-FI',
0x043B: 'se',
0x083B: 'se-SE',
0x203B: 'sms',
0x183B: 'sma-NO',
0x1C3B: 'sms',
0x044F: 'sa',
0x1C1A: 'sr-Cyrl-BA',
0x0C1A: 'sr',
0x181A: 'sr-Latn-BA',
0x081A: 'sr-Latn',
0x046C: 'nso',
0x0432: 'tn',
0x045B: 'si',
0x041B: 'sk',
0x0424: 'sl',
0x2C0A: 'es-AR',
0x400A: 'es-BO',
0x340A: 'es-CL',
0x240A: 'es-CO',
0x140A: 'es-CR',
0x1C0A: 'es-DO',
0x300A: 'es-EC',
0x440A: 'es-SV',
0x100A: 'es-GT',
0x480A: 'es-HN',
0x080A: 'es-MX',
0x4C0A: 'es-NI',
0x180A: 'es-PA',
0x3C0A: 'es-PY',
0x280A: 'es-PE',
0x500A: 'es-PR',
// Microsoft has defined two different language codes for
// “Spanish with modern sorting” and “Spanish with traditional
// sorting”. This makes sense for collation APIs, and it would be
// possible to express this in BCP 47 language tags via Unicode
// extensions (eg., es-u-co-trad is Spanish with traditional
// sorting). However, for storing names in fonts, the distinction
// does not make sense, so we give “es” in both cases.
0x0C0A: 'es',
0x040A: 'es',
0x540A: 'es-US',
0x380A: 'es-UY',
0x200A: 'es-VE',
0x081D: 'sv-FI',
0x041D: 'sv',
0x045A: 'syr',
0x0428: 'tg',
0x085F: 'tzm',
0x0449: 'ta',
0x0444: 'tt',
0x044A: 'te',
0x041E: 'th',
0x0451: 'bo',
0x041F: 'tr',
0x0442: 'tk',
0x0480: 'ug',
0x0422: 'uk',
0x042E: 'hsb',
0x0420: 'ur',
0x0843: 'uz-Cyrl',
0x0443: 'uz',
0x042A: 'vi',
0x0452: 'cy',
0x0488: 'wo',
0x0485: 'sah',
0x0478: 'ii',
0x046A: 'yo'
};
// Returns a IETF BCP 47 language code, for example 'zh-Hant'
// for 'Chinese in the traditional script'.
function getLanguageCode(platformID, languageID, ltag) {
switch (platformID) {
case 0: // Unicode
if (languageID === 0xFFFF) {
return 'und';
} else if (ltag) {
return ltag[languageID];
}
break;
case 1: // Macintosh
return macLanguages[languageID];
case 3: // Windows
return windowsLanguages[languageID];
}
return undefined;
}
var utf16 = 'utf-16';
// MacOS script ID → encoding. This table stores the default case,
// which can be overridden by macLanguageEncodings.
var macScriptEncodings = {
0: 'macintosh', // smRoman
1: 'x-mac-japanese', // smJapanese
2: 'x-mac-chinesetrad', // smTradChinese
3: 'x-mac-korean', // smKorean
6: 'x-mac-greek', // smGreek
7: 'x-mac-cyrillic', // smCyrillic
9: 'x-mac-devanagai', // smDevanagari
10: 'x-mac-gurmukhi', // smGurmukhi
11: 'x-mac-gujarati', // smGujarati
12: 'x-mac-oriya', // smOriya
13: 'x-mac-bengali', // smBengali
14: 'x-mac-tamil', // smTamil
15: 'x-mac-telugu', // smTelugu
16: 'x-mac-kannada', // smKannada
17: 'x-mac-malayalam', // smMalayalam
18: 'x-mac-sinhalese', // smSinhalese
19: 'x-mac-burmese', // smBurmese
20: 'x-mac-khmer', // smKhmer
21: 'x-mac-thai', // smThai
22: 'x-mac-lao', // smLao
23: 'x-mac-georgian', // smGeorgian
24: 'x-mac-armenian', // smArmenian
25: 'x-mac-chinesesimp', // smSimpChinese
26: 'x-mac-tibetan', // smTibetan
27: 'x-mac-mongolian', // smMongolian
28: 'x-mac-ethiopic', // smEthiopic
29: 'x-mac-ce', // smCentralEuroRoman
30: 'x-mac-vietnamese', // smVietnamese
31: 'x-mac-extarabic' // smExtArabic
};
// MacOS language ID → encoding. This table stores the exceptional
// cases, which override macScriptEncodings. For writing MacOS naming
// tables, we need to emit a MacOS script ID. Therefore, we cannot
// merge macScriptEncodings into macLanguageEncodings.
//
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/Readme.txt
var macLanguageEncodings = {
15: 'x-mac-icelandic', // langIcelandic
17: 'x-mac-turkish', // langTurkish
18: 'x-mac-croatian', // langCroatian
24: 'x-mac-ce', // langLithuanian
25: 'x-mac-ce', // langPolish
26: 'x-mac-ce', // langHungarian
27: 'x-mac-ce', // langEstonian
28: 'x-mac-ce', // langLatvian
30: 'x-mac-icelandic', // langFaroese
37: 'x-mac-romanian', // langRomanian
38: 'x-mac-ce', // langCzech
39: 'x-mac-ce', // langSlovak
40: 'x-mac-ce', // langSlovenian
143: 'x-mac-inuit', // langInuktitut
146: 'x-mac-gaelic' // langIrishGaelicScript
};
function getEncoding(platformID, encodingID, languageID) {
switch (platformID) {
case 0: // Unicode
return utf16;
case 1: // Apple Macintosh
return macLanguageEncodings[languageID] || macScriptEncodings[encodingID];
case 3: // Microsoft Windows
if (encodingID === 1 || encodingID === 10) {
return utf16;
}
break;
}
return undefined;
}
// Parse the naming `name` table.
// FIXME: Format 1 additional fields are not supported yet.
// ltag is the content of the `ltag' table, such as ['en', 'zh-Hans', 'de-CH-1904'].
function parseNameTable(data, start, ltag) {
var name = {};
var p = new parse.Parser(data, start);
var format = p.parseUShort();
var count = p.parseUShort();
var stringOffset = p.offset + p.parseUShort();
for (var i = 0; i < count; i++) {
var platformID = p.parseUShort();
var encodingID = p.parseUShort();
var languageID = p.parseUShort();
var nameID = p.parseUShort();
var property = nameTableNames[nameID] || nameID;
var byteLength = p.parseUShort();
var offset = p.parseUShort();
var language = getLanguageCode(platformID, languageID, ltag);
var encoding = getEncoding(platformID, encodingID, languageID);
if (encoding !== undefined && language !== undefined) {
var text;
if (encoding === utf16) {
text = decode.UTF16(data, stringOffset + offset, byteLength);
} else {
text = decode.MACSTRING(data, stringOffset + offset, byteLength, encoding);
}
if (text) {
var translations = name[property];
if (translations === undefined) {
translations = name[property] = {};
}
translations[language] = text;
}
}
}
var langTagCount = 0;
if (format === 1) {
// FIXME: Also handle Microsoft's 'name' table 1.
langTagCount = p.parseUShort();
}
return name;
}
// {23: 'foo'} → {'foo': 23}
// ['bar', 'baz'] → {'bar': 0, 'baz': 1}
function reverseDict(dict) {
var result = {};
for (var key in dict) {
result[dict[key]] = parseInt(key);
}
return result;
}
function makeNameRecord(platformID, encodingID, languageID, nameID, length, offset) {
return new table.Record('NameRecord', [
{name: 'platformID', type: 'USHORT', value: platformID},
{name: 'encodingID', type: 'USHORT', value: encodingID},
{name: 'languageID', type: 'USHORT', value: languageID},
{name: 'nameID', type: 'USHORT', value: nameID},
{name: 'length', type: 'USHORT', value: length},
{name: 'offset', type: 'USHORT', value: offset}
]);
}
// Finds the position of needle in haystack, or -1 if not there.
// Like String.indexOf(), but for arrays.
function findSubArray(needle, haystack) {
var needleLength = needle.length;
var limit = haystack.length - needleLength + 1;
loop:
for (var pos = 0; pos < limit; pos++) {
for (; pos < limit; pos++) {
for (var k = 0; k < needleLength; k++) {
if (haystack[pos + k] !== needle[k]) {
continue loop;
}
}
return pos;
}
}
return -1;
}
function addStringToPool(s, pool) {
var offset = findSubArray(s, pool);
if (offset < 0) {
offset = pool.length;
for (var i = 0, len = s.length; i < len; ++i) {
pool.push(s[i]);
}
}
return offset;
}
function makeNameTable(names, ltag) {
var nameID;
var nameIDs = [];
var namesWithNumericKeys = {};
var nameTableIds = reverseDict(nameTableNames);
for (var key in names) {
var id = nameTableIds[key];
if (id === undefined) {
id = key;
}
nameID = parseInt(id);
if (isNaN(nameID)) {
throw new Error('Name table entry "' + key + '" does not exist, see nameTableNames for complete list.');
}
namesWithNumericKeys[nameID] = names[key];
nameIDs.push(nameID);
}
var macLanguageIds = reverseDict(macLanguages);
var windowsLanguageIds = reverseDict(windowsLanguages);
var nameRecords = [];
var stringPool = [];
for (var i = 0; i < nameIDs.length; i++) {
nameID = nameIDs[i];
var translations = namesWithNumericKeys[nameID];
for (var lang in translations) {
var text = translations[lang];
// For MacOS, we try to emit the name in the form that was introduced
// in the initial version of the TrueType spec (in the late 1980s).
// However, this can fail for various reasons: the requested BCP 47
// language code might not have an old-style Mac equivalent;
// we might not have a codec for the needed character encoding;
// or the name might contain characters that cannot be expressed
// in the old-style Macintosh encoding. In case of failure, we emit
// the name in a more modern fashion (Unicode encoding with BCP 47
// language tags) that is recognized by MacOS 10.5, released in 2009.
// If fonts were only read by operating systems, we could simply
// emit all names in the modern form; this would be much easier.
// However, there are many applications and libraries that read
// 'name' tables directly, and these will usually only recognize
// the ancient form (silently skipping the unrecognized names).
var macPlatform = 1; // Macintosh
var macLanguage = macLanguageIds[lang];
var macScript = macLanguageToScript[macLanguage];
var macEncoding = getEncoding(macPlatform, macScript, macLanguage);
var macName = encode.MACSTRING(text, macEncoding);
if (macName === undefined) {
macPlatform = 0; // Unicode
macLanguage = ltag.indexOf(lang);
if (macLanguage < 0) {
macLanguage = ltag.length;
ltag.push(lang);
}
macScript = 4; // Unicode 2.0 and later
macName = encode.UTF16(text);
}
var macNameOffset = addStringToPool(macName, stringPool);
nameRecords.push(makeNameRecord(macPlatform, macScript, macLanguage,
nameID, macName.length, macNameOffset));
var winLanguage = windowsLanguageIds[lang];
if (winLanguage !== undefined) {
var winName = encode.UTF16(text);
var winNameOffset = addStringToPool(winName, stringPool);
nameRecords.push(makeNameRecord(3, 1, winLanguage,
nameID, winName.length, winNameOffset));
}
}
}
nameRecords.sort(function(a, b) {
return ((a.platformID - b.platformID) ||
(a.encodingID - b.encodingID) ||
(a.languageID - b.languageID) ||
(a.nameID - b.nameID));
});
var t = new table.Table('name', [
{name: 'format', type: 'USHORT', value: 0},
{name: 'count', type: 'USHORT', value: nameRecords.length},
{name: 'stringOffset', type: 'USHORT', value: 6 + nameRecords.length * 12}
]);
for (var r = 0; r < nameRecords.length; r++) {
t.fields.push({name: 'record_' + r, type: 'RECORD', value: nameRecords[r]});
}
t.fields.push({name: 'strings', type: 'LITERAL', value: stringPool});
return t;
}
exports.parse = parseNameTable;
exports.make = makeNameTable;
},{"../parse":10,"../table":13,"../types":32}],29:[function(require,module,exports){
// The `OS/2` table contains metrics required in OpenType fonts.
// https://www.microsoft.com/typography/OTSPEC/os2.htm
'use strict';
var parse = require('../parse');
var table = require('../table');
var unicodeRanges = [
{begin: 0x0000, end: 0x007F}, // Basic Latin
{begin: 0x0080, end: 0x00FF}, // Latin-1 Supplement
{begin: 0x0100, end: 0x017F}, // Latin Extended-A
{begin: 0x0180, end: 0x024F}, // Latin Extended-B
{begin: 0x0250, end: 0x02AF}, // IPA Extensions
{begin: 0x02B0, end: 0x02FF}, // Spacing Modifier Letters
{begin: 0x0300, end: 0x036F}, // Combining Diacritical Marks
{begin: 0x0370, end: 0x03FF}, // Greek and Coptic
{begin: 0x2C80, end: 0x2CFF}, // Coptic
{begin: 0x0400, end: 0x04FF}, // Cyrillic
{begin: 0x0530, end: 0x058F}, // Armenian
{begin: 0x0590, end: 0x05FF}, // Hebrew
{begin: 0xA500, end: 0xA63F}, // Vai
{begin: 0x0600, end: 0x06FF}, // Arabic
{begin: 0x07C0, end: 0x07FF}, // NKo
{begin: 0x0900, end: 0x097F}, // Devanagari
{begin: 0x0980, end: 0x09FF}, // Bengali
{begin: 0x0A00, end: 0x0A7F}, // Gurmukhi
{begin: 0x0A80, end: 0x0AFF}, // Gujarati
{begin: 0x0B00, end: 0x0B7F}, // Oriya
{begin: 0x0B80, end: 0x0BFF}, // Tamil
{begin: 0x0C00, end: 0x0C7F}, // Telugu
{begin: 0x0C80, end: 0x0CFF}, // Kannada
{begin: 0x0D00, end: 0x0D7F}, // Malayalam
{begin: 0x0E00, end: 0x0E7F}, // Thai
{begin: 0x0E80, end: 0x0EFF}, // Lao
{begin: 0x10A0, end: 0x10FF}, // Georgian
{begin: 0x1B00, end: 0x1B7F}, // Balinese
{begin: 0x1100, end: 0x11FF}, // Hangul Jamo
{begin: 0x1E00, end: 0x1EFF}, // Latin Extended Additional
{begin: 0x1F00, end: 0x1FFF}, // Greek Extended
{begin: 0x2000, end: 0x206F}, // General Punctuation
{begin: 0x2070, end: 0x209F}, // Superscripts And Subscripts
{begin: 0x20A0, end: 0x20CF}, // Currency Symbol
{begin: 0x20D0, end: 0x20FF}, // Combining Diacritical Marks For Symbols
{begin: 0x2100, end: 0x214F}, // Letterlike Symbols
{begin: 0x2150, end: 0x218F}, // Number Forms
{begin: 0x2190, end: 0x21FF}, // Arrows
{begin: 0x2200, end: 0x22FF}, // Mathematical Operators
{begin: 0x2300, end: 0x23FF}, // Miscellaneous Technical
{begin: 0x2400, end: 0x243F}, // Control Pictures
{begin: 0x2440, end: 0x245F}, // Optical Character Recognition
{begin: 0x2460, end: 0x24FF}, // Enclosed Alphanumerics
{begin: 0x2500, end: 0x257F}, // Box Drawing
{begin: 0x2580, end: 0x259F}, // Block Elements
{begin: 0x25A0, end: 0x25FF}, // Geometric Shapes
{begin: 0x2600, end: 0x26FF}, // Miscellaneous Symbols
{begin: 0x2700, end: 0x27BF}, // Dingbats
{begin: 0x3000, end: 0x303F}, // CJK Symbols And Punctuation
{begin: 0x3040, end: 0x309F}, // Hiragana
{begin: 0x30A0, end: 0x30FF}, // Katakana
{begin: 0x3100, end: 0x312F}, // Bopomofo
{begin: 0x3130, end: 0x318F}, // Hangul Compatibility Jamo
{begin: 0xA840, end: 0xA87F}, // Phags-pa
{begin: 0x3200, end: 0x32FF}, // Enclosed CJK Letters And Months
{begin: 0x3300, end: 0x33FF}, // CJK Compatibility
{begin: 0xAC00, end: 0xD7AF}, // Hangul Syllables
{begin: 0xD800, end: 0xDFFF}, // Non-Plane 0 *
{begin: 0x10900, end: 0x1091F}, // Phoenicia
{begin: 0x4E00, end: 0x9FFF}, // CJK Unified Ideographs
{begin: 0xE000, end: 0xF8FF}, // Private Use Area (plane 0)
{begin: 0x31C0, end: 0x31EF}, // CJK Strokes
{begin: 0xFB00, end: 0xFB4F}, // Alphabetic Presentation Forms
{begin: 0xFB50, end: 0xFDFF}, // Arabic Presentation Forms-A
{begin: 0xFE20, end: 0xFE2F}, // Combining Half Marks
{begin: 0xFE10, end: 0xFE1F}, // Vertical Forms
{begin: 0xFE50, end: 0xFE6F}, // Small Form Variants
{begin: 0xFE70, end: 0xFEFF}, // Arabic Presentation Forms-B
{begin: 0xFF00, end: 0xFFEF}, // Halfwidth And Fullwidth Forms
{begin: 0xFFF0, end: 0xFFFF}, // Specials
{begin: 0x0F00, end: 0x0FFF}, // Tibetan
{begin: 0x0700, end: 0x074F}, // Syriac
{begin: 0x0780, end: 0x07BF}, // Thaana
{begin: 0x0D80, end: 0x0DFF}, // Sinhala
{begin: 0x1000, end: 0x109F}, // Myanmar
{begin: 0x1200, end: 0x137F}, // Ethiopic
{begin: 0x13A0, end: 0x13FF}, // Cherokee
{begin: 0x1400, end: 0x167F}, // Unified Canadian Aboriginal Syllabics
{begin: 0x1680, end: 0x169F}, // Ogham
{begin: 0x16A0, end: 0x16FF}, // Runic
{begin: 0x1780, end: 0x17FF}, // Khmer
{begin: 0x1800, end: 0x18AF}, // Mongolian
{begin: 0x2800, end: 0x28FF}, // Braille Patterns
{begin: 0xA000, end: 0xA48F}, // Yi Syllables
{begin: 0x1700, end: 0x171F}, // Tagalog
{begin: 0x10300, end: 0x1032F}, // Old Italic
{begin: 0x10330, end: 0x1034F}, // Gothic
{begin: 0x10400, end: 0x1044F}, // Deseret
{begin: 0x1D000, end: 0x1D0FF}, // Byzantine Musical Symbols
{begin: 0x1D400, end: 0x1D7FF}, // Mathematical Alphanumeric Symbols
{begin: 0xFF000, end: 0xFFFFD}, // Private Use (plane 15)
{begin: 0xFE00, end: 0xFE0F}, // Variation Selectors
{begin: 0xE0000, end: 0xE007F}, // Tags
{begin: 0x1900, end: 0x194F}, // Limbu
{begin: 0x1950, end: 0x197F}, // Tai Le
{begin: 0x1980, end: 0x19DF}, // New Tai Lue
{begin: 0x1A00, end: 0x1A1F}, // Buginese
{begin: 0x2C00, end: 0x2C5F}, // Glagolitic
{begin: 0x2D30, end: 0x2D7F}, // Tifinagh
{begin: 0x4DC0, end: 0x4DFF}, // Yijing Hexagram Symbols
{begin: 0xA800, end: 0xA82F}, // Syloti Nagri
{begin: 0x10000, end: 0x1007F}, // Linear B Syllabary
{begin: 0x10140, end: 0x1018F}, // Ancient Greek Numbers
{begin: 0x10380, end: 0x1039F}, // Ugaritic
{begin: 0x103A0, end: 0x103DF}, // Old Persian
{begin: 0x10450, end: 0x1047F}, // Shavian
{begin: 0x10480, end: 0x104AF}, // Osmanya
{begin: 0x10800, end: 0x1083F}, // Cypriot Syllabary
{begin: 0x10A00, end: 0x10A5F}, // Kharoshthi
{begin: 0x1D300, end: 0x1D35F}, // Tai Xuan Jing Symbols
{begin: 0x12000, end: 0x123FF}, // Cuneiform
{begin: 0x1D360, end: 0x1D37F}, // Counting Rod Numerals
{begin: 0x1B80, end: 0x1BBF}, // Sundanese
{begin: 0x1C00, end: 0x1C4F}, // Lepcha
{begin: 0x1C50, end: 0x1C7F}, // Ol Chiki
{begin: 0xA880, end: 0xA8DF}, // Saurashtra
{begin: 0xA900, end: 0xA92F}, // Kayah Li
{begin: 0xA930, end: 0xA95F}, // Rejang
{begin: 0xAA00, end: 0xAA5F}, // Cham
{begin: 0x10190, end: 0x101CF}, // Ancient Symbols
{begin: 0x101D0, end: 0x101FF}, // Phaistos Disc
{begin: 0x102A0, end: 0x102DF}, // Carian
{begin: 0x1F030, end: 0x1F09F} // Domino Tiles
];
function getUnicodeRange(unicode) {
for (var i = 0; i < unicodeRanges.length; i += 1) {
var range = unicodeRanges[i];
if (unicode >= range.begin && unicode < range.end) {
return i;
}
}
return -1;
}
// Parse the OS/2 and Windows metrics `OS/2` table
function parseOS2Table(data, start) {
var os2 = {};
var p = new parse.Parser(data, start);
os2.version = p.parseUShort();
os2.xAvgCharWidth = p.parseShort();
os2.usWeightClass = p.parseUShort();
os2.usWidthClass = p.parseUShort();
os2.fsType = p.parseUShort();
os2.ySubscriptXSize = p.parseShort();
os2.ySubscriptYSize = p.parseShort();
os2.ySubscriptXOffset = p.parseShort();
os2.ySubscriptYOffset = p.parseShort();
os2.ySuperscriptXSize = p.parseShort();
os2.ySuperscriptYSize = p.parseShort();
os2.ySuperscriptXOffset = p.parseShort();
os2.ySuperscriptYOffset = p.parseShort();
os2.yStrikeoutSize = p.parseShort();
os2.yStrikeoutPosition = p.parseShort();
os2.sFamilyClass = p.parseShort();
os2.panose = [];
for (var i = 0; i < 10; i++) {
os2.panose[i] = p.parseByte();
}
os2.ulUnicodeRange1 = p.parseULong();
os2.ulUnicodeRange2 = p.parseULong();
os2.ulUnicodeRange3 = p.parseULong();
os2.ulUnicodeRange4 = p.parseULong();
os2.achVendID = String.fromCharCode(p.parseByte(), p.parseByte(), p.parseByte(), p.parseByte());
os2.fsSelection = p.parseUShort();
os2.usFirstCharIndex = p.parseUShort();
os2.usLastCharIndex = p.parseUShort();
os2.sTypoAscender = p.parseShort();
os2.sTypoDescender = p.parseShort();
os2.sTypoLineGap = p.parseShort();
os2.usWinAscent = p.parseUShort();
os2.usWinDescent = p.parseUShort();
if (os2.version >= 1) {
os2.ulCodePageRange1 = p.parseULong();
os2.ulCodePageRange2 = p.parseULong();
}
if (os2.version >= 2) {
os2.sxHeight = p.parseShort();
os2.sCapHeight = p.parseShort();
os2.usDefaultChar = p.parseUShort();
os2.usBreakChar = p.parseUShort();
os2.usMaxContent = p.parseUShort();
}
return os2;
}
function makeOS2Table(options) {
return new table.Table('OS/2', [
{name: 'version', type: 'USHORT', value: 0x0003},
{name: 'xAvgCharWidth', type: 'SHORT', value: 0},
{name: 'usWeightClass', type: 'USHORT', value: 0},
{name: 'usWidthClass', type: 'USHORT', value: 0},
{name: 'fsType', type: 'USHORT', value: 0},
{name: 'ySubscriptXSize', type: 'SHORT', value: 650},
{name: 'ySubscriptYSize', type: 'SHORT', value: 699},
{name: 'ySubscriptXOffset', type: 'SHORT', value: 0},
{name: 'ySubscriptYOffset', type: 'SHORT', value: 140},
{name: 'ySuperscriptXSize', type: 'SHORT', value: 650},
{name: 'ySuperscriptYSize', type: 'SHORT', value: 699},
{name: 'ySuperscriptXOffset', type: 'SHORT', value: 0},
{name: 'ySuperscriptYOffset', type: 'SHORT', value: 479},
{name: 'yStrikeoutSize', type: 'SHORT', value: 49},
{name: 'yStrikeoutPosition', type: 'SHORT', value: 258},
{name: 'sFamilyClass', type: 'SHORT', value: 0},
{name: 'bFamilyType', type: 'BYTE', value: 0},
{name: 'bSerifStyle', type: 'BYTE', value: 0},
{name: 'bWeight', type: 'BYTE', value: 0},
{name: 'bProportion', type: 'BYTE', value: 0},
{name: 'bContrast', type: 'BYTE', value: 0},
{name: 'bStrokeVariation', type: 'BYTE', value: 0},
{name: 'bArmStyle', type: 'BYTE', value: 0},
{name: 'bLetterform', type: 'BYTE', value: 0},
{name: 'bMidline', type: 'BYTE', value: 0},
{name: 'bXHeight', type: 'BYTE', value: 0},
{name: 'ulUnicodeRange1', type: 'ULONG', value: 0},
{name: 'ulUnicodeRange2', type: 'ULONG', value: 0},
{name: 'ulUnicodeRange3', type: 'ULONG', value: 0},
{name: 'ulUnicodeRange4', type: 'ULONG', value: 0},
{name: 'achVendID', type: 'CHARARRAY', value: 'XXXX'},
{name: 'fsSelection', type: 'USHORT', value: 0},
{name: 'usFirstCharIndex', type: 'USHORT', value: 0},
{name: 'usLastCharIndex', type: 'USHORT', value: 0},
{name: 'sTypoAscender', type: 'SHORT', value: 0},
{name: 'sTypoDescender', type: 'SHORT', value: 0},
{name: 'sTypoLineGap', type: 'SHORT', value: 0},
{name: 'usWinAscent', type: 'USHORT', value: 0},
{name: 'usWinDescent', type: 'USHORT', value: 0},
{name: 'ulCodePageRange1', type: 'ULONG', value: 0},
{name: 'ulCodePageRange2', type: 'ULONG', value: 0},
{name: 'sxHeight', type: 'SHORT', value: 0},
{name: 'sCapHeight', type: 'SHORT', value: 0},
{name: 'usDefaultChar', type: 'USHORT', value: 0},
{name: 'usBreakChar', type: 'USHORT', value: 0},
{name: 'usMaxContext', type: 'USHORT', value: 0}
], options);
}
exports.unicodeRanges = unicodeRanges;
exports.getUnicodeRange = getUnicodeRange;
exports.parse = parseOS2Table;
exports.make = makeOS2Table;
},{"../parse":10,"../table":13}],30:[function(require,module,exports){
// The `post` table stores additional PostScript information, such as glyph names.
// https://www.microsoft.com/typography/OTSPEC/post.htm
'use strict';
var encoding = require('../encoding');
var parse = require('../parse');
var table = require('../table');
// Parse the PostScript `post` table
function parsePostTable(data, start) {
var post = {};
var p = new parse.Parser(data, start);
var i;
post.version = p.parseVersion();
post.italicAngle = p.parseFixed();
post.underlinePosition = p.parseShort();
post.underlineThickness = p.parseShort();
post.isFixedPitch = p.parseULong();
post.minMemType42 = p.parseULong();
post.maxMemType42 = p.parseULong();
post.minMemType1 = p.parseULong();
post.maxMemType1 = p.parseULong();
switch (post.version) {
case 1:
post.names = encoding.standardNames.slice();
break;
case 2:
post.numberOfGlyphs = p.parseUShort();
post.glyphNameIndex = new Array(post.numberOfGlyphs);
for (i = 0; i < post.numberOfGlyphs; i++) {
post.glyphNameIndex[i] = p.parseUShort();
}
post.names = [];
for (i = 0; i < post.numberOfGlyphs; i++) {
if (post.glyphNameIndex[i] >= encoding.standardNames.length) {
var nameLength = p.parseChar();
post.names.push(p.parseString(nameLength));
}
}
break;
case 2.5:
post.numberOfGlyphs = p.parseUShort();
post.offset = new Array(post.numberOfGlyphs);
for (i = 0; i < post.numberOfGlyphs; i++) {
post.offset[i] = p.parseChar();
}
break;
}
return post;
}
function makePostTable() {
return new table.Table('post', [
{name: 'version', type: 'FIXED', value: 0x00030000},
{name: 'italicAngle', type: 'FIXED', value: 0},
{name: 'underlinePosition', type: 'FWORD', value: 0},
{name: 'underlineThickness', type: 'FWORD', value: 0},
{name: 'isFixedPitch', type: 'ULONG', value: 0},
{name: 'minMemType42', type: 'ULONG', value: 0},
{name: 'maxMemType42', type: 'ULONG', value: 0},
{name: 'minMemType1', type: 'ULONG', value: 0},
{name: 'maxMemType1', type: 'ULONG', value: 0}
]);
}
exports.parse = parsePostTable;
exports.make = makePostTable;
},{"../encoding":4,"../parse":10,"../table":13}],31:[function(require,module,exports){
// The `sfnt` wrapper provides organization for the tables in the font.
// It is the top-level data structure in a font.
// https://www.microsoft.com/typography/OTSPEC/otff.htm
// Recommendations for creating OpenType Fonts:
// http://www.microsoft.com/typography/otspec140/recom.htm
'use strict';
var check = require('../check');
var table = require('../table');
var cmap = require('./cmap');
var cff = require('./cff');
var head = require('./head');
var hhea = require('./hhea');
var hmtx = require('./hmtx');
var ltag = require('./ltag');
var maxp = require('./maxp');
var _name = require('./name');
var os2 = require('./os2');
var post = require('./post');
var gsub = require('./gsub');
var meta = require('./meta');
function log2(v) {
return Math.log(v) / Math.log(2) | 0;
}
function computeCheckSum(bytes) {
while (bytes.length % 4 !== 0) {
bytes.push(0);
}
var sum = 0;
for (var i = 0; i < bytes.length; i += 4) {
sum += (bytes[i] << 24) +
(bytes[i + 1] << 16) +
(bytes[i + 2] << 8) +
(bytes[i + 3]);
}
sum %= Math.pow(2, 32);
return sum;
}
function makeTableRecord(tag, checkSum, offset, length) {
return new table.Record('Table Record', [
{name: 'tag', type: 'TAG', value: tag !== undefined ? tag : ''},
{name: 'checkSum', type: 'ULONG', value: checkSum !== undefined ? checkSum : 0},
{name: 'offset', type: 'ULONG', value: offset !== undefined ? offset : 0},
{name: 'length', type: 'ULONG', value: length !== undefined ? length : 0}
]);
}
function makeSfntTable(tables) {
var sfnt = new table.Table('sfnt', [
{name: 'version', type: 'TAG', value: 'OTTO'},
{name: 'numTables', type: 'USHORT', value: 0},
{name: 'searchRange', type: 'USHORT', value: 0},
{name: 'entrySelector', type: 'USHORT', value: 0},
{name: 'rangeShift', type: 'USHORT', value: 0}
]);
sfnt.tables = tables;
sfnt.numTables = tables.length;
var highestPowerOf2 = Math.pow(2, log2(sfnt.numTables));
sfnt.searchRange = 16 * highestPowerOf2;
sfnt.entrySelector = log2(highestPowerOf2);
sfnt.rangeShift = sfnt.numTables * 16 - sfnt.searchRange;
var recordFields = [];
var tableFields = [];
var offset = sfnt.sizeOf() + (makeTableRecord().sizeOf() * sfnt.numTables);
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({name: 'padding', type: 'BYTE', value: 0});
}
for (var i = 0; i < tables.length; i += 1) {
var t = tables[i];
check.argument(t.tableName.length === 4, 'Table name' + t.tableName + ' is invalid.');
var tableLength = t.sizeOf();
var tableRecord = makeTableRecord(t.tableName, computeCheckSum(t.encode()), offset, tableLength);
recordFields.push({name: tableRecord.tag + ' Table Record', type: 'RECORD', value: tableRecord});
tableFields.push({name: t.tableName + ' table', type: 'RECORD', value: t});
offset += tableLength;
check.argument(!isNaN(offset), 'Something went wrong calculating the offset.');
while (offset % 4 !== 0) {
offset += 1;
tableFields.push({name: 'padding', type: 'BYTE', value: 0});
}
}
// Table records need to be sorted alphabetically.
recordFields.sort(function(r1, r2) {
if (r1.value.tag > r2.value.tag) {
return 1;
} else {
return -1;
}
});
sfnt.fields = sfnt.fields.concat(recordFields);
sfnt.fields = sfnt.fields.concat(tableFields);
return sfnt;
}
// Get the metrics for a character. If the string has more than one character
// this function returns metrics for the first available character.
// You can provide optional fallback metrics if no characters are available.
function metricsForChar(font, chars, notFoundMetrics) {
for (var i = 0; i < chars.length; i += 1) {
var glyphIndex = font.charToGlyphIndex(chars[i]);
if (glyphIndex > 0) {
var glyph = font.glyphs.get(glyphIndex);
return glyph.getMetrics();
}
}
return notFoundMetrics;
}
function average(vs) {
var sum = 0;
for (var i = 0; i < vs.length; i += 1) {
sum += vs[i];
}
return sum / vs.length;
}
// Convert the font object to a SFNT data structure.
// This structure contains all the necessary tables and metadata to create a binary OTF file.
function fontToSfntTable(font) {
var xMins = [];
var yMins = [];
var xMaxs = [];
var yMaxs = [];
var advanceWidths = [];
var leftSideBearings = [];
var rightSideBearings = [];
var firstCharIndex;
var lastCharIndex = 0;
var ulUnicodeRange1 = 0;
var ulUnicodeRange2 = 0;
var ulUnicodeRange3 = 0;
var ulUnicodeRange4 = 0;
for (var i = 0; i < font.glyphs.length; i += 1) {
var glyph = font.glyphs.get(i);
var unicode = glyph.unicode | 0;
if (isNaN(glyph.advanceWidth)) {
throw new Error('Glyph ' + glyph.name + ' (' + i + '): advanceWidth is not a number.');
}
if (firstCharIndex > unicode || firstCharIndex === undefined) {
// ignore .notdef char
if (unicode > 0) {
firstCharIndex = unicode;
}
}
if (lastCharIndex < unicode) {
lastCharIndex = unicode;
}
var position = os2.getUnicodeRange(unicode);
if (position < 32) {
ulUnicodeRange1 |= 1 << position;
} else if (position < 64) {
ulUnicodeRange2 |= 1 << position - 32;
} else if (position < 96) {
ulUnicodeRange3 |= 1 << position - 64;
} else if (position < 123) {
ulUnicodeRange4 |= 1 << position - 96;
} else {
throw new Error('Unicode ranges bits > 123 are reserved for internal usage');
}
// Skip non-important characters.
if (glyph.name === '.notdef') continue;
var metrics = glyph.getMetrics();
xMins.push(metrics.xMin);
yMins.push(metrics.yMin);
xMaxs.push(metrics.xMax);
yMaxs.push(metrics.yMax);
leftSideBearings.push(metrics.leftSideBearing);
rightSideBearings.push(metrics.rightSideBearing);
advanceWidths.push(glyph.advanceWidth);
}
var globals = {
xMin: Math.min.apply(null, xMins),
yMin: Math.min.apply(null, yMins),
xMax: Math.max.apply(null, xMaxs),
yMax: Math.max.apply(null, yMaxs),
advanceWidthMax: Math.max.apply(null, advanceWidths),
advanceWidthAvg: average(advanceWidths),
minLeftSideBearing: Math.min.apply(null, leftSideBearings),
maxLeftSideBearing: Math.max.apply(null, leftSideBearings),
minRightSideBearing: Math.min.apply(null, rightSideBearings)
};
globals.ascender = font.ascender;
globals.descender = font.descender;
var headTable = head.make({
flags: 3, // 00000011 (baseline for font at y=0; left sidebearing point at x=0)
unitsPerEm: font.unitsPerEm,
xMin: globals.xMin,
yMin: globals.yMin,
xMax: globals.xMax,
yMax: globals.yMax,
lowestRecPPEM: 3,
createdTimestamp: font.createdTimestamp
});
var hheaTable = hhea.make({
ascender: globals.ascender,
descender: globals.descender,
advanceWidthMax: globals.advanceWidthMax,
minLeftSideBearing: globals.minLeftSideBearing,
minRightSideBearing: globals.minRightSideBearing,
xMaxExtent: globals.maxLeftSideBearing + (globals.xMax - globals.xMin),
numberOfHMetrics: font.glyphs.length
});
var maxpTable = maxp.make(font.glyphs.length);
var os2Table = os2.make({
xAvgCharWidth: Math.round(globals.advanceWidthAvg),
usWeightClass: font.tables.os2.usWeightClass,
usWidthClass: font.tables.os2.usWidthClass,
usFirstCharIndex: firstCharIndex,
usLastCharIndex: lastCharIndex,
ulUnicodeRange1: ulUnicodeRange1,
ulUnicodeRange2: ulUnicodeRange2,
ulUnicodeRange3: ulUnicodeRange3,
ulUnicodeRange4: ulUnicodeRange4,
fsSelection: font.tables.os2.fsSelection, // REGULAR
// See http://typophile.com/node/13081 for more info on vertical metrics.
// We get metrics for typical characters (such as "x" for xHeight).
// We provide some fallback characters if characters are unavailable: their
// ordering was chosen experimentally.
sTypoAscender: globals.ascender,
sTypoDescender: globals.descender,
sTypoLineGap: 0,
usWinAscent: globals.yMax,
usWinDescent: Math.abs(globals.yMin),
ulCodePageRange1: 1, // FIXME: hard-code Latin 1 support for now
sxHeight: metricsForChar(font, 'xyvw', {yMax: Math.round(globals.ascender / 2)}).yMax,
sCapHeight: metricsForChar(font, 'HIKLEFJMNTZBDPRAGOQSUVWXY', globals).yMax,
usDefaultChar: font.hasChar(' ') ? 32 : 0, // Use space as the default character, if available.
usBreakChar: font.hasChar(' ') ? 32 : 0 // Use space as the break character, if available.
});
var hmtxTable = hmtx.make(font.glyphs);
var cmapTable = cmap.make(font.glyphs);
var englishFamilyName = font.getEnglishName('fontFamily');
var englishStyleName = font.getEnglishName('fontSubfamily');
var englishFullName = englishFamilyName + ' ' + englishStyleName;
var postScriptName = font.getEnglishName('postScriptName');
if (!postScriptName) {
postScriptName = englishFamilyName.replace(/\s/g, '') + '-' + englishStyleName;
}
var names = {};
for (var n in font.names) {
names[n] = font.names[n];
}
if (!names.uniqueID) {
names.uniqueID = {en: font.getEnglishName('manufacturer') + ':' + englishFullName};
}
if (!names.postScriptName) {
names.postScriptName = {en: postScriptName};
}
if (!names.preferredFamily) {
names.preferredFamily = font.names.fontFamily;
}
if (!names.preferredSubfamily) {
names.preferredSubfamily = font.names.fontSubfamily;
}
var languageTags = [];
var nameTable = _name.make(names, languageTags);
var ltagTable = (languageTags.length > 0 ? ltag.make(languageTags) : undefined);
var postTable = post.make();
var cffTable = cff.make(font.glyphs, {
version: font.getEnglishName('version'),
fullName: englishFullName,
familyName: englishFamilyName,
weightName: englishStyleName,
postScriptName: postScriptName,
unitsPerEm: font.unitsPerEm,
fontBBox: [0, globals.yMin, globals.ascender, globals.advanceWidthMax]
});
var metaTable = (font.metas && Object.keys(font.metas).length > 0) ? meta.make(font.metas) : undefined;
// The order does not matter because makeSfntTable() will sort them.
var tables = [headTable, hheaTable, maxpTable, os2Table, nameTable, cmapTable, postTable, cffTable, hmtxTable];
if (ltagTable) {
tables.push(ltagTable);
}
// Optional tables
if (font.tables.gsub) {
tables.push(gsub.make(font.tables.gsub));
}
if (metaTable) {
tables.push(metaTable);
}
var sfntTable = makeSfntTable(tables);
// Compute the font's checkSum and store it in head.checkSumAdjustment.
var bytes = sfntTable.encode();
var checkSum = computeCheckSum(bytes);
var tableFields = sfntTable.fields;
var checkSumAdjusted = false;
for (i = 0; i < tableFields.length; i += 1) {
if (tableFields[i].name === 'head table') {
tableFields[i].value.checkSumAdjustment = 0xB1B0AFBA - checkSum;
checkSumAdjusted = true;
break;
}
}
if (!checkSumAdjusted) {
throw new Error('Could not find head table with checkSum to adjust.');
}
return sfntTable;
}
exports.computeCheckSum = computeCheckSum;
exports.make = makeSfntTable;
exports.fontToTable = fontToSfntTable;
},{"../check":2,"../table":13,"./cff":14,"./cmap":15,"./gsub":19,"./head":20,"./hhea":21,"./hmtx":22,"./ltag":25,"./maxp":26,"./meta":27,"./name":28,"./os2":29,"./post":30}],32:[function(require,module,exports){
// Data types used in the OpenType font file.
// All OpenType fonts use Motorola-style byte ordering (Big Endian)
/* global WeakMap */
'use strict';
var check = require('./check');
var LIMIT16 = 32768; // The limit at which a 16-bit number switches signs == 2^15
var LIMIT32 = 2147483648; // The limit at which a 32-bit number switches signs == 2 ^ 31
/**
* @exports opentype.decode
* @class
*/
var decode = {};
/**
* @exports opentype.encode
* @class
*/
var encode = {};
/**
* @exports opentype.sizeOf
* @class
*/
var sizeOf = {};
// Return a function that always returns the same value.
function constant(v) {
return function() {
return v;
};
}
// OpenType data types //////////////////////////////////////////////////////
/**
* Convert an 8-bit unsigned integer to a list of 1 byte.
* @param {number}
* @returns {Array}
*/
encode.BYTE = function(v) {
check.argument(v >= 0 && v <= 255, 'Byte value should be between 0 and 255.');
return [v];
};
/**
* @constant
* @type {number}
*/
sizeOf.BYTE = constant(1);
/**
* Convert a 8-bit signed integer to a list of 1 byte.
* @param {string}
* @returns {Array}
*/
encode.CHAR = function(v) {
return [v.charCodeAt(0)];
};
/**
* @constant
* @type {number}
*/
sizeOf.CHAR = constant(1);
/**
* Convert an ASCII string to a list of bytes.
* @param {string}
* @returns {Array}
*/
encode.CHARARRAY = function(v) {
var b = [];
for (var i = 0; i < v.length; i += 1) {
b[i] = v.charCodeAt(i);
}
return b;
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.CHARARRAY = function(v) {
return v.length;
};
/**
* Convert a 16-bit unsigned integer to a list of 2 bytes.
* @param {number}
* @returns {Array}
*/
encode.USHORT = function(v) {
return [(v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.USHORT = constant(2);
/**
* Convert a 16-bit signed integer to a list of 2 bytes.
* @param {number}
* @returns {Array}
*/
encode.SHORT = function(v) {
// Two's complement
if (v >= LIMIT16) {
v = -(2 * LIMIT16 - v);
}
return [(v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.SHORT = constant(2);
/**
* Convert a 24-bit unsigned integer to a list of 3 bytes.
* @param {number}
* @returns {Array}
*/
encode.UINT24 = function(v) {
return [(v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.UINT24 = constant(3);
/**
* Convert a 32-bit unsigned integer to a list of 4 bytes.
* @param {number}
* @returns {Array}
*/
encode.ULONG = function(v) {
return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.ULONG = constant(4);
/**
* Convert a 32-bit unsigned integer to a list of 4 bytes.
* @param {number}
* @returns {Array}
*/
encode.LONG = function(v) {
// Two's complement
if (v >= LIMIT32) {
v = -(2 * LIMIT32 - v);
}
return [(v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.LONG = constant(4);
encode.FIXED = encode.ULONG;
sizeOf.FIXED = sizeOf.ULONG;
encode.FWORD = encode.SHORT;
sizeOf.FWORD = sizeOf.SHORT;
encode.UFWORD = encode.USHORT;
sizeOf.UFWORD = sizeOf.USHORT;
/**
* Convert a 32-bit Apple Mac timestamp integer to a list of 8 bytes, 64-bit timestamp.
* @param {number}
* @returns {Array}
*/
encode.LONGDATETIME = function(v) {
return [0, 0, 0, 0, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.LONGDATETIME = constant(8);
/**
* Convert a 4-char tag to a list of 4 bytes.
* @param {string}
* @returns {Array}
*/
encode.TAG = function(v) {
check.argument(v.length === 4, 'Tag should be exactly 4 ASCII characters.');
return [v.charCodeAt(0),
v.charCodeAt(1),
v.charCodeAt(2),
v.charCodeAt(3)];
};
/**
* @constant
* @type {number}
*/
sizeOf.TAG = constant(4);
// CFF data types ///////////////////////////////////////////////////////////
encode.Card8 = encode.BYTE;
sizeOf.Card8 = sizeOf.BYTE;
encode.Card16 = encode.USHORT;
sizeOf.Card16 = sizeOf.USHORT;
encode.OffSize = encode.BYTE;
sizeOf.OffSize = sizeOf.BYTE;
encode.SID = encode.USHORT;
sizeOf.SID = sizeOf.USHORT;
// Convert a numeric operand or charstring number to a variable-size list of bytes.
/**
* Convert a numeric operand or charstring number to a variable-size list of bytes.
* @param {number}
* @returns {Array}
*/
encode.NUMBER = function(v) {
if (v >= -107 && v <= 107) {
return [v + 139];
} else if (v >= 108 && v <= 1131) {
v = v - 108;
return [(v >> 8) + 247, v & 0xFF];
} else if (v >= -1131 && v <= -108) {
v = -v - 108;
return [(v >> 8) + 251, v & 0xFF];
} else if (v >= -32768 && v <= 32767) {
return encode.NUMBER16(v);
} else {
return encode.NUMBER32(v);
}
};
/**
* @param {number}
* @returns {number}
*/
sizeOf.NUMBER = function(v) {
return encode.NUMBER(v).length;
};
/**
* Convert a signed number between -32768 and +32767 to a three-byte value.
* This ensures we always use three bytes, but is not the most compact format.
* @param {number}
* @returns {Array}
*/
encode.NUMBER16 = function(v) {
return [28, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.NUMBER16 = constant(3);
/**
* Convert a signed number between -(2^31) and +(2^31-1) to a five-byte value.
* This is useful if you want to be sure you always use four bytes,
* at the expense of wasting a few bytes for smaller numbers.
* @param {number}
* @returns {Array}
*/
encode.NUMBER32 = function(v) {
return [29, (v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF];
};
/**
* @constant
* @type {number}
*/
sizeOf.NUMBER32 = constant(5);
/**
* @param {number}
* @returns {Array}
*/
encode.REAL = function(v) {
var value = v.toString();
// Some numbers use an epsilon to encode the value. (e.g. JavaScript will store 0.0000001 as 1e-7)
// This code converts it back to a number without the epsilon.
var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
if (m) {
var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(v * epsilon) / epsilon).toString();
}
var nibbles = '';
var i;
var ii;
for (i = 0, ii = value.length; i < ii; i += 1) {
var c = value[i];
if (c === 'e') {
nibbles += value[++i] === '-' ? 'c' : 'b';
} else if (c === '.') {
nibbles += 'a';
} else if (c === '-') {
nibbles += 'e';
} else {
nibbles += c;
}
}
nibbles += (nibbles.length & 1) ? 'f' : 'ff';
var out = [30];
for (i = 0, ii = nibbles.length; i < ii; i += 2) {
out.push(parseInt(nibbles.substr(i, 2), 16));
}
return out;
};
/**
* @param {number}
* @returns {number}
*/
sizeOf.REAL = function(v) {
return encode.REAL(v).length;
};
encode.NAME = encode.CHARARRAY;
sizeOf.NAME = sizeOf.CHARARRAY;
encode.STRING = encode.CHARARRAY;
sizeOf.STRING = sizeOf.CHARARRAY;
/**
* @param {DataView} data
* @param {number} offset
* @param {number} numBytes
* @returns {string}
*/
decode.UTF8 = function(data, offset, numBytes) {
var codePoints = [];
var numChars = numBytes;
for (var j = 0; j < numChars; j++, offset += 1) {
codePoints[j] = data.getUint8(offset);
}
return String.fromCharCode.apply(null, codePoints);
};
/**
* @param {DataView} data
* @param {number} offset
* @param {number} numBytes
* @returns {string}
*/
decode.UTF16 = function(data, offset, numBytes) {
var codePoints = [];
var numChars = numBytes / 2;
for (var j = 0; j < numChars; j++, offset += 2) {
codePoints[j] = data.getUint16(offset);
}
return String.fromCharCode.apply(null, codePoints);
};
/**
* Convert a JavaScript string to UTF16-BE.
* @param {string}
* @returns {Array}
*/
encode.UTF16 = function(v) {
var b = [];
for (var i = 0; i < v.length; i += 1) {
var codepoint = v.charCodeAt(i);
b[b.length] = (codepoint >> 8) & 0xFF;
b[b.length] = codepoint & 0xFF;
}
return b;
};
/**
* @param {string}
* @returns {number}
*/
sizeOf.UTF16 = function(v) {
return v.length * 2;
};
// Data for converting old eight-bit Macintosh encodings to Unicode.
// This representation is optimized for decoding; encoding is slower
// and needs more memory. The assumption is that all opentype.js users
// want to open fonts, but saving a font will be comperatively rare
// so it can be more expensive. Keyed by IANA character set name.
//
// Python script for generating these strings:
//
// s = u''.join([chr(c).decode('mac_greek') for c in range(128, 256)])
// print(s.encode('utf-8'))
/**
* @private
*/
var eightBitMacEncodings = {
'x-mac-croatian': // Python: 'mac_croatian'
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø' +
'¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ',
'x-mac-cyrillic': // Python: 'mac_cyrillic'
'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ' +
'јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю',
'x-mac-gaelic':
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/GAELIC.TXT
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø' +
'ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ',
'x-mac-greek': // Python: 'mac_greek'
'Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ' +
'άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ\u00AD',
'x-mac-icelandic': // Python: 'mac_iceland'
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
'x-mac-inuit':
// http://unicode.org/Public/MAPPINGS/VENDORS/APPLE/INUIT.TXT
'ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ' +
'ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł',
'x-mac-ce': // Python: 'mac_latin2'
'ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ' +
'ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ',
macintosh: // Python: 'mac_roman'
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
'x-mac-romanian': // Python: 'mac_romanian'
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ',
'x-mac-turkish': // Python: 'mac_turkish'
'ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø' +
'¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ'
};
/**
* Decodes an old-style Macintosh string. Returns either a Unicode JavaScript
* string, or 'undefined' if the encoding is unsupported. For example, we do
* not support Chinese, Japanese or Korean because these would need large
* mapping tables.
* @param {DataView} dataView
* @param {number} offset
* @param {number} dataLength
* @param {string} encoding
* @returns {string}
*/
decode.MACSTRING = function(dataView, offset, dataLength, encoding) {
var table = eightBitMacEncodings[encoding];
if (table === undefined) {
return undefined;
}
var result = '';
for (var i = 0; i < dataLength; i++) {
var c = dataView.getUint8(offset + i);
// In all eight-bit Mac encodings, the characters 0x00..0x7F are
// mapped to U+0000..U+007F; we only need to look up the others.
if (c <= 0x7F) {
result += String.fromCharCode(c);
} else {
result += table[c & 0x7F];
}
}
return result;
};
// Helper function for encode.MACSTRING. Returns a dictionary for mapping
// Unicode character codes to their 8-bit MacOS equivalent. This table
// is not exactly a super cheap data structure, but we do not care because
// encoding Macintosh strings is only rarely needed in typical applications.
var macEncodingTableCache = typeof WeakMap === 'function' && new WeakMap();
var macEncodingCacheKeys;
var getMacEncodingTable = function(encoding) {
// Since we use encoding as a cache key for WeakMap, it has to be
// a String object and not a literal. And at least on NodeJS 2.10.1,
// WeakMap requires that the same String instance is passed for cache hits.
if (!macEncodingCacheKeys) {
macEncodingCacheKeys = {};
for (var e in eightBitMacEncodings) {
/*jshint -W053 */ // Suppress "Do not use String as a constructor."
macEncodingCacheKeys[e] = new String(e);
}
}
var cacheKey = macEncodingCacheKeys[encoding];
if (cacheKey === undefined) {
return undefined;
}
// We can't do "if (cache.has(key)) {return cache.get(key)}" here:
// since garbage collection may run at any time, it could also kick in
// between the calls to cache.has() and cache.get(). In that case,
// we would return 'undefined' even though we do support the encoding.
if (macEncodingTableCache) {
var cachedTable = macEncodingTableCache.get(cacheKey);
if (cachedTable !== undefined) {
return cachedTable;
}
}
var decodingTable = eightBitMacEncodings[encoding];
if (decodingTable === undefined) {
return undefined;
}
var encodingTable = {};
for (var i = 0; i < decodingTable.length; i++) {
encodingTable[decodingTable.charCodeAt(i)] = i + 0x80;
}
if (macEncodingTableCache) {
macEncodingTableCache.set(cacheKey, encodingTable);
}
return encodingTable;
};
/**
* Encodes an old-style Macintosh string. Returns a byte array upon success.
* If the requested encoding is unsupported, or if the input string contains
* a character that cannot be expressed in the encoding, the function returns
* 'undefined'.
* @param {string} str
* @param {string} encoding
* @returns {Array}
*/
encode.MACSTRING = function(str, encoding) {
var table = getMacEncodingTable(encoding);
if (table === undefined) {
return undefined;
}
var result = [];
for (var i = 0; i < str.length; i++) {
var c = str.charCodeAt(i);
// In all eight-bit Mac encodings, the characters 0x00..0x7F are
// mapped to U+0000..U+007F; we only need to look up the others.
if (c >= 0x80) {
c = table[c];
if (c === undefined) {
// str contains a Unicode character that cannot be encoded
// in the requested encoding.
return undefined;
}
}
result[i] = c;
// result.push(c);
}
return result;
};
/**
* @param {string} str
* @param {string} encoding
* @returns {number}
*/
sizeOf.MACSTRING = function(str, encoding) {
var b = encode.MACSTRING(str, encoding);
if (b !== undefined) {
return b.length;
} else {
return 0;
}
};
// Convert a list of values to a CFF INDEX structure.
// The values should be objects containing name / type / value.
/**
* @param {Array} l
* @returns {Array}
*/
encode.INDEX = function(l) {
var i;
//var offset, offsets, offsetEncoder, encodedOffsets, encodedOffset, data,
// i, v;
// Because we have to know which data type to use to encode the offsets,
// we have to go through the values twice: once to encode the data and
// calculate the offets, then again to encode the offsets using the fitting data type.
var offset = 1; // First offset is always 1.
var offsets = [offset];
var data = [];
for (i = 0; i < l.length; i += 1) {
var v = encode.OBJECT(l[i]);
Array.prototype.push.apply(data, v);
offset += v.length;
offsets.push(offset);
}
if (data.length === 0) {
return [0, 0];
}
var encodedOffsets = [];
var offSize = (1 + Math.floor(Math.log(offset) / Math.log(2)) / 8) | 0;
var offsetEncoder = [undefined, encode.BYTE, encode.USHORT, encode.UINT24, encode.ULONG][offSize];
for (i = 0; i < offsets.length; i += 1) {
var encodedOffset = offsetEncoder(offsets[i]);
Array.prototype.push.apply(encodedOffsets, encodedOffset);
}
return Array.prototype.concat(encode.Card16(l.length),
encode.OffSize(offSize),
encodedOffsets,
data);
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.INDEX = function(v) {
return encode.INDEX(v).length;
};
/**
* Convert an object to a CFF DICT structure.
* The keys should be numeric.
* The values should be objects containing name / type / value.
* @param {Object} m
* @returns {Array}
*/
encode.DICT = function(m) {
var d = [];
var keys = Object.keys(m);
var length = keys.length;
for (var i = 0; i < length; i += 1) {
// Object.keys() return string keys, but our keys are always numeric.
var k = parseInt(keys[i], 0);
var v = m[k];
// Value comes before the key.
d = d.concat(encode.OPERAND(v.value, v.type));
d = d.concat(encode.OPERATOR(k));
}
return d;
};
/**
* @param {Object}
* @returns {number}
*/
sizeOf.DICT = function(m) {
return encode.DICT(m).length;
};
/**
* @param {number}
* @returns {Array}
*/
encode.OPERATOR = function(v) {
if (v < 1200) {
return [v];
} else {
return [12, v - 1200];
}
};
/**
* @param {Array} v
* @param {string}
* @returns {Array}
*/
encode.OPERAND = function(v, type) {
var d = [];
if (Array.isArray(type)) {
for (var i = 0; i < type.length; i += 1) {
check.argument(v.length === type.length, 'Not enough arguments given for type' + type);
d = d.concat(encode.OPERAND(v[i], type[i]));
}
} else {
if (type === 'SID') {
d = d.concat(encode.NUMBER(v));
} else if (type === 'offset') {
// We make it easy for ourselves and always encode offsets as
// 4 bytes. This makes offset calculation for the top dict easier.
d = d.concat(encode.NUMBER32(v));
} else if (type === 'number') {
d = d.concat(encode.NUMBER(v));
} else if (type === 'real') {
d = d.concat(encode.REAL(v));
} else {
throw new Error('Unknown operand type ' + type);
// FIXME Add support for booleans
}
}
return d;
};
encode.OP = encode.BYTE;
sizeOf.OP = sizeOf.BYTE;
// memoize charstring encoding using WeakMap if available
var wmm = typeof WeakMap === 'function' && new WeakMap();
/**
* Convert a list of CharString operations to bytes.
* @param {Array}
* @returns {Array}
*/
encode.CHARSTRING = function(ops) {
// See encode.MACSTRING for why we don't do "if (wmm && wmm.has(ops))".
if (wmm) {
var cachedValue = wmm.get(ops);
if (cachedValue !== undefined) {
return cachedValue;
}
}
var d = [];
var length = ops.length;
for (var i = 0; i < length; i += 1) {
var op = ops[i];
d = d.concat(encode[op.type](op.value));
}
if (wmm) {
wmm.set(ops, d);
}
return d;
};
/**
* @param {Array}
* @returns {number}
*/
sizeOf.CHARSTRING = function(ops) {
return encode.CHARSTRING(ops).length;
};
// Utility functions ////////////////////////////////////////////////////////
/**
* Convert an object containing name / type / value to bytes.
* @param {Object}
* @returns {Array}
*/
encode.OBJECT = function(v) {
var encodingFunction = encode[v.type];
check.argument(encodingFunction !== undefined, 'No encoding function for type ' + v.type);
return encodingFunction(v.value);
};
/**
* @param {Object}
* @returns {number}
*/
sizeOf.OBJECT = function(v) {
var sizeOfFunction = sizeOf[v.type];
check.argument(sizeOfFunction !== undefined, 'No sizeOf function for type ' + v.type);
return sizeOfFunction(v.value);
};
/**
* Convert a table object to bytes.
* A table contains a list of fields containing the metadata (name, type and default value).
* The table itself has the field values set as attributes.
* @param {opentype.Table}
* @returns {Array}
*/
encode.TABLE = function(table) {
var d = [];
var length = table.fields.length;
var subtables = [];
var subtableOffsets = [];
var i;
for (i = 0; i < length; i += 1) {
var field = table.fields[i];
var encodingFunction = encode[field.type];
check.argument(encodingFunction !== undefined, 'No encoding function for field type ' + field.type + ' (' + field.name + ')');
var value = table[field.name];
if (value === undefined) {
value = field.value;
}
var bytes = encodingFunction(value);
if (field.type === 'TABLE') {
subtableOffsets.push(d.length);
d = d.concat([0, 0]);
subtables.push(bytes);
} else {
d = d.concat(bytes);
}
}
for (i = 0; i < subtables.length; i += 1) {
var o = subtableOffsets[i];
var offset = d.length;
check.argument(offset < 65536, 'Table ' + table.tableName + ' too big.');
d[o] = offset >> 8;
d[o + 1] = offset & 0xff;
d = d.concat(subtables[i]);
}
return d;
};
/**
* @param {opentype.Table}
* @returns {number}
*/
sizeOf.TABLE = function(table) {
var numBytes = 0;
var length = table.fields.length;
for (var i = 0; i < length; i += 1) {
var field = table.fields[i];
var sizeOfFunction = sizeOf[field.type];
check.argument(sizeOfFunction !== undefined, 'No sizeOf function for field type ' + field.type + ' (' + field.name + ')');
var value = table[field.name];
if (value === undefined) {
value = field.value;
}
numBytes += sizeOfFunction(value);
// Subtables take 2 more bytes for offsets.
if (field.type === 'TABLE') {
numBytes += 2;
}
}
return numBytes;
};
encode.RECORD = encode.TABLE;
sizeOf.RECORD = sizeOf.TABLE;
// Merge in a list of bytes.
encode.LITERAL = function(v) {
return v;
};
sizeOf.LITERAL = function(v) {
return v.length;
};
exports.decode = decode;
exports.encode = encode;
exports.sizeOf = sizeOf;
},{"./check":2}],33:[function(require,module,exports){
'use strict';
exports.isBrowser = function() {
return typeof window !== 'undefined';
};
exports.isNode = function() {
return typeof window === 'undefined';
};
exports.nodeBufferToArrayBuffer = function(buffer) {
var ab = new ArrayBuffer(buffer.length);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
view[i] = buffer[i];
}
return ab;
};
exports.arrayBufferToNodeBuffer = function(ab) {
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
};
exports.checkArgument = function(expression, message) {
if (!expression) {
throw message;
}
};
},{}]},{},[9])(9)
}); | joeyparrish/cdnjs | ajax/libs/opentype.js/0.6.7/opentype.js | JavaScript | mit | 295,992 |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.test.models;
/**
* Simple function interface with a varargs SAM method.
*/
@FunctionalInterface
public interface VarArgConsumer {
public void apply(Object... o);
}
| FauxFaux/jdk9-nashorn | test/src/jdk/nashorn/test/models/VarArgConsumer.java | Java | gpl-2.0 | 1,400 |
import { onBlur } from "../display/focus"
import { setGuttersForLineNumbers, updateGutters } from "../display/gutters"
import { alignHorizontally } from "../display/line_numbers"
import { loadMode, resetModeState } from "../display/mode_state"
import { initScrollbars, updateScrollbars } from "../display/scrollbars"
import { updateSelection } from "../display/selection"
import { regChange } from "../display/view_tracking"
import { getKeyMap } from "../input/keymap"
import { defaultSpecialCharPlaceholder } from "../line/line_data"
import { Pos } from "../line/pos"
import { findMaxLine } from "../line/spans"
import { clearCaches, compensateForHScroll, estimateLineHeights } from "../measurement/position_measurement"
import { replaceRange } from "../model/changes"
import { mobile, windows } from "../util/browser"
import { addClass, rmClass } from "../util/dom"
import { off, on } from "../util/event"
import { themeChanged } from "./utils"
export let Init = {toString: function(){return "CodeMirror.Init"}}
export let defaults = {}
export let optionHandlers = {}
export function defineOptions(CodeMirror) {
let optionHandlers = CodeMirror.optionHandlers
function option(name, deflt, handle, notOnInit) {
CodeMirror.defaults[name] = deflt
if (handle) optionHandlers[name] =
notOnInit ? (cm, val, old) => {if (old != Init) handle(cm, val, old)} : handle
}
CodeMirror.defineOption = option
// Passed to option handlers when there is no old value.
CodeMirror.Init = Init
// These two are, on init, called from the constructor because they
// have to be initialized before the editor can start at all.
option("value", "", (cm, val) => cm.setValue(val), true)
option("mode", null, (cm, val) => {
cm.doc.modeOption = val
loadMode(cm)
}, true)
option("indentUnit", 2, loadMode, true)
option("indentWithTabs", false)
option("smartIndent", true)
option("tabSize", 4, cm => {
resetModeState(cm)
clearCaches(cm)
regChange(cm)
}, true)
option("lineSeparator", null, (cm, val) => {
cm.doc.lineSep = val
if (!val) return
let newBreaks = [], lineNo = cm.doc.first
cm.doc.iter(line => {
for (let pos = 0;;) {
let found = line.text.indexOf(val, pos)
if (found == -1) break
pos = found + val.length
newBreaks.push(Pos(lineNo, found))
}
lineNo++
})
for (let i = newBreaks.length - 1; i >= 0; i--)
replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
})
option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, (cm, val, old) => {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g")
if (old != Init) cm.refresh()
})
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, cm => cm.refresh(), true)
option("electricChars", true)
option("inputStyle", mobile ? "contenteditable" : "textarea", () => {
throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
}, true)
option("spellcheck", false, (cm, val) => cm.getInputField().spellcheck = val, true)
option("rtlMoveVisually", !windows)
option("wholeLineUpdateBefore", true)
option("theme", "default", cm => {
themeChanged(cm)
guttersChanged(cm)
}, true)
option("keyMap", "default", (cm, val, old) => {
let next = getKeyMap(val)
let prev = old != Init && getKeyMap(old)
if (prev && prev.detach) prev.detach(cm, next)
if (next.attach) next.attach(cm, prev || null)
})
option("extraKeys", null)
option("configureMouse", null)
option("lineWrapping", false, wrappingChanged, true)
option("gutters", [], cm => {
setGuttersForLineNumbers(cm.options)
guttersChanged(cm)
}, true)
option("fixedGutter", true, (cm, val) => {
cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"
cm.refresh()
}, true)
option("coverGutterNextToScrollbar", false, cm => updateScrollbars(cm), true)
option("scrollbarStyle", "native", cm => {
initScrollbars(cm)
updateScrollbars(cm)
cm.display.scrollbars.setScrollTop(cm.doc.scrollTop)
cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)
}, true)
option("lineNumbers", false, cm => {
setGuttersForLineNumbers(cm.options)
guttersChanged(cm)
}, true)
option("firstLineNumber", 1, guttersChanged, true)
option("lineNumberFormatter", integer => integer, guttersChanged, true)
option("showCursorWhenSelecting", false, updateSelection, true)
option("resetSelectionOnContextMenu", true)
option("lineWiseCopyCut", true)
option("pasteLinesPerSelection", true)
option("readOnly", false, (cm, val) => {
if (val == "nocursor") {
onBlur(cm)
cm.display.input.blur()
}
cm.display.input.readOnlyChanged(val)
})
option("disableInput", false, (cm, val) => {if (!val) cm.display.input.reset()}, true)
option("dragDrop", true, dragDropChanged)
option("allowDropFileTypes", null)
option("cursorBlinkRate", 530)
option("cursorScrollMargin", 0)
option("cursorHeight", 1, updateSelection, true)
option("singleCursorHeightPerLine", true, updateSelection, true)
option("workTime", 100)
option("workDelay", 100)
option("flattenSpans", true, resetModeState, true)
option("addModeClass", false, resetModeState, true)
option("pollInterval", 100)
option("undoDepth", 200, (cm, val) => cm.doc.history.undoDepth = val)
option("historyEventDelay", 1250)
option("viewportMargin", 10, cm => cm.refresh(), true)
option("maxHighlightLength", 10000, resetModeState, true)
option("moveInputWithCursor", true, (cm, val) => {
if (!val) cm.display.input.resetPosition()
})
option("tabindex", null, (cm, val) => cm.display.input.getField().tabIndex = val || "")
option("autofocus", null)
option("direction", "ltr", (cm, val) => cm.doc.setDirection(val), true)
}
function guttersChanged(cm) {
updateGutters(cm)
regChange(cm)
alignHorizontally(cm)
}
function dragDropChanged(cm, value, old) {
let wasOn = old && old != Init
if (!value != !wasOn) {
let funcs = cm.display.dragFunctions
let toggle = value ? on : off
toggle(cm.display.scroller, "dragstart", funcs.start)
toggle(cm.display.scroller, "dragenter", funcs.enter)
toggle(cm.display.scroller, "dragover", funcs.over)
toggle(cm.display.scroller, "dragleave", funcs.leave)
toggle(cm.display.scroller, "drop", funcs.drop)
}
}
function wrappingChanged(cm) {
if (cm.options.lineWrapping) {
addClass(cm.display.wrapper, "CodeMirror-wrap")
cm.display.sizer.style.minWidth = ""
cm.display.sizerWidth = null
} else {
rmClass(cm.display.wrapper, "CodeMirror-wrap")
findMaxLine(cm)
}
estimateLineHeights(cm)
regChange(cm)
clearCaches(cm)
setTimeout(() => updateScrollbars(cm), 100)
}
| AfrikaBurn/Main | web/libraries/codemirror/src/edit/options.js | JavaScript | gpl-2.0 | 6,874 |
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Serbian (Cyrillic) language.
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang[ 'sr' ] = {
// ARIA description.
editor: 'Rich Text Editor', // MISSING
editorPanel: 'Rich Text Editor panel', // MISSING
// Common messages and labels.
common: {
// Screenreader titles. Please note that screenreaders are not always capable
// of reading non-English words. So be careful while translating it.
editorHelp: 'Press ALT 0 for help', // MISSING
browseServer: 'Претражи сервер',
url: 'УРЛ',
protocol: 'Протокол',
upload: 'Пошаљи',
uploadSubmit: 'Пошаљи на сервер',
image: 'Слика',
flash: 'Флеш елемент',
form: 'Форма',
checkbox: 'Поље за потврду',
radio: 'Радио-дугме',
textField: 'Текстуално поље',
textarea: 'Зона текста',
hiddenField: 'Скривено поље',
button: 'Дугме',
select: 'Изборно поље',
imageButton: 'Дугме са сликом',
notSet: '<није постављено>',
id: 'Ид',
name: 'Назив',
langDir: 'Смер језика',
langDirLtr: 'С лева на десно (LTR)',
langDirRtl: 'С десна на лево (RTL)',
langCode: 'Kôд језика',
longDescr: 'Пун опис УРЛ',
cssClass: 'Stylesheet класе',
advisoryTitle: 'Advisory наслов',
cssStyle: 'Стил',
ok: 'OK',
cancel: 'Oткажи',
close: 'Затвори',
preview: 'Изглед странице',
resize: 'Resize', // MISSING
generalTab: 'Опште',
advancedTab: 'Напредни тагови',
validateNumberFailed: 'Ова вредност није цигра.',
confirmNewPage: 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING
confirmCancel: 'You have changed some options. Are you sure you want to close the dialog window?', // MISSING
options: 'Опције',
target: 'Meтa',
targetNew: 'New Window (_blank)', // MISSING
targetTop: 'Topmost Window (_top)', // MISSING
targetSelf: 'Same Window (_self)', // MISSING
targetParent: 'Parent Window (_parent)', // MISSING
langDirLTR: 'С лева на десно (LTR)',
langDirRTL: 'С десна на лево (RTL)',
styles: 'Стил',
cssClasses: 'Stylesheet класе',
width: 'Ширина',
height: 'Висина',
align: 'Равнање',
alignLeft: 'Лево',
alignRight: 'Десно',
alignCenter: 'Средина',
alignJustify: 'Обострано равнање',
alignTop: 'Врх',
alignMiddle: 'Средина',
alignBottom: 'Доле',
alignNone: 'None', // MISSING
invalidValue : 'Invalid value.', // MISSING
invalidHeight: 'Height must be a number.', // MISSING
invalidWidth: 'Width must be a number.', // MISSING
invalidCssLength: 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING
invalidHtmlLength: 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING
invalidInlineStyle: 'Value specified for the inline style must consist of one or more tuples with the format of "name : value", separated by semi-colons.', // MISSING
cssLengthTooltip: 'Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING
// Put the voice-only part of the label in the span.
unavailable: '%1<span class="cke_accessibility">, unavailable</span>' // MISSING
}
};
| noskill/Firesoft | src/main/webapp/ckeditor/lang/sr.js | JavaScript | gpl-3.0 | 3,935 |
/*
* DarkTooltip v0.4.0
* Simple customizable tooltip with confirm option and 3d effects
* (c)2014 Rubén Torres - rubentdlh@gmail.com
* Released under the MIT license
*/
(function($) {
function DarkTooltip(element, options){
this.bearer = element;
this.options = options;
this.hideEvent;
this.mouseOverMode=(this.options.trigger == "hover" || this.options.trigger == "mouseover" || this.options.trigger == "onmouseover");
}
DarkTooltip.prototype = {
show: function(){
var dt = this;
if(this.options.modal){
this.modalLayer.css('display', 'block');
}
//Close all other tooltips
this.tooltip.css('display', 'block');
//Set event to prevent tooltip from closig when mouse is over the tooltip
if(dt.mouseOverMode){
this.tooltip.mouseover( function(){
clearTimeout(dt.hideEvent);
});
this.tooltip.mouseout( function(){
clearTimeout(dt.hideEvent);
dt.hide();
});
}
},
hide: function(){
var dt=this;
this.hideEvent = setTimeout( function(){
dt.tooltip.hide();
}, 100);
if(dt.options.modal){
dt.modalLayer.hide();
}
this.options.onClose();
},
toggle: function(){
if(this.tooltip.is(":visible")){
this.hide();
}else{
this.show();
}
},
addAnimation: function(){
switch(this.options.animation){
case 'none':
break;
case 'fadeIn':
this.tooltip.addClass('animated');
this.tooltip.addClass('fadeIn');
break;
case 'flipIn':
this.tooltip.addClass('animated');
this.tooltip.addClass('flipIn');
break;
}
},
setContent: function(){
$(this.bearer).css('cursor', 'pointer');
//Get tooltip content
if(this.options.content){
this.content = this.options.content;
}else if(this.bearer.attr("data-tooltip")){
this.content = this.bearer.attr("data-tooltip");
}else{
// console.log("No content for tooltip: " + this.bearer.selector);
return;
}
if(this.content.charAt(0) == '#'){
if (this.options.delete_content){
var content = $(this.content).html();
$(this.content).html('');
this.content = content;
delete content;
}
else{
$(this.content).hide();
this.content = $(this.content).html();
}
this.contentType='html';
}else{
this.contentType='text';
}
tooltipId = "";
if(this.bearer.attr("id") != ""){
tooltipId = "id='darktooltip-" + this.bearer.attr("id") + "'";
}
//Create modal layer
this.modalLayer = $("<ins class='darktooltip-modal-layer'></ins>");
//Create tooltip container
this.tooltip = $("<ins " + tooltipId + " class = 'dark-tooltip " + this.options.theme + " " + this.options.size + " "
+ this.options.gravity + "'><div>" + this.content + "</div><div class = 'tip'></div></ins>");
this.tip = this.tooltip.find(".tip");
$("body").append(this.modalLayer);
$("body").append(this.tooltip);
//Adjust size for html tooltip
if(this.contentType == 'html'){
this.tooltip.css('max-width','none');
}
this.tooltip.css('opacity', this.options.opacity);
this.addAnimation();
if(this.options.confirm){
this.addConfirm();
}
},
setPositions: function(){
var leftPos = this.bearer.offset().left;
var topPos = this.bearer.offset().top;
switch(this.options.gravity){
case 'south':
leftPos += this.bearer.outerWidth()/2 - this.tooltip.outerWidth()/2;
topPos += -this.tooltip.outerHeight() - this.tip.outerHeight()/2;
break;
case 'west':
leftPos += this.bearer.outerWidth() + this.tip.outerWidth()/2;
topPos += this.bearer.outerHeight()/2 - (this.tooltip.outerHeight()/2);
break;
case 'north':
leftPos += this.bearer.outerWidth()/2 - (this.tooltip.outerWidth()/2);
topPos += this.bearer.outerHeight() + this.tip.outerHeight()/2;
break;
case 'east':
leftPos += -this.tooltip.outerWidth() - this.tip.outerWidth()/2;
topPos += this.bearer.outerHeight()/2 - this.tooltip.outerHeight()/2;
break;
}
if(this.options.autoLeft){
this.tooltip.css('left', leftPos);
}
if(this.options.autoTop){
this.tooltip.css('top', topPos);
}
},
setEvents: function(){
var dt = this;
var delay = dt.options.hoverDelay;
var setTimeoutConst;
if(dt.mouseOverMode){
this.bearer.mouseenter( function(){
//Timeout for hover mouse delay
setTimeoutConst = setTimeout( function(){
dt.setPositions();
dt.show();
}, delay);
}).mouseleave( function(){
clearTimeout(setTimeoutConst );
dt.hide();
});
}else if(this.options.trigger == "click" || this.options.trigger == "onclik"){
this.tooltip.click( function(e){
e.stopPropagation();
});
this.bearer.click( function(e){
e.preventDefault();
dt.setPositions();
dt.toggle();
e.stopPropagation();
});
$('html').click(function(){
dt.hide();
})
}
},
activate: function(){
this.setContent();
if(this.content){
this.setEvents();
}
},
addConfirm: function(){
this.tooltip.append("<ul class = 'confirm'><li class = 'darktooltip-yes'>"
+ this.options.yes +"</li><li class = 'darktooltip-no'>"+ this.options.no +"</li></ul>");
this.setConfirmEvents();
},
setConfirmEvents: function(){
var dt = this;
this.tooltip.find('li.darktooltip-yes').click( function(e){
dt.onYes();
e.stopPropagation();
});
this.tooltip.find('li.darktooltip-no').click( function(e){
dt.onNo();
e.stopPropagation();
});
},
finalMessage: function(){
if(this.options.finalMessage){
var dt = this;
dt.tooltip.find('div:first').html(this.options.finalMessage);
dt.tooltip.find('ul').remove();
dt.setPositions();
setTimeout( function(){
dt.hide();
dt.setContent();
}, dt.options.finalMessageDuration);
}else{
this.hide();
}
},
onYes: function(){
this.options.onYes(this.bearer);
this.finalMessage();
},
onNo: function(){
this.options.onNo(this.bearer);
this.hide();
}
}
$.fn.darkTooltip = function(options) {
return this.each(function(){
options = $.extend({}, $.fn.darkTooltip.defaults, options);
var tooltip = new DarkTooltip($(this), options);
tooltip.activate();
});
}
$.fn.darkTooltip.defaults = {
animation: 'none',
confirm: false,
content:'',
finalMessage: '',
finalMessageDuration: 1000,
gravity: 'south',
hoverDelay: 0,
modal: false,
no: 'No',
onNo: function(){},
onYes: function(){},
opacity: 0.9,
size: 'medium',
theme: 'dark',
trigger: 'hover',
yes: 'Yes',
autoTop: true,
autoLeft: true,
onClose: function(){}
};
})(jQuery);
| gtison/kf | src/main/resources/static/js/jquery.darktooltip.js | JavaScript | apache-2.0 | 6,675 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.regionserver.compactions;
import java.util.List;
import org.apache.hadoop.hbase.regionserver.StoreFile;
public abstract class StoreFileListGenerator
extends MockStoreFileGenerator implements Iterable<List<StoreFile>> {
public static final int MAX_FILE_GEN_ITERS = 10;
public static final int NUM_FILES_GEN = 1000;
StoreFileListGenerator(final Class klass) {
super(klass);
}
}
| Guavus/hbase | hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/compactions/StoreFileListGenerator.java | Java | apache-2.0 | 1,237 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.schema.validation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.nifi.serialization.record.validation.SchemaValidationResult;
import org.apache.nifi.serialization.record.validation.ValidationError;
public class StandardSchemaValidationResult implements SchemaValidationResult {
private final List<ValidationError> validationErrors = new ArrayList<>();
@Override
public boolean isValid() {
return validationErrors.isEmpty();
}
@Override
public Collection<ValidationError> getValidationErrors() {
return Collections.unmodifiableList(validationErrors);
}
public void addValidationError(final ValidationError validationError) {
this.validationErrors.add(validationError);
}
}
| mcgilman/nifi | nifi-nar-bundles/nifi-extension-utils/nifi-record-utils/nifi-standard-record-utils/src/main/java/org/apache/nifi/schema/validation/StandardSchemaValidationResult.java | Java | apache-2.0 | 1,648 |
import * as Boom from '@hapi/boom';
import * as http from 'http';
import * as https from 'https';
export interface Host {
name: string;
port: number;
}
export interface CustomRequest {
authorization: string;
contentType: string;
host: string;
method: string;
port: number;
url: string;
}
export interface ParseRequestOptions {
host?: string | undefined;
hostHeaderName?: string | undefined;
name?: string | undefined;
port?: number | undefined;
}
export const version: string;
export const limits: {
/** Limit the length of uris and headers to avoid a DoS attack on string matching */
maxMatchLength: number;
};
export function now(localtimeOffsetMsec: number): number;
export function nowSecs(localtimeOffsetMsec: number): number;
export function parseAuthorizationHeader(header: string, keys?: string[]): Record<string, string>;
export function parseContentType(header?: string): string;
export function parseHost(req: http.RequestOptions | https.RequestOptions, hostHeaderName?: string): Host | null;
export function parseRequest(
req: http.RequestOptions | https.RequestOptions,
options?: ParseRequestOptions,
): CustomRequest;
export function unauthorized(
message?: string,
attributes?: string | Boom.unauthorized.Attributes,
): Boom.Boom & Boom.unauthorized.MissingAuth;
| markogresak/DefinitelyTyped | types/hawk/lib/utils.d.ts | TypeScript | mit | 1,362 |
/*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
public class X11CNS11643P2 extends X11CNS11643 {
public X11CNS11643P2() {
super(2, "X11CNS11643P2");
}
}
| rokn/Count_Words_2015 | testing/openjdk/jdk/test/sun/nio/cs/X11CNS11643P2.java | Java | mit | 1,335 |
package builder
import (
"os"
"github.com/spf13/cobra"
kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"github.com/openshift/origin/pkg/build/builder/cmd"
ocmd "github.com/openshift/origin/pkg/cmd/cli/cmd"
"github.com/openshift/origin/pkg/cmd/templates"
)
var (
s2iBuilderLong = templates.LongDesc(`
Perform a Source-to-Image build
This command executes a Source-to-Image build using arguments passed via the environment.
It expects to be run inside of a container.`)
dockerBuilderLong = templates.LongDesc(`
Perform a Docker build
This command executes a Docker build using arguments passed via the environment.
It expects to be run inside of a container.`)
)
// NewCommandS2IBuilder provides a CLI handler for S2I build type
func NewCommandS2IBuilder(name string) *cobra.Command {
cmd := &cobra.Command{
Use: name,
Short: "Run a Source-to-Image build",
Long: s2iBuilderLong,
Run: func(c *cobra.Command, args []string) {
err := cmd.RunS2IBuild(c.OutOrStderr())
kcmdutil.CheckErr(err)
},
}
cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{}))
return cmd
}
// NewCommandDockerBuilder provides a CLI handler for Docker build type
func NewCommandDockerBuilder(name string) *cobra.Command {
cmd := &cobra.Command{
Use: name,
Short: "Run a Docker build",
Long: dockerBuilderLong,
Run: func(c *cobra.Command, args []string) {
err := cmd.RunDockerBuild(c.OutOrStderr())
kcmdutil.CheckErr(err)
},
}
cmd.AddCommand(ocmd.NewCmdVersion(name, nil, os.Stdout, ocmd.VersionOptions{}))
return cmd
}
| rawlingsj/gofabric8 | vendor/github.com/openshift/origin/pkg/cmd/infra/builder/builder.go | GO | apache-2.0 | 1,590 |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading;
namespace QuantConnect.Util
{
/// <summary>
/// Provides extension methods to make working with the <see cref="ReaderWriterLockSlim"/> class easier
/// </summary>
public static class ReaderWriterLockSlimExtensions
{
/// <summary>
/// Opens the read lock
/// </summary>
/// <param name="readerWriterLockSlim">The lock to open for read</param>
/// <returns>A disposable reference which will release the lock upon disposal</returns>
public static IDisposable Read(this ReaderWriterLockSlim readerWriterLockSlim)
{
return new ReaderLockToken(readerWriterLockSlim);
}
/// <summary>
/// Opens the write lock
/// </summary>
/// <param name="readerWriterLockSlim">The lock to open for write</param>
/// <returns>A disposale reference which will release thelock upon disposal</returns>
public static IDisposable Write(this ReaderWriterLockSlim readerWriterLockSlim)
{
return new WriteLockToken(readerWriterLockSlim);
}
private sealed class ReaderLockToken : ReaderWriterLockSlimToken
{
public ReaderLockToken(ReaderWriterLockSlim readerWriterLockSlim)
: base(readerWriterLockSlim)
{
}
protected override void EnterLock(ReaderWriterLockSlim readerWriterLockSlim)
{
readerWriterLockSlim.EnterReadLock();
}
protected override void ExitLock(ReaderWriterLockSlim readerWriterLockSlim)
{
readerWriterLockSlim.ExitReadLock();
}
}
private sealed class WriteLockToken : ReaderWriterLockSlimToken
{
public WriteLockToken(ReaderWriterLockSlim readerWriterLockSlim)
: base(readerWriterLockSlim)
{
}
protected override void EnterLock(ReaderWriterLockSlim readerWriterLockSlim)
{
readerWriterLockSlim.EnterWriteLock();
}
protected override void ExitLock(ReaderWriterLockSlim readerWriterLockSlim)
{
readerWriterLockSlim.ExitWriteLock();
}
}
private abstract class ReaderWriterLockSlimToken : IDisposable
{
private ReaderWriterLockSlim _readerWriterLockSlim;
public ReaderWriterLockSlimToken(ReaderWriterLockSlim readerWriterLockSlim)
{
_readerWriterLockSlim = readerWriterLockSlim;
// ReSharper disable once DoNotCallOverridableMethodsInConstructor -- we control the subclasses, this is fine
EnterLock(_readerWriterLockSlim);
}
protected abstract void EnterLock(ReaderWriterLockSlim readerWriterLockSlim);
protected abstract void ExitLock(ReaderWriterLockSlim readerWriterLockSlim);
public void Dispose()
{
if (_readerWriterLockSlim != null)
{
ExitLock(_readerWriterLockSlim);
_readerWriterLockSlim = null;
}
}
}
}
}
| young-zhang/Lean | Common/Util/ReaderWriterLockSlimExtensions.cs | C# | apache-2.0 | 3,963 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq.Expressions;
namespace System.Dynamic
{
/// <summary>
/// Represents a dynamic object, that can have its operations bound at runtime.
/// </summary>
/// <remarks>
/// Objects that want to participate in the binding process should implement an IDynamicMetaObjectProvider interface,
/// and implement <see cref="IDynamicMetaObjectProvider.GetMetaObject" /> to return a <see cref="DynamicMetaObject" />.
/// </remarks>
public interface IDynamicMetaObjectProvider
{
/// <summary>
/// Returns the <see cref="DynamicMetaObject" /> responsible for binding operations performed on this object.
/// </summary>
/// <param name="parameter">The expression tree representation of the runtime value.</param>
/// <returns>The <see cref="DynamicMetaObject" /> to bind this object.</returns>
DynamicMetaObject GetMetaObject(Expression parameter);
}
}
| iamjasonp/corefx | src/System.Dynamic.Runtime/src/System/Dynamic/IDynamicMetaObjectProvider.cs | C# | mit | 1,145 |
// tslint:disable:no-unnecessary-generics
import { ComponentType } from 'react';
import { EditorColor } from '../../';
declare namespace withColorContext {
interface Props {
colors: EditorColor[];
disableCustomColors: boolean;
hasColorsToChoose: boolean;
}
}
// prettier-ignore
declare function withColorContext<
ProvidedProps extends Partial<withColorContext.Props>,
OwnProps extends any = any,
T extends ComponentType<ProvidedProps & OwnProps> = ComponentType<ProvidedProps & OwnProps>
>(component: T):
T extends ComponentType<infer U> ? ComponentType<
Omit<U, 'colors' | 'disableCustomColors' | 'hasColorsToChoose'> &
Omit<ProvidedProps, 'hasColorsToChoose'>> :
never;
export default withColorContext;
| markogresak/DefinitelyTyped | types/wordpress__block-editor/components/color-palette/with-color-context.d.ts | TypeScript | mit | 777 |
<?php
/* $Id$ */
/**
* translated by: Pietro Danesi <danone at users.sourceforge.net> 2002-03-29
* Revised by: "DPhantom" <dphantom at users.sourceforge.net> 2002-04-16
* Revised by: "Luca Rebellato" <rebeluca at users.sourceforge.net> 2007-07-26
*/
$charset = 'iso-8859-1';
$text_dir = 'ltr';
$number_thousands_separator = '.';
$number_decimal_separator = ',';
// shortcuts for Byte, Kilo, Mega, Giga, Tera, Peta, Exa
$byteUnits = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB');
$day_of_week = array('Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'); //italian days
$month = array('Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'); //italian months
// See http://www.php.net/manual/en/function.strftime.php to define the
// variable below
$datefmt = '%d %B, %Y at %I:%M %p'; //italian time
$timespanfmt = '%s giorni, %s ore, %s minuti e %s secondi';
$strAbortedClients = 'Fallito';
$strAccessDenied = 'Accesso negato';
$strAccessDeniedCreateConfig = 'La ragione di questo è che probabilmente non hai creato alcun file di configurazione. Potresti voler usare %1$ssetup script%2$s per crearne uno.';
$strAccessDeniedExplanation = 'phpMyAdmin ha provato a connettersi al server MySQL, e il server ha rifiutato la connessione. Si dovrebbe controllare il nome dell\'host, l\'username e la password nel file config.inc.php ed assicurarsi che corrispondano alle informazioni fornite dall\'amministratore del server MySQL.';
$strAction = 'Azione';
$strAddAutoIncrement = 'Aggiungi valore AUTO_INCREMENT';
$strAddClause = 'Aggiungi %s';
$strAddConstraints = 'Aggiungi vincoli';
$strAddDeleteColumn = 'Aggiungi/Cancella campo';
$strAddDeleteRow = 'Aggiungi/Cancella criterio';
$strAddFields = 'Aggiungi %s campo(i)';
$strAddHeaderComment = 'Aggiunge un commento personalizzato all\'header (\\n per tornare a capo)';
$strAddIntoComments = 'Aggiungi nei commenti';
$strAddNewField = 'Aggiungi un nuovo campo';
$strAddPrivilegesOnDb = 'Aggiungi privilegi sul seguente database';
$strAddPrivilegesOnTbl = 'Aggiungi privilegi sulla seguente tabella';
$strAddSearchConditions = 'Aggiungi condizioni di ricerca (corpo della clausola "where"):';
$strAddToIndex = 'Aggiungi all\'indice %s colonna/e';
$strAddUser = 'Aggiungi un nuovo utente';
$strAddUserMessage = 'Hai aggiunto un nuovo utente.';
$strAdministration = 'Amministrazione';
$strAffectedRows = 'Righe interessate:';
$strAfter = 'Dopo %s';
$strAfterInsertBack = 'Indietro';
$strAfterInsertNewInsert = 'Inserisci un nuovo record';
$strAfterInsertNext = 'Modifica il record successivo';
$strAfterInsertSame = 'Torna a questa pagina';
$strAllowInterrupt = 'Permette di interrompere il processo di importazione nel caso lo script rilevi che è troppo vicino al tempo limite. Questo potrebbe essere un buon modo di importare grandi file, tuttavia potrebbe interrompere la transazione.';
$strAllTableSameWidth = 'mostra tutte le Tabelle con la stessa larghezza?';
$strAll = 'Tutti';
$strAlterOrderBy = 'Altera tabella ordinata per';
$strAnalyzeTable = 'Analizza tabella';
$strAnd = 'e';
$strAndThen = 'e quindi';
$strAngularLinks = 'Link angolari';
$strAnIndex = 'Un indice è stato aggiunto in %s';
$strAnyHost = 'Qualsiasi host';
$strAny = 'Qualsiasi';
$strAnyUser = 'Qualsiasi utente';
$strApproximateCount = 'Può essere approssimato. Vedere FAQ 3.11';
$strAPrimaryKey = 'Una chiave primaria è stata aggiunta in %s';
$strArabic = 'Arabo';
$strArmenian = 'Armeno';
$strAscending = 'Crescente';
$strAtBeginningOfTable = 'All\'inizio della tabella';
$strAtEndOfTable = 'Alla fine della tabella';
$strAttr = 'Attributi';
$strAutomaticLayout = 'Impaginazione automatica';
$strBack = 'Indietro';
$strBaltic = 'Baltico';
$strBeginCut = 'INIZIO CUT';
$strBeginRaw = 'INIZIO RAW';
$strBinary = 'Binario';
$strBinaryDoNotEdit = 'Tipo di dato Binario - non modificare';
$strBinaryLog = 'Log binario';
$strBinLogEventType = 'Tipo di evento';
$strBinLogInfo = 'Informazioni';
$strBinLogName = 'Nome del Log';
$strBinLogOriginalPosition = 'Posizione originale';
$strBinLogPosition = 'Posizione';
$strBinLogServerId = 'ID del server';
$strBookmarkAllUsers = 'Permetti ad ogni utente di accedere a questo bookmark';
$strBookmarkCreated = 'Segnalibro %s creato';
$strBookmarkDeleted = 'Il bookmark è stato cancellato.';
$strBookmarkLabel = 'Etichetta';
$strBookmarkQuery = 'Query SQL aggiunte ai preferiti';
$strBookmarkReplace = 'Sostituzione dei segnalibri esistenti con lo stesso nome';
$strBookmarkThis = 'Aggiungi ai preferiti questa query SQL';
$strBookmarkView = 'Visualizza solo';
$strBrowseDistinctValues = 'Naviga tra i valori DISTINCT';
$strBrowseForeignValues = 'Sfoglia le opzioni straniere';
$strBrowse = 'Mostra';
$strBufferPoolActivity = 'Attività del Buffer Pool';
$strBufferPool = 'Buffer Pool';
$strBufferPoolUsage = 'Utilizzo del Buffer Pool';
$strBufferReadMissesInPercent = 'Non letto in %';
$strBufferReadMisses = 'Non letto';
$strBufferWriteWaits = 'In attesa di scrittura';
$strBufferWriteWaitsInPercent = 'In attesa di scrittura in %';
$strBulgarian = 'Bulgaro';
$strBusyPages = 'Pagine occupate';
$strBzError = 'phpMyAdmin non è capace di comprimere il dump a causa dell\'estensione Bz2 errata in questa versione di PHP. Vi raccomandiamo vivamente di settare il parametro <code>$cfg[\'BZipDump\']</code> nel vostro file di configurazione di phpMyAdmin a <code>FALSE</code>. Se volete utilizzare le capacità di compressione Bz2, dovreste aggiornare il PHP all\'ultima versione. Date un\'occhiata al bug report %s per uteriori dettagli.';
$strBzip = '"compresso con bzip2"';
$strCalendar = 'Calendario';
$strCancel = 'Annulla';
$strCanNotLoadExportPlugins = 'Non posso caricare i plugins di esportazione. Controlla l\'installazione!';
$strCanNotLoadImportPlugins = 'Non posso caricare i plugins di importazione, controlla la tua configurazione!';
$strCannotLogin = 'Impossibile eseguire il login nel server MySQL';
$strCantLoad = 'Impossibile caricare l\'estensione %s,<br />prego controllare la configurazione di PHP';
$strCantLoadRecodeIconv = 'Impossibile caricare l\'estensione iconv o recode necessaria per la conversione del set di caratteri, configurare il PHP per permettere di utilizzare queste estenzioni o disabilitare la conversione dei set di caratteri in phpMyAdmin.';
$strCantRenameIdxToPrimary = 'Impossibile rinominare l\'indice a PRIMARIO!';
$strCantUseRecodeIconv = 'Impossibile utilizzare le funzioni iconv o libiconv o recode_string in quanto l\'estensione deve essere caricata. Controllare la configurazione del PHP.';
$strCardinality = 'Cardinalità';
$strCaseInsensitive = 'case-insensitive';
$strCaseSensitive = 'case-sensitive';
$strCentralEuropean = 'Europeo Centrale';
$strChangeCopyModeCopy = '... mantieni quello vecchio.';
$strChangeCopyMode = 'Crea un nuovo utente con gli stessi privilegi e ...';
$strChangeCopyModeDeleteAndReload = ' ... cancella quello vecchio dalla tabella degli utenti e in seguito ricarica i privilegi.';
$strChangeCopyModeJustDelete = ' ... cancella quello vecchio dalla tabella degli utenti.';
$strChangeCopyModeRevoke = ' ... revoca tutti i privilegi attivi da quello vecchio e in seguito cancellalo.';
$strChangeCopyUser = 'Cambia le Informazioni di Login / Copia Utente';
$strChangeDisplay = 'Scegli il campo da mostrare';
$strChange = 'Modifica';
$strChangePassword = 'Cambia password';
$strCharsetOfFile = 'Set di caratteri del file:';
$strCharsetsAndCollations = 'Set di Caratteri e Collations';
$strCharset = 'Set di caratteri';
$strCharsets = 'Set di caratteri';
$strCheckAll = 'Seleziona tutti';
$strCheckOverhead = 'Controllo addizionale';
$strCheckPrivs = 'Controlla i privilegi';
$strCheckPrivsLong = 'Controlla i privilegi per il database "%s".';
$strCheckTable = 'Controlla tabella';
$strChoosePage = 'Prego scegliere una Page da modificare';
$strColComFeat = 'Visualizzazione commenti delle colonne';
$strCollation = 'Collation';
$strColumnNames = 'Nomi delle colonne';
$strColumnPrivileges = 'Privilegi relativi alle colonne';
$strCommand = 'Comando';
$strComments = 'Commenti';
$strCommentsForTable = 'Commenti per la tabella';
$strCompatibleHashing = 'Compatibile con MySQL 4.0';
$strCompleteInserts = 'Inserimenti completi';
$strCompression = 'Compressione';
$strCompressionWillBeDetected = 'Il tipo di compressione del file importato sarà automaticamente rilevato da: %s';
$strConfigDefaultFileError = 'Non posso leggere la configurazione da: "%1$s"';
$strConfigFileError = 'phpMyAdmin non riesce a leggere il file di configurazione!<br />Questo può accadere se il php trova un parse error in esso oppure il php non trova il file.<br />Richiamate il file di configurazione direttamente utilizzando il link sotto e leggete il/i messaggio/i di errore del php che ricevete. Nella maggior parte dei casi ci sono un apostrofo o una virgoletta mancanti.<br />Se ricevete una pagina bianca, allora è tutto a posto.';
$strConfigureTableCoord = 'Prego, configurare le coordinate per la tabella %s';
$strConnectionError = 'Impossibile connettersi: impostazioni non valide.';
$strConnections = 'Connessioni';
$strConstraintsForDumped = 'Limiti per le tabelle scaricate';
$strConstraintsForTable = 'Limiti per la tabella';
$strControluserFailed = 'Connessione per controluser come definito nella configurazione fallita.';
$strCookiesRequired = 'Da questo punto in poi, i cookies devono essere abilitati.';
$strCopy = 'Copia';
$strCopyDatabaseOK = 'Il Database %s è stato copiato in %s';
$strCopyTable = 'Copia la tabella nel (database<b>.</b>tabella):';
$strCopyTableOK = 'La tabella %s è stata copiata su %s.';
$strCopyTableSameNames = 'Impossibile copiare la tabella su se stessa!';
$strCouldNotKill = 'phpMyAdmin non è in grado di terminare il thread %s. Probabilmente è già stato terminato.';
$strCreate = 'Crea';
$strCreateDatabaseBeforeCopying = 'CREATE DATABASE prima di copiare';
$strCreateIndex = 'Crea un indice su %s columns';
$strCreateIndexTopic = 'Crea un nuovo indice';
$strCreateNewDatabase = 'Crea un nuovo database';
$strCreateNewTable = 'Crea una nuova tabella nel database %s';
$strCreatePage = 'Crea una nuova pagina';
$strCreatePdfFeat = 'Creazione di PDF';
$strCreateRelation = 'Crea relazioni';
$strCreateTable = 'Crea tabelle';
$strCreateUserDatabase = 'Database per l\'utente';
$strCreateUserDatabaseName = 'Crea un database con lo stesso nome e concedi tutti i privilegi';
$strCreateUserDatabaseNone = 'None';
$strCreateUserDatabaseWildcard = 'Concedi tutti i privilegi al nome con caratteri jolly (username\_%)';
$strCreationDates = 'Creazione/Aggiornamento/Controllo date';
$strCriteria = 'Criterio';
$strCroatian = 'Croato';
$strCSV = 'CSV';
$strCyrillic = 'Cirillico';
$strCzech = 'Ceco';
$strCzechSlovak = 'Ceco-Slovacco';
$strDanish = 'Danese';
$strDatabase = 'Database';
$strDatabaseEmpty = 'Il nome del DataBase è vuoto!';
$strDatabaseExportOptions = 'Opzioni di esportazione del database';
$strDatabaseHasBeenDropped = 'Il Database %s è stato eliminato.';
$strDatabases = 'Database';
$strDatabasesDropped = '%s databases sono stati cancellati correttamente.';
$strDatabasesStatsDisable = 'Disabilita le Statistiche';
$strDatabasesStatsEnable = 'Abilita le Statistiche';
$strDatabasesStatsHeavyTraffic = 'N.B.: Abilitare qui le statistiche del Database potrebbe causare del traffico intenso fra il server web e MySQL.';
$strDatabasesStats = 'Statistiche dei databases';
$strData = 'Dati';
$strDataDict = 'Data Dictionary';
$strDataOnly = 'Solo dati';
$strDataPages = 'Pagine contenenti dati';
$strDBComment = 'Commento al Database: ';
$strDBCopy = 'Copia il Database in';
$strDbIsEmpty = 'Il databse sembra essere vuoto!';
$strDbPrivileges = 'Privilegi specifici al database';
$strDBRename = 'Rinomina il DataBase in';
$strDbSpecific = 'specifico del database';
$strDefaultEngine = '%s è il motore di memorizzazione predefinito su questo server MySQL.';
$strDefault = 'Predefinito';
$strDefaultValueHelp = 'Per i valori predefiniti, prego inserire un singolo valore, senza backslashes escaping o virgolette, utilizzando questo formato: a';
$strDefragment = 'Deframmenta la tabella';
$strDelayedInserts = 'Utilizza inserimenti ritardati';
$strDeleteAndFlush = 'Cancella gli utenti e dopo ricarica i privilegi.';
$strDeleteAndFlushDescr = 'Questa è la vita più giusta, ma il caricamento dei privilegi può durare qualche secondo.';
$strDeleted = 'La riga è stata cancellata';
$strDeletedRows = 'Righe cancellate:';
$strDelete = 'Elimina';
$strDeleteNoUsersSelected = 'Nessun utente selezionato per la cancellazione!';
$strDeleteRelation = 'Elimina relazione';
$strDeleting = 'Cancellazione in corso di %s';
$strDelimiter = 'Delimitatori';
$strDelOld = 'La Pagina corrente contiene Riferimenti a Tabelle che non esistono più. Volete cancellare questi Riferimenti?';
$strDescending = 'Decrescente';
$strDescription = 'Descrizione';
$strDesigner = 'Designer';
$strDesignerHelpDisplayField = 'Il campi da mostrare sono in colore rosa. Per impostare/togliere un campo come campo da mostrare, clicca l\'icona "Scegli il campo da mostrare", e poi clicca sul nome appropriato del campo.';
$strDictionary = 'dizionario';
$strDirectLinks = 'Link diretti';
$strDirtyPages = 'Pagine sporche';
$strDisabled = 'Disabilitata';
$strDisableForeignChecks = 'Disabilita i controlli sulle chiavi straniere';
$strDisplayFeat = 'Mostra Caratteristiche';
$strDisplayOrder = 'Ordine di visualizzazione:';
$strDisplayPDF = 'Mostra lo schema del PDF';
$strDoAQuery = 'Esegui "query da esempio" (carattere jolly: "%")';
$strDocSQL = 'DocSQL';
$strDocu = 'Documentazione';
$strDoYouReally = 'Confermi: ';
$strDropDatabaseStrongWarning = 'Si sta per DISTRUGGERE COMPLETAMENTE un intero DataBase!';
$strDrop = 'Elimina';
$strDropUsersDb = 'Elimina i databases gli stessi nomi degli utenti.';
$strDumpingData = 'Dump dei dati per la tabella';
$strDumpSaved = 'Il dump è stato salvato sul file %s.';
$strDumpXRows = 'Dump di %s righe a partire dalla riga %s.';
$strDynamic = 'dinamico';
$strEdit = 'Modifica';
$strEditPDFPages = 'Modifica pagine PDF';
$strEditPrivileges = 'Modifica Privilegi';
$strEffective = 'Effettivo';
$strEmptyResultSet = 'MySQL ha restituito un insieme vuoto (i.e. zero righe).';
$strEmpty = 'Svuota';
$strEnabled = 'Abilitata';
$strEncloseInTransaction = 'Includi export in una transazione';
$strEndCut = 'FINE CUT';
$strEnd = 'Fine';
$strEndRaw = 'FINE RAW';
$strEngineAvailable = '%s è disponibile su questo server MySQL.';
$strEngineDisabled = '%s è stato disabilitato su questo server MySQL.';
$strEngines = 'Motori';
$strEngineUnsupported = 'Questo server MySQL non supporta il motore di memorizzazione %s.';
$strEnglish = 'Inglese';
$strEnglishPrivileges = 'Nota: i nomi dei privilegi di MySQL sono in Inglese';
$strError = 'Errore';
$strErrorInZipFile = 'Errore nell\'archivio ZIP:';
$strErrorRelationAdded = 'Errore: relazione non aggiunta.';
$strErrorRelationExists = 'Errore: relazione già esistente.';
$strErrorRenamingTable = 'Errore nel rinominare la tabella %1$s in %2$s';
$strErrorSaveTable = 'Errore nel salvare le coordinate per il Designer.';
$strEscapeWildcards = 'I caratteri jolly _ e % dovrebbero essere preceduti da un \ per l\'utilizzo letterale';
$strEsperanto = 'Esperanto';
$strEstonian = 'Estone';
$strEvent = 'Eventi';
$strExcelEdition = 'Edizione Excel';
$strExecuteBookmarked = 'Esegue la query dalle preferite';
$strExplain = 'Spiega SQL';
$strExport = 'Esporta';
$strExportImportToScale = 'Importa/esporta alla dimensione';
$strExportMustBeFile = 'Il tipo di esportazione selezionato necessita di essere salvato in un file!';
$strExtendedInserts = 'Inserimenti estesi';
$strExtra = 'Extra';
$strFailedAttempts = 'Tentativi falliti';
$strField = 'Campo';
$strFieldHasBeenDropped = 'Il campo %s è stato eliminato';
$strFieldInsertFromFileTempDirNotExists = 'Errore nello spostare il file caricato, vedi FAQ 1.11';
$strFields = 'Campi';
$strFieldsEnclosedBy = 'Campo composto da';
$strFieldsEscapedBy = 'Campo impedito da';
$strFieldsTerminatedBy = 'Campo terminato da';
$strFileAlreadyExists = 'Il file %s esiste già sul server: prego, cambiare nome del file o selezionare l\'opzione "sovrascrivi".';
$strFileCouldNotBeRead = 'Il file non può essere letto';
$strFileNameTemplateDescriptionDatabase = 'nome database';
$strFileNameTemplateDescription = 'Questo valore è interpretato usando %1$sstrftime%2$s, in questo modo puoi usare stringhe di formattazione per le date/tempi. Verranno anche aggiunte le seguenti trasformazioni: %3$s. Il testo rimanente resterà invariato.';
$strFileNameTemplateDescriptionServer = 'nome server';
$strFileNameTemplateDescriptionTable = 'nome tabella';
$strFileNameTemplate = 'Nome file template';
$strFileNameTemplateRemember = 'ricorda il template';
$strFiles = 'File';
$strFileToImport = 'File importato';
$strFixed = 'fisso';
$strFlushPrivilegesNote = 'N.B.: phpMyAdmin legge i privilegi degli utenti direttamente nella tabella dei privilegi di MySQL. Il contenuto di questa tabella può differire dai privilegi usati dal server se sono stati fatti cambiamenti manuali. In questo caso, Si dovrebbero %srinfrescare i privilegi%s prima di continuare.';
$strFlushQueryCache = 'Rinfresca la cache delle query';
$strFlushTable = 'Inizializza ("FLUSH") la tabella';
$strFlushTables = 'Rinfresca (chiudi) tutte le tabelle';
$strFontSize = 'Dimensione font';
$strForeignKeyError = 'Errore creando una foreign key (controlla il tipo di dati)';
$strFormat = 'Formato';
$strFormEmpty = 'Valore mancante nel form!';
$strFreePages = 'Pagine libere';
$strFullText = 'Testo completo';
$strFunction = 'Funzione';
$strFunctions = 'Funzioni';
$strGenBy = 'Generato da';
$strGeneralRelationFeat = 'Caratteristiche Generali di Relazione';
$strGenerate = 'Genera';
$strGeneratePassword = 'Genera Password';
$strGenTime = 'Generato il';
$strGeorgian = 'Georgiano';
$strGerman = 'Tedesco';
$strGlobal = 'globale';
$strGlobalPrivileges = 'Privilegi globali';
$strGlobalValue = 'Valore globale';
$strGo = 'Esegui';
$strGrantOption = 'Grant';
$strGreek = 'Greco';
$strGzip = '"compresso con gzip"';
$strHandler = 'Handler';
$strHasBeenAltered = 'è stato modificato.';
$strHasBeenCreated = 'è stato creato.';
$strHaveToShow = 'Devi scegliere almeno una Colonna da mostrare';
$strHebrew = 'Ebreo';
$strHelp = 'Aiuto';
$strHexForBLOB = 'Usa dati esadecimali per BLOB';
$strHide = 'Nascondi';
$strHideShowAll = 'Mostra/nascondi tutto';
$strHideShowNoRelation = 'Mostra/nascondi tabella senza relazioni';
$strHome = 'Home';
$strHomepageOfficial = 'Home page ufficiale di phpMyAdmin';
$strHostEmpty = 'Il nome di host è vuoto!';
$strHost = 'Host';
$strHTMLExcel = 'Microsoft Excel 2000';
$strHTMLWord = 'Microsoft Word 2000';
$strHungarian = 'Ungherese';
$strIcelandic = 'Islandese';
$strId = 'ID';
$strIdxFulltext = 'Testo completo';
$strIEUnsupported = 'Internet explorer non supporta questa funzione.';
$strIgnoreDuplicates = 'Ignora le righe duplicate';
$strIgnore = 'Ignora';
$strIgnoreInserts = 'Utilizza gli IGNORE INSERTS';
$strImportExportCoords = 'Importa/esporta le coordinate per PDF schema';
$strImportFiles = 'Importa file';
$strImportFormat = 'Formato del file importato';
$strImport = 'Importa';
$strImportSuccessfullyFinished = 'Importazione eseguita con successo, %d query eseguite.';
$strIndexes = 'Indici';
$strIndexesSeemEqual = 'I seguenti indici sembrano essere uguali e uno di essi deve essere rimosso:';
$strIndexHasBeenDropped = 'L\'indice %s è stato eliminato';
$strIndex = 'Indice';
$strIndexName = 'Nome dell\'indice :';
$strIndexType = 'Tipo di indice :';
$strIndexWarningTable = 'Problemi con gli indici della tabella `%s`';
$strInnoDBAutoextendIncrementDesc = ' La dimensione di incremento per aumentare la dimensione di una tabella autoextending quando diventa piena.';
$strInnoDBAutoextendIncrement = 'Incremento autoextend';
$strInnoDBBufferPoolSizeDesc = 'La dimensione del buffer di memoria InnoDB cacha dati e indici delle proprie tabelle.';
$strInnoDBBufferPoolSize = 'Dimensione del Buffer pool';
$strInnoDBDataFilePath = 'File dati';
$strInnoDBDataHomeDirDesc = 'La parte comune del path della directory per tutti i file dati InnoDB.';
$strInnoDBDataHomeDir = 'Home directory dei dati';
$strInnoDBPages = 'pagine';
$strInnoDBRelationAdded = 'Aggiunta relazione InnoDB';
$strInnodbStat = 'Stato InnoDB';
$strInsecureMySQL = 'Il file di configurazione in uso contiene impostazioni (root con nessuna password) che corrispondono ai privilegi dell\'account MySQL predefinito. Un server MySQL funzionante con queste impostazioni è aperto a intrusioni, e si dovrebbe realmente riparare a questa falla nella sicurezza.';
$strInsertAsNewRow = 'Inserisci come nuova riga';
$strInsertedRowId = 'Inserito id riga:';
$strInsertedRows = 'Righe inserite:';
$strInsert = 'Inserisci';
$strInternalNotNecessary = '* Non è necessaria una relazione interna quando già esiste in InnoDB.';
$strInternalRelationAdded = 'Aggiunte relazioni internet';
$strInternalRelations = 'Relazioni interne';
$strInUse = 'in uso';
$strInvalidAuthMethod = 'Metodo di autenticazione settato nella configurazione non valido:';
$strInvalidColumn = 'Colonna specificata (%s) invalida!';
$strInvalidColumnCount = 'Il contatore delle colonne deve essere superiore a 0.';
$strInvalidCSVFieldCount = 'Contatore di campo non valido nell\'input CSV alla linea %d.';
$strInvalidCSVFormat = 'Formato non valido per l\'input CSV alla linea %d.';
$strInvalidCSVParameter = 'Parametro non valido per importazione CSV: %s';
$strInvalidDatabase = 'Database non valido';
$strInvalidFieldAddCount = 'Deviaggiungere come minimo un campo.';
$strInvalidFieldCount = 'la tabella deve avere come minimo un dato.';
$strInvalidLDIImport = 'Questo plugin non supporta importazioni di dati compressi!';
$strInvalidRowNumber = '%d non è un numero valido di righe.';
$strInvalidServerHostname = 'Nome host per il server %1$s non valido. Controlla la tua configurazione.';
$strInvalidServerIndex = 'Server index non valido: "%s"';
$strInvalidTableName = 'Nome tabella non valido';
$strJapanese = 'Giapponese';
$strJoins = 'Joins';
$strJumpToDB = 'Passa al database "%s".';
$strJustDelete = 'Cancella soltanto gli utenti dalle tabelle dei privilegi.';
$strJustDeleteDescr = 'Gli utenti "cancellati" saranno ancora in grado di accedere al servercome al solito finché i privilegi non verraanno ricaricati.';
$strKeepPass = 'Non cambiare la password';
$strKeyCache = 'Key cache';
$strKeyname = 'Nome chiave';
$strKill = 'Rimuovi';
$strKnownExternalBug = 'La %s funzionalità è affetta da un bug noto, vedi %s';
$strKorean = 'Coreano';
$strLandscape = 'Orizzontale';
$strLanguage = 'Lingua';
$strLanguageUnknown = 'Lingua non conosciuta : %1$s.';
$strLatchedPages = 'Latched pages';
$strLatexCaption = 'Sottotitolo della tabella';
$strLatexContent = 'Contenuto della tabella __TABLE__';
$strLatexContinuedCaption = 'Sottotitolo della tabella continuato';
$strLatexContinued = '(continua)';
$strLatexIncludeCaption = 'Includi sottotitolo della tabella';
$strLatexLabel = 'Chiave etichetta';
$strLaTeX = 'LaTeX';
$strLatexStructure = 'Struttura della tabella __TABLE__';
$strLatvian = 'Lituano';
$strLDI = 'CSV usando LOAD DATA';
$strLDILocal = 'Usa LOCAL keyword';
$strLengthSet = 'Lunghezza/Set*';
$strLimitNumRows = 'record per pagina';
$strLinesTerminatedBy = 'Linee terminate da';
$strLinkNotFound = 'Link non trovato';
$strLinksTo = 'Collegamenti a';
$strLithuanian = 'Lituano';
$strLocalhost = 'Locale';
$strLocationTextfile = 'Percorso del file';
$strLogin = 'Connetti';
$strLoginInformation = 'Informazioni di Login';
$strLogout = 'Disconnetti';
$strLogPassword = 'Password:';
$strLogServer = 'Server';
$strLogUsername = 'Nome utente:';
$strLongOperation = 'Questa operazione potrebbe impiegare molto tempo. Procedere comunque?';
$strMaxConnects = 'max. connessioni contemporanee';
$strMaximalQueryLength = 'Lunghezza massima di una query creata';
$strMaximumSize = 'Dimensione massima: %s%s';
$strMbExtensionMissing = 'L\'estensione PHP mbstring non è stata trovata e sembra che si stia utilizzando un set di caratteri multibyte. Senza l\'estensione mbstring, phpMyAdmin non è in grado di dividere correttamente le stringhe di caratteri e questo può portare a risultati inaspettati.';
$strMbOverloadWarning = 'Avete abilitato mbstring.func_overload nella configurazione del PHP. Questa opzione è incompatibile con phpMyAdmin e potrebbe causare la corruzione di alcuni dati!';
$strMIME_available_mime = 'Tipi-MIME disponibili';
$strMIME_available_transform = 'Trasformazioni disponibili';
$strMIME_description = 'Descrizione';
$strMIME_MIMEtype = 'tipo MIME';
$strMIME_nodescription = 'Nessuna descrizione è disponibile per questa trasformazione.<br />Prego, chiedere all\'autore cosa %s faccia.';
$strMIME_transformation_note = 'Per una lista di opzioni di trasformazione disponibili e le loro rispettive trasformazioni di tipi-MIME, cliccate su %strasformazione descrizioni%s';
$strMIME_transformation_options_note = 'Prego, immettere i valori per le opzioni di trasformazioneutilizzando questo formato: \'a\', 100, b,\'c\'...<br />Se c\'è la necessità di immettere un backslash ("\") o un apostrofo ("\'") tra questi valori, essi vanno backslashati (per es. \'\\\\xyz\' or \'a\\\'b\').';
$strMIME_transformation_options = 'Opzioni di Transformation';
$strMIME_transformation = 'Trasformazione del Browser';
$strMIMETypesForTable = 'MIME TYPES FOR TABLE';
$strMIME_without = 'Tipi-MIME stampati in italics non hanno una funzione di trasformazione separata';
$strModifications = 'Le modifiche sono state salvate';
$strModifyIndexTopic = 'Modifica un indice';
$strModify = 'Modifica';
$strMoveMenu = 'Muovi menù';
$strMoveTableOK = 'La tabella %s è stata spostata in %s.';
$strMoveTableSameNames = 'Impossibile spostare la tabella su se stessa!';
$strMoveTable = 'Sposta la tabella nel (database<b>.</b>tabella):';
$strMultilingual = 'multilingua';
$strMyISAMDataPointerSizeDesc = 'Dimensione del puntatore predefinito in Bytes, che deve essere usata da CREATE TABLE per le tabelle MyISAM quando non è stata specificata l\'opzione MAX_ROWS.';
$strMyISAMDataPointerSize = 'Domensione del puntatore dati';
$strMyISAMMaxExtraSortFileSizeDesc = 'Se il file temporaneo è usato per la creazione veloce di un indice MyISAM, occuperebbe più spazio dell\'utilizzo del metodo key cache con la quantità ivi specificata: perciò si deve prediligere il metodo key cache.';
$strMyISAMMaxExtraSortFileSize = 'Dimensione massima per i file temporanei nella creazione di un indice';
$strMyISAMMaxSortFileSizeDesc = 'La dimensione massima dei file temporanei MySQL può essere utilizzata nella rigenerazione di un indice MyISAM (durante un REPAIR TABLE, ALTER TABLE, o LOAD DATA INFILE).';
$strMyISAMMaxSortFileSize = 'Dimensione massima dei file temporanei di ordinamento';
$strMyISAMRecoverOptionsDesc = 'La modalità di irppristino automatico di tabelle MyISAM corrotte, come impostato tramite l\'opzione di lan cio del server --myisam-recover.';
$strMyISAMRecoverOptions = 'Modalità di ripristino automatico';
$strMyISAMRepairThreadsDesc = 'Se questo valore è maggiore di 1, gli indici della tabella MyISAM vengono creati in parallelo (ogni indice nel suo thread) durante il processo di ordinamento Repair by.';
$strMyISAMRepairThreads = 'Thread di riparazione';
$strMyISAMSortBufferSizeDesc = 'Il buffer che viene allocato nell\'ordinamento degli indici MyISAM durante un REPAIR TABLE o nella creazione degli indici con CREATE INDEX o ALTER TABLE.';
$strMyISAMSortBufferSize = 'Ordina la dimensione del buffer';
$strMySQLCharset = 'Set di caratteri MySQL';
$strMysqlClientVersion = 'Versione MySQL client';
$strMySQLConnectionCollation = 'collazione della connessione di MySQL';
$strMysqlLibDiffersServerVersion = 'Le tue librerie di PHP per MySQL versione %s sono diverse dalla versione di MySQL server %s. Potrebbe causare comportamenti imprevedibili.';
$strMySQLSaid = 'Messaggio di MySQL: ';
$strMySQLShowProcess = 'Visualizza processi in esecuzione';
$strMySQLShowStatus = 'Visualizza informazioni di runtime di MySQL';
$strMySQLShowVars = 'Visualizza variabili di sistema di MySQL';
$strName = 'Nome';
$strNext = 'Prossimo';
$strNoActivity = 'Nessuna attività da %s secondi o più, si prega di autenticarsi nuovamente';
$strNoDatabases = 'Nessun database';
$strNoDatabasesSelected = 'Nessun database selezionato.';
$strNoDataReceived = 'Non sono stati ricevuti dati da importare. O non è stato indicato alcun nome file, oppure è stato superata la dimensione massima consentita per il file, impostata nella configurazione di PHP. Vedi FAQ 1.16.';
$strNoDescription = 'nessuna Description';
$strNoDetailsForEngine = 'Non è disponibile nessuna informazione dettagliata sullo stato di questo motore di memorizzazione.';
$strNoDropDatabases = 'I comandi "DROP DATABASE" sono disabilitati.';
$strNoExplain = 'Non Spiegare SQL';
$strNoFilesFoundInZip = 'Non sono stati trovati file ZIP all\'interno dell\'archivio!';
$strNoFrames = 'phpMyAdmin funziona meglio con browser che supportano frames';
$strNoIndex = 'Nessun indice definito!';
$strNoIndexPartsDefined = 'Nessuna parte di indice definita!';
$strNoModification = 'Nessun cambiamento';
$strNone = 'Nessuno';
$strNo = ' No ';
$strNoOptions = 'Questo formato non ha opzioni';
$strNoPassword = 'Nessuna Password';
$strNoPermission = 'Il server web non possiede i privilegi per salvare il file %s.';
$strNoPhp = 'senza codice PHP';
$strNoPrivileges = 'Nessun Privilegio';
$strNoRights = 'Non hai i permessi per effettuare questa operazione!';
$strNoRowsSelected = 'Nessuna riga selezionata';
$strNoSpace = 'Spazio insufficiente per salvare il file %s.';
$strNoTablesFound = 'Non ci sono tabelle nel database.';
$strNoThemeSupport = 'Nessun supporto per i temi, si prega di controllare la configurazione e/o i temi nella cartella %s.';
$strNotNumber = 'Questo non è un numero!';
$strNotOK = 'non OK';
$strNotSet = '<b>%s</b> tabella non trovata o non settata in %s';
$strNoUsersFound = 'Nessun utente trovato.';
$strNoValidateSQL = 'Non Validare SQL';
$strNull = 'Null';
$strNumberOfFields = 'Numero di campi';
$strNumberOfTables = 'Numero di tabelle';
$strNumSearchResultsInTable = '%s corrisponde/ono nella tabella <i>%s</i>';
$strNumSearchResultsTotal = '<b>Totale:</b> <i>%s</i> corrispondenza/e';
$strNumTables = 'Tabelle';
$strOK = 'OK';
$strOpenDocumentSpreadsheet = 'Foglio di calcolo nel formato Open Document';
$strOpenDocumentText = 'Testo nel formato Open Document';
$strOpenNewWindow = 'Apri una nuova finestra di PhpMyAdmin';
$strOperations = 'Operazioni';
$strOperator = 'Operatore';
$strOptimizeTable = 'Ottimizza tabella';
$strOptions = 'Opzioni';
$strOr = 'Oppure';
$strOverhead = 'In eccesso';
$strOverwriteExisting = 'Sovrascrivi file(s) esistente/i';
$strPageNumber = 'Numero pagina:';
$strPagesToBeFlushed = 'Pagine che devono essere flushate';
$strPaperSize = 'Dimensioni carta';
$strPartialImport = 'Importazione parziale';
$strPartialText = 'Testo parziale';
$strPasswordChanged = 'La password per l\'utente %s è cambiata con successo.';
$strPasswordEmpty = 'La password è vuota!';
$strPasswordHashing = 'Password Hashing';
$strPasswordNotSame = 'La password non coincide!';
$strPassword = 'Password';
$strPdfDbSchema = 'Schema del database "%s" - Pagina %s';
$strPdfInvalidTblName = 'La tabella "%s" non esiste!';
$strPdfNoTables = 'Nessuna Tabella';
$strPDF = 'PDF';
$strPDFReportExplanation = '(Genera un report contenete i dati di una singola tabella)';
$strPDFReportTitle = 'Titolo del Report';
$strPerHour = 'all\'ora';
$strPerMinute = 'al minuto';
$strPerSecond = 'al secondo';
$strPersian = 'Persiano';
$strPhoneBook = 'rubrica';
$strPHP40203 = 'Si sta utilizzando PHP 4.2.3, che presenta un serio bug con le stringhe multi-byte (mbstring). Vedi report PHP 19404. Questa versione di PHP non è raccomandata per l\'utilizzo con phpMyAdmin.';
$strPhp = 'Crea il codice PHP';
$strPHPVersion = 'Versione PHP';
$strPleaseSelectPrimaryOrUniqueKey = 'Seleziona la chiave primaria o una chiave univoca';
$strPmaDocumentation = 'Documentazione di phpMyAdmin';
$strPmaUriError = 'La direttiva <tt>$cfg[\'PmaAbsoluteUri\']</tt> DEVE essere impostata nel file di configurazione!';
$strPmaWiki = 'phpMyAdmin wiki';
$strPolish = 'Polacco';
$strPortrait = 'Verticale';
$strPos1 = 'Inizio';
$strPrevious = 'Precedente';
$strPrimaryKeyHasBeenDropped = 'La chiave primaria è stata eliminata';
$strPrimaryKeyName = 'Il nome della chiave primaria deve essere... PRIMARY!';
$strPrimaryKeyWarning = '("PRIMARY" <b>deve</b> essere il nome di, e <b>solo di</b>, una chiave primaria!)';
$strPrimary = 'Primaria';
$strPrint = 'Stampa';
$strPrintViewFull = 'Vista stampa (con full text)';
$strPrintView = 'Visualizza per stampa';
$strPrivDescAllPrivileges = 'Comprende tutti i privilegi tranne GRANT.';
$strPrivDescAlter = 'Permette di alterare la struttura di tabelle esistenti.';
$strPrivDescAlterRoutine = 'Permette l\'alterazione e l\'eliminazione di routines memorizzate.';
$strPrivDescCreateDb = 'Permette di creare nuove tabelle e nuovi databases.';
$strPrivDescCreateRoutine = 'Permette la creazione di routines memorizzate.';
$strPrivDescCreateTbl = 'Permette di creare nuove tabelle.';
$strPrivDescCreateTmpTable = 'Permette di creare tabelle temporanee.';
$strPrivDescCreateUser = 'Permette di creare, cancellare e rinominare gli account utente.';
$strPrivDescCreateView = 'Permette la creazione di nuove viste.';
$strPrivDescDelete = 'Permette di cancellare dati.';
$strPrivDescDropDb = 'Permette di eliminare databases e tabelle.';
$strPrivDescDropTbl = 'Permette di eliminare tabelle.';
$strPrivDescExecute5 = 'Permette l\'esecuzione di routines memorizzate.';
$strPrivDescExecute = 'Permette di eseguire procedure memorizzate; Non ha effetto in questa versione di MySQL.';
$strPrivDescFile = 'Permette di importare dati da e esportare dati in file.';
$strPrivDescGrant = 'Permette di aggiungere utenti e privilegi senza ricaricare le tabelle dei privilegi.';
$strPrivDescIndex = 'Permette di creare ed eliminare gli indici.';
$strPrivDescInsert = 'Permette di inserire e sovrascrivere dati.';
$strPrivDescLockTables = 'Permette di bloccare le tabelle per il thread corrente.';
$strPrivDescMaxConnections = 'Limita il numero di nuove connessioni che un utente può aprire in un\'ora.';
$strPrivDescMaxQuestions = 'Limita il numero di query che un utente può mandare al server in un\'ora.';
$strPrivDescMaxUpdates = 'Limita il numero di comandi che possono cambiare una tabella o un database che un utente può eseguire in un\'ora.';
$strPrivDescMaxUserConnections = 'Limite di connessioni simultanee che un utente può fare.';
$strPrivDescProcess3 = 'Permette di killare i processi di altri utenti.';
$strPrivDescProcess4 = 'Permette di vedere le query complete nella lista dei processi.';
$strPrivDescReferences = 'Non ha alcun effetto in questa versione di MySQL.';
$strPrivDescReload = 'Permette di ricaricare i parametri del server e di resettare la cache del server.';
$strPrivDescReplClient = 'Accorda il diritto ad un utente di domandare dove sono i masters/slaves.';
$strPrivDescReplSlave = 'Necessario per la replicazione degli slaves.';
$strPrivDescSelect = 'Permette di leggere i dati.';
$strPrivDescShowDb = 'Accorda l\'accesso alla lista completa dei databases.';
$strPrivDescShowView = 'Permette di effettuare query del tipo SHOW CREATE VIEW.';
$strPrivDescShutdown = 'Permette di chiudere il server.';
$strPrivDescSuper = 'Permette altre connessioni, anche se è stato raggiunto il massimo numero di connessioni; Necessario per molte operazioni di amministrazione come il settaggio di variabili globali o la cancellazione dei threads di altri utenti.';
$strPrivDescUpdate = 'Permette di cambiare i dati.';
$strPrivDescUsage = 'Nessun privilegio.';
$strPrivileges = 'Privilegi';
$strPrivilegesReloaded = 'I privilegi sono stati ricaricati con successo.';
$strProcedures = 'Procedure';
$strProcesses = 'Processi';
$strProcesslist = 'Lista Processi';
$strProfiling = 'Profiling';
$strProtocolVersion = 'Versione protocollo';
$strPutColNames = 'Mette i nomi delle colonne alla prima riga';
$strQBEDel = 'Elimina';
$strQBEIns = 'Aggiungi';
$strQBE = 'Query da esempio';
$strQueryCache = 'Cache delle query';
$strQueryFrame = 'Finestra della Query';
$strQueryOnDb = 'SQL-query sul database <b>%s</b>:';
$strQueryResultsOperations = 'Risultato delle operazioni di Query';
$strQuerySQLHistory = 'Storico dell\'SQL';
$strQueryStatistics = '<b>Query delle Statistiche</b>: Dall\'avvio, %s query sono state effettuate sul server.';
$strQueryTime = 'La query ha impiegato %01.4f sec';
$strQueryType = 'Tipo di Query';
$strQueryWindowLock = 'Non sovrascrivere questa query da fuori della finestra';
$strReadRequests = 'Richieste di lettura';
$strReceived = 'Ricevuti';
$strRecommended = 'raccomandato';
$strRecords = 'Record';
$strReferentialIntegrity = 'Controlla l\'integrità delle referenze:';
$strRefresh = 'Aggiorna';
$strRelationalSchema = 'Schema relazionale';
$strRelationDeleted = 'Relazione cancellata';
$strRelationNotWorking = 'Le caratteristiche aggiuntive sono state disattivate per funzionare con le tabelle linkate. Per scoprire perché clicca %squi%s.';
$strRelationsForTable = 'RELATIONS FOR TABLE';
$strRelations = 'Relazioni';
$strRelationView = 'Vedi relazioni';
$strReloadingThePrivileges = 'Caricamento dei privilegi in corso';
$strReloadPrivileges = 'Ricarica i privilegi';
$strReload = 'Ricarica';
$strRemoveSelectedUsers = 'Rimuove gli utenti selezionati';
$strRenameDatabaseOK = 'Il DataBase %s è stato rinominato in %s';
$strRenameTableOK = 'La tabella %s è stata rinominata %s';
$strRenameTable = 'Rinomina la tabella in';
$strRepairTable = 'Ripara tabella';
$strReplaceNULLBy = 'Sostituisci NULL con';
$strReplaceTable = 'Sostituisci i dati della tabella col file';
$strReplication = 'Replicazione';
$strReset = 'Riavvia';
$strResourceLimits = 'Limiti di risorse';
$strRestartInsertion = 'Riprendi inserimento con la riga %s';
$strReType = 'Reinserisci';
$strRevokeAndDeleteDescr = 'Gli utenti UTILIZZERANNO comunque il privilegio finché i privilegi non saranno ricaricati.';
$strRevokeAndDelete = 'Revoca tutti i privilegi attivi agli utenti e dopo li cancella.';
$strRevokeMessage = 'Hai revocato i privilegi per %s';
$strRevoke = 'Revoca';
$strRomanian = 'Rumeno';
$strRoutineReturnType = 'Tipo di risultato';
$strRoutines = 'Routines';
$strRowLength = 'Lunghezza riga';
$strRowsFrom = 'righe a partire da';
$strRowSize = 'Dimensione riga';
$strRowsModeFlippedHorizontal = 'orizzontale (headers ruotati)';
$strRowsModeHorizontal = ' orizzontale ';
$strRowsModeOptions = ' in modalità %s e ripeti gli headers dopo %s celle ';
$strRowsModeVertical = ' verticale ';
$strRows = 'Righe';
$strRowsStatistic = 'Statistiche righe';
$strRunning = 'in esecuzione su %s';
$strRunQuery = 'Invia Query';
$strRunSQLQuery = 'Esegui la/e query SQL sul database %s';
$strRunSQLQueryOnServer = 'Eseguendo query SQL sul server %s';
$strRussian = 'Russo';
$strSaveOnServer = 'Salva sul server nella directory %s';
$strSavePosition = 'Salva la posizione';
$strSave = 'Salva';
$strScaleFactorSmall = 'Il fattore di scala è troppo piccolo per riempire lo schema nella pagina';
$strSearch = 'Cerca';
$strSearchFormTitle = 'Cerca nel database';
$strSearchInTables = 'Nella/e tabella/e:';
$strSearchNeedle = 'parola/e o valore/i da cercare (carattere jolly: "%"):';
$strSearchOption1 = 'almeno una delle parole';
$strSearchOption2 = 'tutte le parole';
$strSearchOption3 = 'la frase esatta';
$strSearchOption4 = 'come espressione regolare';
$strSearchResultsFor = 'Cerca i risultati per "<i>%s</i>" %s:';
$strSearchType = 'Trova:';
$strSecretRequired = 'Adesso c\'è bisogno di una password per il file di configurazione (blowfish_secret).';
$strSelectADb = 'Prego, selezionare un database';
$strSelectAll = 'Seleziona Tutto';
$strSelectBinaryLog = 'Selezionare il log binario da visualizzare';
$strSelectFields = 'Seleziona campi (almeno uno):';
$strSelectForeignKey = 'Seleziona Foreign Key';
$strSelectNumRows = 'nella query';
$strSelectReferencedKey = 'Seleziona le chiavi referenziali';
$strSelectTables = 'Seleziona Tables';
$strSend = 'Salva con nome...';
$strSent = 'Spediti';
$strServerChoice = 'Scelta del server';
$strServerNotResponding = 'Il server non risponde';
$strServer = 'Server';
$strServers = 'Servers';
$strServerStatusDelayedInserts = 'Inserimento ritardato';
$strServerStatus = 'Informazioni di Runtime';
$strServerStatusUptime = 'Questo server MySQL sta girando da %s. E\' stato avviato il %s.';
$strServerTabVariables = 'Variabili';
$strServerTrafficNotes = '<b>Traffico del server</b>: Queste tabelle mostrano le statistiche del traffico di retedi questo server MySQL dal momento del suo avvio.';
$strServerVars = 'Variabili e parametri del Server';
$strServerVersion = 'Versione MySQL';
$strSessionStartupErrorGeneral = 'Non posso far partire la sessione senza errori, controlla gli errori nel log di PHP e/o del tuo server web e configura correttamente la tua installazione di PHP.';
$strSessionValue = 'Valore sessione';
$strSetEnumVal = 'Se il tipo di campo è "enum" o "set", immettere i valori usando il formato: \'a\',\'b\',\'c\'...<br />Se comunque dovete mettere dei backslashes ("\") o dei single quote ("\'") davanti a questi valori, backslashateli (per esempio \'\\\\xyz\' o \'a\\\'b\').';
$strShowAll = 'Mostra tutti';
$strShowColor = 'Mostra il colore';
$strShowDatadictAs = 'Formato del Data Dictionary';
$strShowFullQueries = 'Mostra query complete';
$strShowGrid = 'Mostra la griglia';
$strShowHideLeftMenu = 'Mostra/nascondi il menù di sinistra';
$strShowingBookmark = 'Mostrando i segnalibri';
$strShowingPhp = 'Mostrando il codice PHP';
$strShowingRecords = 'Visualizzazione record ';
$strShowingSQL = 'Mostrando la query SQL';
$strShow = 'Mostra';
$strShowOpenTables = 'Mostra le tabelle aperte';
$strShowPHPInfo = 'Mostra le info sul PHP';
$strShowSlaveHosts = 'Mostra gli hosts slave';
$strShowSlaveStatus = 'Mostra lo stato degli slave';
$strShowStatusBinlog_cache_disk_useDescr = 'Il numero delle transazioni che usano la cache temporanea del log binario, ma che oltrepassano il valore di binlog_cache_size e usano un file temporaneo per salvare gli statements dalle transazioni.';
$strShowStatusBinlog_cache_useDescr = 'Il numero delle transazioni che usano la cache temporanea del log binario.';
$strShowStatusCreated_tmp_disk_tablesDescr = 'Il numero delle tabelle temporanee create automaticamente sul disco dal server mentre esegue i comandi. Se il valore Created_tmp_disk_tables è grande, potresti voler aumentare il valore tmp_table_size, per fare im modo che le tabelle temporanee siano memory-based anzichè disk-based.';
$strShowStatusCreated_tmp_filesDescr = 'Numero di file temporanei che mysqld ha creato.';
$strShowStatusCreated_tmp_tablesDescr = 'Il numero di tabelle temporanee create automaticamente in memoria dal server durante l\'esecuzione dei comandi.';
$strShowStatusDelayed_errorsDescr = 'Numero di righe scritte con INSERT DELAYED in cui ci sono stati degli errori (probabilmete chiave dublicata).';
$strShowStatusDelayed_insert_threadsDescr = 'Il numero di processi INSERT DELAYED in uso. Ciascuna tabella su cui è usato INSERT DELAYED occupa un thread.';
$strShowStatusDelayed_writesDescr = 'Il numero di righe INSERT DELAYED scritte.';
$strShowStatusFlush_commandsDescr = 'Il numero di comandi FLUSH eseguiti.';
$strShowStatusHandler_commitDescr = 'Il numero di comandi interni COMMIT eseguiti.';
$strShowStatusHandler_deleteDescr = 'Il numero di volte in cui una riga è stata cancellata da una tabella.';
$strShowStatusHandler_discoverDescr = 'Il server MySQL può chiedere al motore di storage NDB Cluster se conosce una tabella sulla base di un nome dato. Questo è chaiamto discovery. Handler_discover indica il numero di volte che una tabella è stata trovata.';
$strShowStatusHandler_read_firstDescr = 'Il numero di volte che il primo valore è stato letto da un indice. Se è troppo alto è probabile che il server stia facendo molte scansioni complete degli indici; per esempio, SELECT col1 FROM foo, assumento che col1 sia indicizzata.';
$strShowStatusHandler_read_keyDescr = 'Il numero di richieste per leggere una riga basata su di una chiave. Se è alta, è un buon indice che le tue query e le tue tabelle sono correttamente indicizzate.';
$strShowStatusHandler_read_nextDescr = 'Il numero di richieste per leggere la riga successiva nell\'ordine delle chiavi. Questo valore è incrementato se stai facendo una query su di una colonna indice con un range costante, oppure se stai facendo una scansione degli indici.';
$strShowStatusHandler_read_prevDescr = 'Il numero di richieste per leggere la riga precedente nell\'ordine delle chiavi. Questo metodo di lettura è principalmente utilizzato per ottimizzare ORDER BY ... DESC.';
$strShowStatusHandler_read_rndDescr = 'Il numero di richieste per leggere una riga basata su una posizione fissa. Questo valore è alto se stai facendo molte richieste che richiedono un ordinamento dei risultati. Probabilmente hai molte query che che richiedono a MySQL di leggere l\'intera tabella oppure ci sono dei joins che non usano le chiavi correttamente.';
$strShowStatusHandler_read_rnd_nextDescr = 'Il numero di richieste per leggere la riga successiva in un file di dati. Questo valore è alto se stai facendo molte scansioni della tabella. Generalmente è un segnale che le tue tabelle non sono correttamente indicizzate, o che le query non sono state scritte per trarre vantaggi dagli indici che hai.';
$strShowStatusHandler_rollbackDescr = 'Il numero di comandi ROLLBACK interni.';
$strShowStatusHandler_updateDescr = 'Il numero di richieste per aggiornare una riga in una tabella.';
$strShowStatusHandler_writeDescr = 'Il numero di richieste per inserire una riga in una tabella.';
$strShowStatusInnodb_buffer_pool_pages_dataDescr = 'Il numero di pagine che contengono dati (sporchi o puliti).';
$strShowStatusInnodb_buffer_pool_pages_dirtyDescr = 'Il numero di pagine attualmente sporche.';
$strShowStatusInnodb_buffer_pool_pages_flushedDescr = 'Il numero di buffer pool pages che hanno avuto richiesta di essere aggiornate.';
$strShowStatusInnodb_buffer_pool_pages_freeDescr = 'Il numero di pagine libere.';
$strShowStatusInnodb_buffer_pool_pages_latchedDescr = 'Il numero di pagine bloccate in un InnoDB buffer pool. Queste pagine sono attualmente in lettura o in scittura e non possono essere aggiornate o rimosse per altre ragioni.';
$strShowStatusInnodb_buffer_pool_pages_miscDescr = 'Il numero di pagine occupate perchè sono state allocate per amministrazione, come row locks o per hash index adattivi. Questo valore può essere calcolato come Innodb_buffer_pool_pages_total - Innodb_buffer_pool_pages_free - Innodb_buffer_pool_pages_data.';
$strShowStatusInnodb_buffer_pool_pages_totalDescr = 'Il numero totale di buffer pool, in pagine.';
$strShowStatusInnodb_buffer_pool_read_ahead_rndDescr = 'Il numero di read-aheads "random" InnoDB iniziate. Questo accade quando una query legge una porzione di una tabella, ma in ordine casuale.';
$strShowStatusInnodb_buffer_pool_read_ahead_seqDescr = 'Il numero di read-aheads InnoDB sequanziali. Questo accade quando InnoDB esegue una scansione completa sequenziale di una tabella.';
$strShowStatusInnodb_buffer_pool_read_requestsDescr = 'Il numero di richieste logiche che InnoDb ha fatto.';
$strShowStatusInnodb_buffer_pool_readsDescr = 'Il numero di richieste logiche che InnoDB non può soddisfare dal buffer pool e che devono fare una lettura di una pagina singola.';
$strShowStatusInnodb_buffer_pool_wait_freeDescr = 'Normalmente le sritture nel buffer pool InnoDB vengono effettuate in background. Tuttavia se è necessario leggere o creare una pagina, e non sono disponibile pagine pulite è necessario attendere che le pagine siano aggiornate prima. Questo contatore conta le istanze di queste attese. Se la dimesione del buffer pool è stata settata correttamente questo valore dovrebbe essere basso.';
$strShowStatusInnodb_buffer_pool_write_requestsDescr = 'Il numero di scritture effettuate nel buffer pool InnoDB.';
$strShowStatusInnodb_data_fsyncsDescr = 'Il numero delle operazioni fsync() fino ad ora.';
$strShowStatusInnodb_data_pending_fsyncsDescr = 'Il numero di operazioni fsync() in attesa.';
$strShowStatusInnodb_data_pending_readsDescr = 'Il numero di letture in attesa.';
$strShowStatusInnodb_data_pending_writesDescr = 'Il numero di scritture in attesa.';
$strShowStatusInnodb_data_readDescr = 'La quantità di dati letti fino ad ora, in bytes.';
$strShowStatusInnodb_data_readsDescr = 'Il numero totale di dati letti.';
$strShowStatusInnodb_data_writesDescr = 'Il numero totale di dati scritti.';
$strShowStatusInnodb_data_writtenDescr = 'La quantità di dati scritti fino ad ora, in bytes.';
$strShowStatusInnodb_dblwr_pages_writtenDescr = 'Il numero di scritture doublewrite che sono state eseguite ed il numero che sono state scritte a questo scopo.';
$strShowStatusInnodb_dblwr_writesDescr = 'Il numero di scritture doublewrite che sono state eseguite ed il numero che sono state scritte a questo scopo.';
$strShowStatusInnodb_log_waitsDescr = 'Il numero di attese che abbiamo avuto perchè il buffer di log era troppo piccolo e abbiamo duvuto attendere che fosse aggiornato prima di continuare.';
$strShowStatusInnodb_log_write_requestsDescr = 'Il numero di richieste di scrittura dei log.';
$strShowStatusInnodb_log_writesDescr = 'Il numero scritture fisiche del log file.';
$strShowStatusInnodb_os_log_fsyncsDescr = 'Il numero di scritture fsync fatte sul log file.';
$strShowStatusInnodb_os_log_pending_fsyncsDescr = 'Il numero degli fsyncs in sospeso sul log file.';
$strShowStatusInnodb_os_log_pending_writesDescr = 'Il numero di scritture in sospeso sul log file.';
$strShowStatusInnodb_os_log_writtenDescr = 'Il numero di bytes scritti sul log file.';
$strShowStatusInnodb_pages_createdDescr = 'Il numero di pagine create.';
$strShowStatusInnodb_page_sizeDescr = 'La dimesione di-compilazione delle pagine InnoDB (default 16KB). Molti valori sono conteggiati nelle pagine; la dimesione delle pagine permette di convertirli facilmente in bytes.';
$strShowStatusInnodb_pages_readDescr = 'Il numero di pagine lette.';
$strShowStatusInnodb_pages_writtenDescr = 'Il numero di pagine scritte.';
$strShowStatusInnodb_row_lock_current_waitsDescr = 'Il numero di row locks attualmente in attesa.';
$strShowStatusInnodb_row_lock_time_avgDescr = 'Il tempo medio per l\'acquisizione di un row lock, in millisecondi.';
$strShowStatusInnodb_row_lock_timeDescr = 'Il tempo totale per l\'acquisizione di un row locks, in millisecondi.';
$strShowStatusInnodb_row_lock_time_maxDescr = 'Il tempo massimo per l\'acquisizione di un row lock, in millisecondi.';
$strShowStatusInnodb_row_lock_waitsDescr = 'Il numero di volte che un row lock ha dovuto attendere.';
$strShowStatusInnodb_rows_deletedDescr = 'Il numero di righe cancellate da una tabella InnoDB.';
$strShowStatusInnodb_rows_insertedDescr = 'Il numero di righe inserite da una tabella InnoDB.';
$strShowStatusInnodb_rows_readDescr = 'Il numero di righe lette da una tabella InnoDB.';
$strShowStatusInnodb_rows_updatedDescr = 'Il numero di righe aggiornate da una tabella InnoDB.';
$strShowStatusKey_blocks_not_flushedDescr = 'Il numero di blocchi chaive aggiunti nella cache chiave che sono stati cambiati, ma che non sono stai aggiornati su disco. E\' conosciuto con il nome di Not_flushed_key_blocks.';
$strShowStatusKey_blocks_unusedDescr = 'Il numero di blocchi non usati nella cache chiave. Puoi usare questo valore per determinare quanta cache chiave è in uso.';
$strShowStatusKey_blocks_usedDescr = 'Il numero di blocchi usati nella cache chiave. The number of used blocks in the key cache. Questo valore è un\'importante segnale che indica il numero massimo di blocchi che sono stati in uso contemporaneamente.';
$strShowStatusKey_read_requestsDescr = 'Il numero di richieste per le ggere un blocco chiave dalla cache.';
$strShowStatusKey_readsDescr = 'Il numero di letture fisiche dal disco di un blocco chiave. Se Key_reads è grande allora il valore key_buffer_size è probabilmente troppo piccolo. IIl rapporto di cache miss rate può essere calcolato come Key_reads/Key_read_requests.';
$strShowStatusKey_write_requestsDescr = 'Il numero di richieste per scrivere una blocco chiave nella cache.';
$strShowStatusKey_writesDescr = 'Il numero di scritture fisiche di un blocco chiave sul disco.';
$strShowStatusLast_query_costDescr = 'Il costo totale dell\'ultima query compilata così come computato dall\'ottimizzatore delle query. Utile per comparare il costo di differenti query per la stessa operazione di query. Il valore di default è 0, che significa che nessuna query è stata ancora compilata.';
$strShowStatusNot_flushed_delayed_rowsDescr = 'In numero di righe in attesa di essere scritte nella coda INSERT DELAYED.';
$strShowStatusOpened_tablesDescr = 'Il numero di tabelle che sono state aperte. Se il valore opened_tables è grande, probabilmente il valore di table cache è troppo piccolo.';
$strShowStatusOpen_filesDescr = 'Il numero di file che sono aperti.';
$strShowStatusOpen_streamsDescr = 'il numero di stream che sono aperti (usato principalmente per il logging).';
$strShowStatusOpen_tablesDescr = 'Il numero di tabelle che sono aperte.';
$strShowStatusQcache_free_blocksDescr = 'Il numero di blocchi di memoria liberi nella cache delle query.';
$strShowStatusQcache_free_memoryDescr = 'L\'ammontare di memoria libera nella cache delle query.';
$strShowStatusQcache_hitsDescr = 'Il numero di cache hits.';
$strShowStatusQcache_insertsDescr = 'Il numero di query aggiunte alla cache.';
$strShowStatusQcache_lowmem_prunesDescr = 'Il numero di query che sono state rimosse dalla cache per liberare memoria per la cache di nuove query. Questa informazione può aiutarti per parametrare la dimensione della cache delle query. La cache delle query usa una strategia di "meno usate recentemente" (LRU - least recently used) per decidere quali query rimuovere dalla cache.';
$strShowStatusQcache_not_cachedDescr = 'Il numero di query non in cache (impossibilità di inserirle nella cache oppure non inserite per i settaggi del parametro query_cache_type).';
$strShowStatusQcache_queries_in_cacheDescr = 'Il numero di query registrate nella cache.';
$strShowStatusQcache_total_blocksDescr = 'Il numero totale di blocchi nella cache delle query.';
$strShowStatusReset = 'Reset';
$strShowStatusRpl_statusDescr = 'Lo sato delle repliche failsafe (non ancora implementato).';
$strShowStatusSelect_full_joinDescr = 'Il numero di joins che non usano gli indici. (Se questo valore non è 0, dovresti controllare attentamente gli indici delle tue tabelle.)';
$strShowStatusSelect_full_range_joinDescr = 'Il numero di joins che usano una ricerca limitata su di una tabella di riferimento.';
$strShowStatusSelect_range_checkDescr = 'Il numero di joins senza chiavi che controllano per l\'uso di una chiave dopo ogni riga. (Se questo valore non è 0, dovresti controllare attentamente gli indici delle tue tabelle.)';
$strShowStatusSelect_rangeDescr = 'Il numero di joins che usano un range sulla prima tabella. (Non è, solitamente, un valore critico anche se è grande.)';
$strShowStatusSelect_scanDescr = 'Il numero di join che hanno effettuato una scansione completa della prima tabella.';
$strShowStatusSlave_open_temp_tablesDescr = 'Il numero di tabelle temporaneamente aperte da processi SQL slave.';
$strShowStatusSlave_retried_transactionsDescr = 'Numero totale di volte (dalla partenza) in cui la replica slave SQL ha ritentato una transazione.';
$strShowStatusSlave_runningDescr = 'Questa chiave è ON se questo è un server slave connesso ad un server master.';
$strShowStatusSlow_launch_threadsDescr = 'Numero di processi che hanno impiegato più di "slow_launch_time" secondi per partire.';
$strShowStatusSlow_queriesDescr = 'Numero di query che hanno impiegato più di "long_query_time" seconds.';
$strShowStatusSort_merge_passesDescr = 'Il numero di fusioni passate all\'algoritmo di ordianemento che sono state fatte. Se questo valore è grande, dovresti incrementare la variabile di sistema sort_buffer_size.';
$strShowStatusSort_rangeDescr = 'Il numero di ordinamenti che sono stati eseguiti in un intervallo.';
$strShowStatusSort_rowsDescr = 'Il numero di righe ordinate.';
$strShowStatusSort_scanDescr = 'Il numero di ordinamenti che sono stati fatti leggendo la tabella.';
$strShowStatusTable_locks_immediateDescr = 'Il numero di volte che un table lock è stato eseguito immediatamente.';
$strShowStatusTable_locks_waitedDescr = 'Il numero di volte che un table lock è stato eseguito immediatamente ed era necessaria un\'attesa. Se è alto, potresti avere dei problemi con le performance, dovresti prima ottimizzare le query, oppure sia utilizzare le repliche, sia dividere le tabelle.';
$strShowStatusThreads_cachedDescr = 'Il numero dei processi nella cache dei processi. L\'hit rate della cache può essere calcolato come processi_creati/connessioni. Se questo valore è rosso devi aumentare la tua thread_cache_size.';
$strShowStatusThreads_connectedDescr = 'Il numero di connessioni correntemente aperte.';
$strShowStatusThreads_createdDescr = 'Il numero di processi creati per gestire le connessioni. Se Threads_created è grosso, devi probabilmente aumentare il valore thread_cache_size. (Normalmente questo non fornisce un significatico incremento delle performace se hai una buona implementazione dei processi.)';
$strShowStatusThreads_runningDescr = 'Il numero di processi non in attesa.';
$strShowTableDimension = 'Mostra la dimensione delle tabelle';
$strShowTables = 'Mostra le tabelle';
$strShowThisQuery = 'Mostra questa query di nuovo';
$strSimplifiedChinese = 'Cinese Semplificato';
$strSingly = '(singolarmente)';
$strSize = 'Dimensione';
$strSkipQueries = 'Numero di record (query) da saltare a partire dall\'inizio';
$strSlovak = 'Slovacco';
$strSlovenian = 'Sloveno';
$strSmallBigAll = 'Piccolo/grande';
$strSnapToGrid = 'Calamita alla griglia';
$strSocketProblem = '(o il socket del server locale MySQL non è correttamente configurato)';
$strSortByKey = 'Ordina per chiave';
$strSorting = 'Ordinando';
$strSort = 'Ordinamento';
$strSpaceUsage = 'Spazio utilizzato';
$strSpanish = 'Spagnolo';
$strSplitWordsWithSpace = 'Le parole sono spezzate sulle spaziature (" ").';
$strSQLCompatibility = 'Modo di compatibilità SQL';
$strSQLExportType = 'Tipo di esportazione';
$strSQLParserBugMessage = 'C\'è la possibilità che ci sia un bug nel parser SQL. Per favore, esaminate la query accuratamente, e controllate che le virgolette siano corrette e non sbagliate. Altre possibili cause d\'errori possono essere che si stia cercando di uploadare un file binario al di fuori di un\'area di testo virgolettata. Si può anche provare la query MySQL dalla riga di comando di MySQL. L\'errore qui sotto restituito dal server MySQL, se ce n\'è uno, può anche aiutare nella diagnostica del problema. Se ci sono ancora problemi, o se il parser SQL di phpMyAdmin sbaglia quando invece l\'interfaccia a riga di comando non mostra problemi, si può ridurre la query SQL in ingresso alla singola query che causa problemi, e inviare un bug report con i dati riportati nella sezione CUT qui sotto:';
$strSQLParserUserError = 'Pare che ci sia un errore nella query SQL immessa. L\'errore del server MySQL mostrato qui sotto, se c\'è, può anche aiutare nella risoluzione del problema';
$strSQLQuery = 'query SQL';
$strSQLResult = 'Risultato SQL';
$strSQL = 'SQL';
$strSQPBugInvalidIdentifer = 'Identificatore Non Valido';
$strSQPBugUnclosedQuote = 'Virgolette Non Chiuse';
$strSQPBugUnknownPunctuation = 'Stringa di Punctuation Sconosciuta';
$strStandInStructureForView = 'Struttura Stand-in per le viste';
$strStatCheckTime = 'Ultimo controllo';
$strStatCreateTime = 'Creazione';
$strStatement = 'Istruzioni';
$strStatisticsOverrun = 'Su di un server sovraccarico, il contatore dei bytes potrebbe incrementarsi, e per questa ragione le statistiche riportate dal server MySQL potrebbero non essere corrette.';
$strStatUpdateTime = 'Ultimo cambiamento';
$strStatus = 'Stato';
$strStorageEngine = 'Motore di Memorizzazione';
$strStorageEngines = 'Motori di Memorizzazione';
$strStrucCSV = 'dati CSV';
$strStrucData = 'Struttura e dati';
$strStrucExcelCSV = 'CSV per dati MS Excel';
$strStrucNativeExcel = 'Dati nativi di MS Excel';
$strStrucOnly = 'Solo struttura';
$strStructPropose = 'Proponi la struttura della tabella';
$strStructureForView = 'Struttura per la vista';
$strStructure = 'Struttura';
$strSubmit = 'Invia';
$strSuccess = 'La query è stata eseguita con successo';
$strSuhosin = 'Sul server è in esecuzione Suhosin. Controlla la documentazione: %sdocumentation%s per possibili problemi.';
$strSum = 'Totali';
$strSwedish = 'Svedese';
$strSwitchToDatabase = 'Passare al Database copiato';
$strSwitchToTable = 'Passa alla tabella copiata';
$strTableAlreadyExists = 'La tabella %s esiste già!';
$strTableComments = 'Commenti sulla tabella';
$strTableEmpty = 'Il nome della tabella è vuoto!';
$strTableHasBeenDropped = 'La tabella %s è stata eliminata';
$strTableHasBeenEmptied = 'La tabella %s è stata svuotata';
$strTableHasBeenFlushed = 'La tabella %s è stata inizializzata';
$strTableIsEmpty = 'La tabella sembra essere vuota!';
$strTableMaintenance = 'Amministrazione tabella';
$strTableName = 'Nome tabella';
$strTableOfContents = 'Tabella dei contenuti';
$strTableOptions = 'Opzioni della tabella';
$strTables = '%s tabella(e)';
$strTableStructure = 'Struttura della tabella';
$strTable = 'Tabella';
$strTakeIt = 'prendilo';
$strTblPrivileges = 'Privilegi relativi alle tabelle';
$strTempData = 'Dati temporanei';
$strTextAreaLength = ' A causa della sua lunghezza,<br /> questo campo non può essere modificato ';
$strThai = 'Thai';
$strThemeDefaultNotFound = 'Tema di default %s non trovato!';
$strThemeNoPreviewAvailable = 'Nessuna preview disponibile.';
$strThemeNotFound = 'Tema %s non trovato!';
$strThemeNoValidImgPath = 'Nessun percorso per le immagini per il tema %s trovato!';
$strThemePathNotFound = 'Percorso per il tema non trovato %s!';
$strTheme = 'Tema / Stile';
$strThisHost = 'Questo Host';
$strThreads = 'Processi';
$strThreadSuccessfullyKilled = 'Il thread %s è stato terminato con successo.';
$strTimeoutInfo = 'Una precedente importazione è entrata in timeout, dopo un nuovo inoltro riprenderà dalla posizione: %d.';
$strTimeoutNothingParsed = 'Nell\'ultima esecuzione nessun dato è stato processato, questo, solitamente, vuole dire che che phpMyAdmin non è in grado di ultimare l\'operazione fino a che non verrà aumentato il parametro php time limits.';
$strTimeoutPassed = 'Superato il tempo limite dello script, se vuoi finire l\'importazione inoltra nuovamente il file e il processo riprenderà.';
$strTime = 'Tempo';
$strToFromPage = 'da/per pagina';
$strToggleScratchboard = '(dis)attiva scratchboard';
$strToggleSmallBig = 'Cambia grande/piccolo';
$strToSelectRelation = 'Per selezionare una relazione, click :';
$strTotal = 'Totali';
$strTotalUC = 'Totale';
$strTraditionalChinese = 'Cinese Tradizionale';
$strTraditionalSpanish = 'Spagnolo tradizionale';
$strTraffic = 'Traffico';
$strTransactionCoordinator = 'Coordinatore delle transazioni';
$strTransformation_application_octetstream__download = 'Visualizza un collegamento per trasferire i dati di un campo in formato binario. La prima opzione è il nome del file binario. La seconda opzione è un nome di campo possibile di una riga della tabella che contiene il nome di schedario. Se fornite una seconda opzione dovete avere la prima opzione settata ad una stringa vuota';
$strTransformation_application_octetstream__hex = 'Mostra una rappresentazione esadecimale dei dati. Il primo parametro, opzionale, specifica ogni quanto deve essere aggiunto uno spazio (default a 2 nibbles).';
$strTransformation_image_jpeg__inline = 'Mostra un thumbnalil cliccabile; opzioni: larghezza,altezza in pixel (mantiere la proporzione iniziale)';
$strTransformation_image_jpeg__link = 'Mostra un link a questa immagine (download blob diretto, i.e.).';
$strTransformation_image_png__inline = 'Vedi immagine/jpeg: inline';
$strTransformation_text_plain__dateformat = 'Mostra i campi TIME, TIMESTAMP, DATETIME o il TIMESTAMP UNIX come data formattata. La prima opzione è l\'offset (in ore) che verrà aggiunto all\'ora (Default: 0). Usare la seconda opzione per specificare un differente formato di data/ora. La terza opzione determina se vuoi vedere l\'ora locale o UTC (usa "local" o "utc" per questo). In relazione a questo, il formato data ha differenti valori - per "local" guarda la documentazione della funzione PHP strftime(); per "utc" viene usata la funzione gmdate().';
$strTransformation_text_plain__external = 'SOLO PER LINUX: Lancia un\'applicazione esterna e riempie i dati dei campi tramite lo standard input. Restituisce lo standard output dell\'applicazione. L\'impostazione predefinita è Tidy, per stampare in maniera corretta il codice HTML. Per motivi di sicurezza, dovete editare manualmente il file libraries/transformations/text_plain__external.inc.php e inserire gli strumenti che permettete di utilizzare. La prima opzione è così il numero del programma che volete utilizzare e la seconda sono i parametri per il programma. Il terzo parametro, se impostato a 1 convertirà l\'output utilizzando htmlspecialchars() (Predefinito: 1). Un quarto parametro, se impostato a 1 inserirà un NOWRAP al contenuto della cella così che l\'intero output sarà mostrato senza essere riformattato (Predefinito: 1)';
$strTransformation_text_plain__formatted = 'Preserva l\'originale formattazione del campo. Nessun Escaping viene applicato.';
$strTransformation_text_plain__imagelink = 'Mostra un collegamento ad una immagine esterna; il campo contiene il nome del file; la prima opzione è un prefisso come "http://tuodominio.com/", la seconda opzione è la larghezza in pixel, la terza è l\'altezza.';
$strTransformation_text_plain__link = 'Mostra un collegamento, il campo contiene il nome del file; la prima opzione è un prefisso come "http://tuodominio.com/", la seconda opzione è un titolo per il collegamento.';
$strTransformation_text_plain__sql = 'Formatta il testo come query SQL con evidenziazione della sintassi.';
$strTransformation_text_plain__substr = 'Mostra soltanto una parte della stringa. La prima opzione è l\'offset che serve a definire dove inizia l\'output del vostro testo (Prefinito: 0). La seconda opzione è un offset che indica quanto testo viene restituito. Se vuoto, restituisce tutto il testo rimanente. La terza opzione definisce quali caratteri saranno aggiunti in fondo all\'output quando una soptto-stringa viene restituita (Predefinito: ...) .';
$strTriggers = 'Triggers';
$strTruncateQueries = 'Tronca le Query Mostrate';
$strTurkish = 'Turco';
$strType = 'Tipo';
$strUkrainian = 'Ucraino';
$strUncheckAll = 'Deseleziona tutti';
$strUnicode = 'Unicode';
$strUnique = 'Unica';
$strUnknown = 'sconosciuto';
$strUnselectAll = 'Deseleziona Tutto';
$strUnsupportedCompressionDetected = 'Stai cercando di importare un file con un tipo di compressione non supportato. Altrimenti il supporto per questo tipo di compressione non è stato ancora implementato o è stato disabilitato dalla tua configurazione.';
$strUpdatePrivMessage = 'Hai aggiornato i permessi per %s.';
$strUpdateProfileMessage = 'Il profilo è stato aggiornato.';
$strUpdateQuery = 'Aggiorna Query';
$strUpdComTab = 'Prego leggere la documentazione su come aggiornare la vostra tabella Column_comments';
$strUpgrade = 'Si dovrebbe aggiornare %s alla versione %s o successiva.';
$strUploadErrorCantWrite = 'Non riesco a scrivere il file su disco.';
$strUploadErrorExtension = 'Caricamento del file interrotto per estensione errata.';
$strUploadErrorFormSize = 'Il file caricato eccede il parametro MAX_FILE_SIZE specificato nel form HTML.';
$strUploadErrorIniSize = 'Il file caricato eccede il parametro upload_max_filesize in php.ini.';
$strUploadErrorNoTempDir = 'Non trovo la cartella temporanea.';
$strUploadErrorPartial = 'Il file è stato solo parzialmente caricato.';
$strUploadErrorUnknown = 'Errore sconosciuto nel caricamento del file.';
$strUploadLimit = 'Stai probabilmente cercando di uplodare un file troppo grosso. Fai riferimento alla documentazione %sdocumentation%s Per i modi di aggirare questo limite.';
$strUploadsNotAllowed = 'Non è permesso l\'upload dei file su questo server.';
$strUsage = 'Utilizzo';
$strUseBackquotes = 'Usa i backquotes con i nomi delle tabelle e dei campi';
$strUsedPhpExtensions = 'Estensioni PHP usate';
$strUseHostTable = 'Utilizza la Tabella dell\'Host';
$strUserAlreadyExists = 'L\'utente %s esiste già!';
$strUserEmpty = 'Il nome utente è vuoto!';
$strUserName = 'Nome utente';
$strUserNotFound = 'L\'utente selezionato non è stato trovato nella tabella dei privilegi.';
$strUserOverview = 'Vista d\'insieme dell\'utente';
$strUsersDeleted = 'Gli utenti selezionati sono stati cancellati con successo.';
$strUsersHavingAccessToDb = 'Utenti che hanno accesso a "%s"';
$strUser = 'Utente';
$strUseTabKey = 'Usare il tasto TAB per spostare il cursore di valore in valore, o CTRL+frecce per spostarlo altrove';
$strUseTables = 'Utilizza tabelle';
$strUseTextField = 'Utilizza campo text';
$strUseThisValue = 'Usa questa opzione';
$strValidateSQL = 'Valida SQL';
$strValidatorError = 'L\' SQL validator non può essere inizializzato. Prego controllare di avere installato le estensioni php necessarie come descritto nella %sdocumentazione%s.';
$strValue = 'Valore';
$strVar = 'Variabile';
$strVersionInformation = 'Informazioni sulla versione';
$strViewDumpDatabases = 'Visualizza il dump (schema) dei databases';
$strViewDumpDB = 'Visualizza dump (schema) del database';
$strViewDump = 'Visualizza dump (schema) della tabella';
$strViewHasBeenDropped = 'La vista %s è stata eliminata';
$strViewMaxExactCount = 'Questa vista ha più di %d righe. Per informazioni fare riferimento a %sdocumentation%s.';
$strViewName = 'Nome VISTA';
$strView = 'Vista';
$strWebServerUploadDirectory = 'directory di upload del web-server';
$strWebServerUploadDirectoryError = 'La directory impostata per l\'upload non può essere trovata';
$strWelcome = 'Benvenuto in %s';
$strWestEuropean = 'Europeo Occidentale';
$strWildcard = 'wildcard';
$strWindowNotFound = 'La finestra destinataria del browser non può essere aggiornata. Può darsi che sia stata chiusa la finestra madre o che il vostro browser stia bloccando gli aggiornamenti fra browsers a causa di qualche impostazione di sicurezza';
$strWithChecked = 'Se selezionati:';
$strWriteRequests = 'Richieste di scrittura';
$strWrongUser = 'Nome utente o password errati. Accesso negato.';
$strXML = 'XML';
$strYes = 'Sì';
$strZeroRemovesTheLimit = 'N.B.: 0 (zero) significa nessun limite.';
$strZip = '"compresso con zip"';
?>
| mwhitlaw/openemr | phpmyadmin/lang/italian-iso-8859-1.inc.php | PHP | gpl-2.0 | 70,896 |
/* Copyright (c) 2003, 2005 MySQL AB
Use is subject to license terms
This program 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; version 2 of the License.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
/**
* @file SQLTransactTest.cpp
*/
#include <common.hpp>
#define STR_MESSAGE_LENGTH 200
#define STR_NAME_LEN 20
#define STR_PHONE_LEN 20
#define STR_ADDRESS_LEN 20
using namespace std;
SQLHDBC STR_hdbc;
SQLHSTMT STR_hstmt;
SQLHENV STR_henv;
SQLHDESC STR_hdesc;
void Transact_DisplayError(SQLSMALLINT STR_HandleType,
SQLHSTMT STR_InputHandle);
int STR_Display_Result(SQLHSTMT EXDR_InputHandle);
/**
* Test:
* -#Test to request a commit or a rollback operation for
* all active transactions associated with a specific
* environment or connection handle
*
* @return Zero, if test succeeded
*/
int SQLTransactTest()
{
SQLRETURN STR_ret;
ndbout << endl << "Start SQLTransact Testing" << endl;
//************************************
//** Allocate An Environment Handle **
//************************************
STR_ret = SQLAllocHandle(SQL_HANDLE_ENV,
SQL_NULL_HANDLE,
&STR_henv);
if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO)
ndbout << "Allocated an environment Handle!" << endl;
//*********************************************
//** Set the ODBC application Version to 3.x **
//*********************************************
STR_ret = SQLSetEnvAttr(STR_henv,
SQL_ATTR_ODBC_VERSION,
(SQLPOINTER) SQL_OV_ODBC3,
SQL_IS_UINTEGER);
if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO)
ndbout << "Set the ODBC application Version to 3.x!" << endl;
//**********************************
//** Allocate A Connection Handle **
//**********************************
STR_ret = SQLAllocHandle(SQL_HANDLE_DBC,
STR_henv,
&STR_hdbc);
if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO)
ndbout << "Allocated a connection Handle!" << endl;
// *******************
// ** Connect to DB **
// *******************
STR_ret = SQLConnect(STR_hdbc,
(SQLCHAR *) connectString(),
SQL_NTS,
(SQLCHAR *) "",
SQL_NTS,
(SQLCHAR *) "",
SQL_NTS);
if (STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO)
ndbout << "Connected to DB : OK!" << endl;
else
{
ndbout << "Failure to Connect DB!" << endl;
return NDBT_FAILED;
}
//*******************************
//** Allocate statement handle **
//*******************************
STR_ret = SQLAllocHandle(SQL_HANDLE_STMT,
STR_hdbc,
&STR_hstmt);
if(STR_ret == SQL_SUCCESS || STR_ret == SQL_SUCCESS_WITH_INFO)
ndbout << "Allocated a statement handle!" << endl;
//********************************
//** Turn Manual-Commit Mode On **
//********************************
STR_ret = SQLSetConnectOption(STR_hdbc,
SQL_AUTOCOMMIT,
(UDWORD) SQL_AUTOCOMMIT_OFF);
//**********************************************
//** Prepare and Execute a prepared statement **
//**********************************************
STR_ret = SQLExecDirect(STR_hstmt,
(SQLCHAR*)"SELECT * FROM Customers",
SQL_NTS);
if (STR_ret == SQL_INVALID_HANDLE)
{
ndbout << "Handle Type is SQL_HANDLE_STMT, but SQL_INVALID_HANDLE"
<< endl;
ndbout << "still appeared. Please check program" << endl;
}
if (STR_ret == SQL_ERROR || STR_ret == SQL_SUCCESS_WITH_INFO)
Transact_DisplayError(SQL_HANDLE_STMT, STR_hstmt);
//*************************
//** Display the results **
//*************************
STR_Display_Result(STR_hstmt);
//****************************
//** Commit the transaction **
//****************************
STR_ret = SQLTransact(STR_henv,
STR_hdbc,
SQL_COMMIT);
//****************
// Free Handles **
//****************
SQLDisconnect(STR_hdbc);
SQLFreeHandle(SQL_HANDLE_STMT, STR_hstmt);
SQLFreeHandle(SQL_HANDLE_DBC, STR_hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, STR_henv);
return NDBT_OK;
}
void Transact_DisplayError(SQLSMALLINT STR_HandleType,
SQLHSTMT STR_InputHandle)
{
SQLCHAR STR_Sqlstate[5];
SQLINTEGER STR_NativeError;
SQLSMALLINT STR_i, STR_MsgLen;
SQLCHAR STR_Msg[STR_MESSAGE_LENGTH];
SQLRETURN SQLSTATEs;
STR_i = 1;
ndbout << "-------------------------------------------------" << endl;
ndbout << "Error diagnostics:" << endl;
while ((SQLSTATEs = SQLGetDiagRec(STR_HandleType,
STR_InputHandle,
STR_i,
STR_Sqlstate,
&STR_NativeError,
STR_Msg,
sizeof(STR_Msg),
&STR_MsgLen))
!= SQL_NO_DATA) {
ndbout << "the HandleType is:" << STR_HandleType << endl;
ndbout << "the InputHandle is :" << (long)STR_InputHandle << endl;
ndbout << "the STR_Msg is: " << (char *) STR_Msg << endl;
ndbout << "the output state is:" << (char *)STR_Sqlstate << endl;
STR_i ++;
// break;
}
ndbout << "-------------------------------------------------" << endl;
}
int STR_Display_Result(SQLHSTMT STR_InputHandle)
{
SQLRETURN STR_retcode;
unsigned long STR_CustID;
SQLCHAR STR_Name[STR_NAME_LEN], STR_Phone[STR_PHONE_LEN];
SQLCHAR STR_Address[STR_ADDRESS_LEN];
//*********************
//** Bind columns 1 **
//*********************
STR_retcode =SQLBindCol(STR_InputHandle,
1,
SQL_C_ULONG,
&STR_CustID,
sizeof(STR_CustID),
NULL);
if (STR_retcode == SQL_ERROR)
{
ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
return NDBT_FAILED;
}
//*********************
//** Bind columns 2 **
//*********************
STR_retcode =SQLBindCol(STR_InputHandle,
2,
SQL_C_CHAR,
&STR_Name,
STR_NAME_LEN,
NULL);
if (STR_retcode == SQL_ERROR)
{
ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
return NDBT_FAILED;
}
//*********************
//** Bind columns 3 **
//*********************
STR_retcode = SQLBindCol(STR_InputHandle,
3,
SQL_C_CHAR,
&STR_Address,
STR_ADDRESS_LEN,
NULL);
if (STR_retcode == SQL_ERROR)
{
ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
return NDBT_FAILED;
}
//*********************
//** Bind columns 4 **
//*********************
STR_retcode = SQLBindCol(STR_InputHandle,
4,
SQL_C_CHAR,
&STR_Phone,
STR_PHONE_LEN,
NULL);
if (STR_retcode == SQL_ERROR)
{
ndbout << "Executing SQLBindCol, SQL_ERROR happened!" << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
return NDBT_FAILED;
}
//*****************************************
//* Fetch and print each row of data. On **
//* an error, display a message and exit **
//*****************************************
if (STR_retcode != SQL_ERROR)
STR_retcode = SQLFetch(STR_InputHandle);
ndbout << endl << "STR_retcode = SQLFetch(STR_InputHandle) = "
<< STR_retcode << endl;
if (STR_retcode == SQL_ERROR)
{
ndbout << "Executing SQLFetch, SQL_ERROR happened!" << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
return NDBT_FAILED;
}
else if (STR_retcode == SQL_SUCCESS_WITH_INFO)
{
ndbout << "CustID = " << (int)STR_CustID << endl;
ndbout << "Name = " << (char *)STR_Name << endl;
ndbout << "Address = " << (char *)STR_Address << endl;
ndbout << "Phone = " << (char *)STR_Phone << endl;
Transact_DisplayError(SQL_HANDLE_STMT, STR_InputHandle);
}
else
{
ndbout << "CustID = " << (int)STR_CustID << endl;
ndbout << "Name = " << (char *)STR_Name << endl;
ndbout << "Address = " << (char *)STR_Address << endl;
ndbout << "Phone = " << (char *)STR_Phone << endl;
}
return 0;
}
| fengshao0907/mysql | storage/ndb/test/odbc/client/SQLTransactTest.cpp | C++ | gpl-2.0 | 8,798 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.chaos.actions;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.chaos.monkies.PolicyBasedChaosMonkey;
/**
* Action that restarts a random HRegionServer
*/
public class RestartRandomRsAction extends RestartActionBaseAction {
public RestartRandomRsAction(long sleepTime) {
super(sleepTime);
}
@Override
public void perform() throws Exception {
LOG.info("Performing action: Restart random region server");
ServerName server = PolicyBasedChaosMonkey.selectRandomItem(getCurrentServers());
restartRs(server, sleepTime);
}
}
| Guavus/hbase | hbase-it/src/test/java/org/apache/hadoop/hbase/chaos/actions/RestartRandomRsAction.java | Java | apache-2.0 | 1,416 |